ai_co_discuss 0.3.8 → 0.3.10

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.
@@ -1,1961 +1,2274 @@
1
- """Free collaboration rooms: member credentials, durable requests and per-member executions.
2
-
3
- A free room has no floor, turns or rounds. The user (holding the room control credential)
4
- names members; each named member gets one durable request per message. The local runner
5
- delivers a runner member's open requests as one execution, and the member's answer completes
6
- them. A manual member finds its own requests and answers by request id; an online member's
7
- answer is forwarded by the owner. The user is the client, never the host: one member that
8
- answers by itself always hosts, routes unnamed messages, names members in its answers, and is
9
- woken once when everything it dispatched has finished. No software is launched here.
10
- """
11
-
12
- import hashlib
13
- import hmac
14
- import json
15
- import re
16
- import time
17
- import uuid
18
-
19
- from .identity import MAX_ROOM_AGENTS, is_ai
20
- from .runtime import (LEASE_SECONDS, MAX_EXECUTION_SEGMENTS, begin_write, enforce_session_limits,
21
- require_owner, save_segments, token_hash)
22
-
23
- FREE_EXECUTION_MINUTES = 20
24
- RECENT_REQUESTS = 100
25
- RECENT_EXECUTIONS = 100
26
- # The timeline page reads this many recent executions of each kind; with `after` (?3) only those running or ended since.
27
- # Parameters: ?1 room, ?2 limit, ?3 after (0 reads all). Shared verbatim with the Worker.
28
- TIMELINE_EXECUTIONS = 100
29
- # Rounds used and allowed in the room's recent chains, for "第 2/3 轮"; parameters: the room's limit, the room.
30
- CHAIN_PROGRESS_SQL = """SELECT b.chain_id,COUNT(*) AS used,? + COALESCE((SELECT h.extra_rounds FROM free_chain_holds h
31
- WHERE h.room_id=b.room_id AND h.chain_id=b.chain_id),0) AS allowed FROM free_batches b WHERE b.room_id=?
32
- GROUP BY b.chain_id ORDER BY b.chain_id DESC LIMIT 10"""
33
- TIMELINE_STATES = {"completed": "done", "failed": "failed", "cancelled": "cancelled"}
34
- TIMELINE_FREE_IDS = "SELECT id FROM member_executions WHERE room_id=?1 AND (?3=0 OR finished_at=0 OR finished_at>=?3) ORDER BY id DESC LIMIT ?2"
35
- TIMELINE_DISCUSSION_IDS = """SELECT e.id FROM discussion_events e LEFT JOIN event_timings t ON t.event_id=e.id
36
- WHERE e.room_id=?1 AND (t.dispatched_at>0 OR e.status='pending') AND (?3=0 OR COALESCE(t.finished_at,0)=0 OR t.finished_at>=?3)
37
- ORDER BY e.id DESC LIMIT ?2"""
38
- # Besides times: the task an execution took on (its request message, or the discussion turn's question), its result
39
- # (the answer's summary, else the answer's opening), its latest progress note, how many files it changed (NULL when
40
- # unobserved), its last output time (free executions only) and the discussion run it belongs to (discussion only).
41
- TIMELINE_SQL = f"""SELECT x.*,(SELECT COALESCE(NULLIF(s.text,''),substr(a.text,1,200)) FROM messages a
42
- LEFT JOIN message_summaries s ON s.message_id=a.id WHERE a.id=x.answer_id) AS result FROM (
43
- SELECT 'free' AS source,e.id,m.name AS member,m.role,e.status,
44
- COALESCE((SELECT MIN(r.created_at) FROM member_requests r WHERE r.execution_id=e.id),e.created_at) AS queued_at,
45
- e.created_at AS dispatched_at,0 AS started_at,e.finished_at,
46
- CASE WHEN e.status='failed' THEN e.result ELSE '' END AS reason,
47
- (SELECT parent.execution_id FROM member_requests r JOIN member_requests parent ON parent.answer_id=r.message_id
48
- WHERE r.execution_id=e.id AND parent.execution_id IS NOT NULL ORDER BY r.id LIMIT 1) AS parent_id,
49
- e.activity_at,(SELECT MIN(r.message_id) FROM member_requests r WHERE r.execution_id=e.id) AS task_id,
50
- (SELECT substr(q.text,1,160) FROM messages q WHERE q.id=(SELECT MIN(r.message_id) FROM member_requests r WHERE r.execution_id=e.id)) AS task,
51
- (SELECT MAX(r.answer_id) FROM member_requests r WHERE r.execution_id=e.id) AS answer_id,
52
- (SELECT n.text FROM execution_notes n WHERE n.execution_id=e.id ORDER BY n.seq DESC LIMIT 1) AS last_note,
53
- CASE WHEN e.changes='' THEN NULL ELSE json_array_length(e.changes) END AS changes,NULL AS run_id
54
- FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.id IN ({TIMELINE_FREE_IDS})
55
- UNION ALL SELECT 'discussion',e.id,e.participant,e.role,e.status,CAST(strftime('%s',e.created_at) AS INTEGER),
56
- COALESCE(t.dispatched_at,0),e.started_at,COALESCE(t.finished_at,0),CASE WHEN e.status='failed' THEN e.result ELSE '' END,NULL,
57
- 0,NULL,(SELECT substr(q.question,1,160) FROM discussion_turns q WHERE q.id=e.turn_id),
58
- CASE WHEN e.result LIKE 'message:%' THEN CAST(substr(e.result,9) AS INTEGER) END,NULL,NULL,e.run_id
59
- FROM discussion_events e LEFT JOIN event_timings t ON t.event_id=e.id WHERE e.id IN ({TIMELINE_DISCUSSION_IDS})) x"""
60
- TIMELINE_SEGMENTS_SQL = f"""SELECT source,execution_id,phase,tool,start_ms,end_ms FROM execution_segments WHERE room_id=?1 AND (
61
- (source='free' AND execution_id IN ({TIMELINE_FREE_IDS})) OR (source='discussion' AND execution_id IN ({TIMELINE_DISCUSSION_IDS})))
62
- ORDER BY source,execution_id,seq"""
63
- # Only the times of progress notes: the texts are read when the reader hovers one.
64
- TIMELINE_NOTES_SQL = f"""SELECT execution_id,created_at FROM execution_notes
65
- WHERE room_id=?1 AND execution_id IN ({TIMELINE_FREE_IDS}) ORDER BY execution_id,seq"""
66
- RECENT_CHANGES = 50
67
- MAX_CHANGED_FILES = 200
68
- # What a member's software last showed it doing, as reported by the runner with each renewal.
69
- ACTIVITY_PHASES = ("", "thinking", "command", "tool", "editing", "writing")
70
- # Progress notes per execution, their length, and how many one renewal may carry.
71
- MAX_EXECUTION_NOTES = 50
72
- MAX_NOTE_LENGTH = 500
73
- MAX_NOTES_PER_RENEW = 10
74
- # A member description is a short note for the scheduler and the host, keyed by the member's name.
75
- MAX_MEMBER_DESCRIPTION = 500
76
- # A display label replaces the member's name on screen only; the name stays the member's identity everywhere else.
77
- MAX_MEMBER_LABEL = 32
78
- MAX_MEMBER_NAME = 80
79
- MAX_PATH_LENGTH = 500
80
- # Refused operations one execution may report, and the length of each field.
81
- MAX_DENIALS = 20
82
- MAX_DENIAL_FIELD = 300
83
- # A manual member's delivery is retried at most this often before the execution fails.
84
- MAX_RETRIES = 3
85
- MAX_RETRY_REASON = 500
86
- ACTIVE = ("dispatched", "started")
87
- ACCESS_MODES = ("runner", "manual")
88
- LEGACY_ACCESS_MODES = ("runner", "manual", "online")
89
- SCHEDULER_PROVIDERS = ("jev", "decisions")
90
- RECOMMEND_SECONDS = 60
91
- # A click sent just before the hint disappears still counts.
92
- RECOMMEND_GRACE_SECONDS = 5
93
- # Rounds a host may run from one owner message by default (a round: one host dispatch, its members' answers and the
94
- # hand-back); each owner message starts a chain. Counted in rounds, so a room with more members gets no fewer of them.
95
- CHAIN_ROUNDS = 3
96
- # The most rounds an owner may allow per chain, or add at once when continuing a stopped chain.
97
- MAX_CHAIN_ROUNDS = 20
98
- # A host that left gives up the role; the first active runner member (else manual) then takes it.
99
- RELEASE_HOST = "UPDATE room_members SET role='member' WHERE room_id=? AND role='host' AND status<>'active'"
100
- ASSIGN_HOST = """UPDATE room_members SET role='host' WHERE id=(SELECT id FROM room_members WHERE room_id=? AND status='active'
101
- AND NOT EXISTS(SELECT 1 FROM member_manual_sources source WHERE source.member_id=room_members.id AND source.source='web')
102
- ORDER BY access='runner' DESC, id LIMIT 1)
103
- AND NOT EXISTS (SELECT 1 FROM room_members WHERE room_id=? AND role='host' AND status='active')"""
104
- TERMINAL = ("completed", "cancelled", "failed")
105
- # A queued member has been asked once its request for that message exists.
106
- QUEUE_ASKED = "EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id={row}.message_id AND r.member_id={row}.member_id)"
107
- SESSION_MODES = ("new", "borrowed")
108
- FREE_OPERATIONS = ("messages", "attachments", "move", "folder", "rename", "archive", "restore", "delete")
109
- MEMBER_FIELDS = ("id", "name", "adapter", "role", "status", "access", "session_mode", "read_until")
110
- EXECUTION_FIELDS = ("id", "member_id", "status", "session_id", "lease_until", "created_at", "finished_at", "result",
111
- "activity", "activity_at")
112
- # Columns added after the first free-room tables; Python databases created by that build gain them here.
113
- LATER_COLUMNS = {"room_members": {"access": "TEXT NOT NULL DEFAULT 'runner'", "session_mode": "TEXT NOT NULL DEFAULT 'new'"},
114
- "member_executions": {"changes": "TEXT NOT NULL DEFAULT ''", "cwd": "TEXT NOT NULL DEFAULT ''",
115
- "activity": "TEXT NOT NULL DEFAULT ''", "activity_at": "INTEGER NOT NULL DEFAULT 0"},
116
- "member_requests": {"chain_id": "INTEGER NOT NULL DEFAULT 0", "batch_id": "INTEGER NOT NULL DEFAULT 0",
117
- "purpose": "TEXT NOT NULL DEFAULT 'ask'", "created_by": "TEXT NOT NULL DEFAULT 'user'"}}
118
-
119
-
120
- def migrate_free_tables(connection):
121
- """Add columns that early free-room databases lack; repeated runs change nothing."""
122
- for table, columns in LATER_COLUMNS.items():
123
- present = {row[1] for row in connection.execute(f"PRAGMA table_info({table})")}
124
- for name, definition in columns.items():
125
- if name not in present:
126
- connection.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")
127
- connection.execute("""CREATE TABLE IF NOT EXISTS member_manual_sources (
128
- member_id INTEGER PRIMARY KEY REFERENCES room_members(id) ON DELETE CASCADE,
129
- source TEXT NOT NULL CHECK(source='web'))""")
130
- connection.execute("""INSERT OR IGNORE INTO member_manual_sources(member_id,source)
131
- SELECT id,'web' FROM room_members WHERE access='online'""")
132
- connection.execute("UPDATE room_members SET access='manual' WHERE access='online'")
133
- connection.execute("UPDATE room_modes SET mode='free' WHERE mode='brainstorm'")
134
-
135
-
136
- def room_mode(connection, room_id):
137
- """Return 'free' for free rooms; every legacy room is a brainstorm room."""
138
- row = connection.execute("SELECT mode FROM room_modes WHERE room_id=?", (room_id,)).fetchone()
139
- return row[0] if row else "brainstorm"
140
-
141
-
142
- def member_value(member):
143
- """Validate one member and its client-generated credential."""
144
- if not isinstance(member, dict) or not is_ai(member.get("name")):
145
- raise ValueError("成员须为有效 AI 身份")
146
- if not token_hash(member.get("token")):
147
- raise ValueError("每位成员须提供 32–256 字符的成员凭证")
148
- adapter = member.get("adapter", "")
149
- if not isinstance(adapter, str) or len(adapter) > 40:
150
- raise ValueError("成员适配器名称无效")
151
- access, session_mode = member.get("access", "runner"), member.get("session_mode", "new")
152
- if access not in LEGACY_ACCESS_MODES or session_mode not in SESSION_MODES:
153
- raise ValueError("成员接入方式须为 runner/manual/online,会话方式须为 new/borrowed")
154
- manual_source = member.get("manual_source", "")
155
- if access == "online":
156
- manual_source, access = "web", "manual"
157
- if manual_source not in ("", "web") or (manual_source == "web" and access != "manual"):
158
- raise ValueError("manual_source 只能为 manual 成员配置 web")
159
- return {"name": member["name"], "adapter": adapter, "token": member["token"],
160
- "access": access, "session_mode": session_mode, "manual_source": manual_source}
161
-
162
-
163
- def member_values(members):
164
- """Validate independent member credentials for a room."""
165
- if not isinstance(members, list) or not len(members) <= MAX_ROOM_AGENTS:
166
- raise ValueError("房间成员须为列表,且不超过成员上限")
167
- result = [member_value(member) for member in members]
168
- if len({member["name"] for member in result}) != len(result):
169
- raise ValueError("成员名称不能重复")
170
- if len({member["token"] for member in result}) != len(result):
171
- raise ValueError("每位成员须使用独立凭证")
172
- return result
173
-
174
-
175
- def insert_member(connection, room_id, member, now):
176
- """Store one member with only its credential hash."""
177
- connection.execute("""INSERT INTO room_members (room_id,name,adapter,token_hash,access,session_mode,created_at)
178
- VALUES (?,?,?,?,?,?,?)""", (room_id, member["name"], member["adapter"], token_hash(member["token"]),
179
- member["access"], member["session_mode"], now))
180
- if member.get("manual_source") == "web" or member.get("access") == "online":
181
- member_id = connection.execute("SELECT id FROM room_members WHERE room_id=? AND name=? AND token_hash=?",
182
- (room_id, member["name"], token_hash(member["token"]))).fetchone()[0]
183
- connection.execute("INSERT OR IGNORE INTO member_manual_sources(member_id,source) VALUES(?,'web')", (member_id,))
184
-
185
-
186
- def save_room_access(connection, room_id, control_token, members, settings):
187
- """Persist the mode, the owner's control hash and the members in the creating transaction."""
188
- control = token_hash(control_token)
189
- if not control:
190
- raise ValueError("建房须提供 32–256 字符的房间控制凭据")
191
- if any(token_hash(member["token"]) == control for member in members):
192
- raise ValueError("成员凭证不能与房主控制凭据相同")
193
- connection.execute("INSERT INTO room_modes (room_id,mode,control_hash) VALUES (?,?,?)", (room_id, settings["mode"], control))
194
- for member in members:
195
- insert_member(connection, room_id, member, settings["created_at"])
196
- connection.execute("UPDATE room_members SET role='host' WHERE room_id=? AND name=?", (room_id, settings["host"]))
197
-
198
-
199
- def discussion_access_ok(access, capability, automatic, is_host, manual_source=""):
200
- """Require web relays to stay read-only while local participants use runner or manual access."""
201
- if capability == "online":
202
- return access == "manual" and manual_source == "web" and not is_host
203
- if manual_source == "web":
204
- return False
205
- if not automatic:
206
- return access == "manual"
207
- return access == "runner" or (access == "manual" and not is_host)
208
-
209
-
210
- def mark_manual(member, automatic):
211
- """A manual expert of a woken discussion carries adapter 'manual', so mode switches never turn it into a woken member."""
212
- return {**member, "adapter": "manual"} if automatic and member["access"] == "manual" else member
213
-
214
-
215
- def discussion_members(payload, settings):
216
- """Validate credentials against the room's declared participants and delivery mode."""
217
- members = member_values(payload.get("members")) if settings["experts"] else []
218
- if {member["name"] for member in members} != set(settings["experts"]):
219
- raise ValueError("成员凭证名单须与参与者名单一致")
220
- for member in members:
221
- if not discussion_access_ok(member["access"], settings["experts"][member["name"]],
222
- payload.get("runtime_mode") == "automatic", member["name"] == settings["host"],
223
- member["manual_source"]):
224
- raise ValueError("成员接入方式与房间参与能力、任务交付方式不符")
225
- return [mark_manual(member, payload.get("runtime_mode") == "automatic") for member in members]
226
-
227
-
228
- def sync_discussion_members(connection, room_id, payload, settings):
229
- """Keep existing credentials; require fresh credentials for added or changed members."""
230
- current = {row["name"]: row for row in connection.execute("""SELECT m.*,
231
- COALESCE(s.source,'') AS manual_source FROM room_members m
232
- LEFT JOIN member_manual_sources s ON s.member_id=m.id WHERE m.room_id=? AND m.status='active'""", (room_id,))}
233
- supplied = {member["name"]: member_value(member) for member in payload.get("members", [])}
234
- run = connection.execute("SELECT mode FROM discussion_runtime WHERE room_id=?", (room_id,)).fetchone()
235
- for name, capability in settings["experts"].items():
236
- automatic = bool(run and run[0] == "automatic")
237
- old = current.get(name)
238
- if old and (old["manual_source"] == "web") == (capability == "online"):
239
- if name in supplied and token_hash(supplied[name]["token"]) != old["token_hash"]:
240
- raise FileExistsError("成员凭证与已登记身份不符;请核对原接入文件")
241
- continue
242
- if name not in supplied or not discussion_access_ok(supplied[name]["access"], capability, automatic,
243
- name == settings["host"], supplied[name]["manual_source"]):
244
- raise ValueError(f"新增或改变接入方式的成员 {name} 须提供独立的新凭证")
245
- member = mark_manual(supplied[name], automatic)
246
- hashed = token_hash(member["token"])
247
- if connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND token_hash=? UNION ALL SELECT 1 FROM room_modes WHERE room_id=? AND control_hash=?", (room_id, hashed, room_id, hashed)).fetchone():
248
- raise ValueError("新成员凭证不能复用已有凭证")
249
- connection.execute("UPDATE room_members SET status='removed' WHERE room_id=? AND name=?", (room_id, name))
250
- insert_member(connection, room_id, member, int(time.time()))
251
- for name in current.keys() - settings["experts"].keys():
252
- connection.execute("UPDATE room_members SET status='removed' WHERE room_id=? AND name=?", (room_id, name))
253
- connection.execute("UPDATE room_members SET role=CASE WHEN name=? THEN 'host' ELSE 'member' END WHERE room_id=?", (settings["host"], room_id))
254
-
255
-
256
- def sync_participants(connection, room_id):
257
- """Keep one active AI host, then mirror member capabilities and the host into shared room metadata."""
258
- connection.execute(RELEASE_HOST, (room_id,))
259
- connection.execute(ASSIGN_HOST, (room_id, room_id))
260
- members = connection.execute("""SELECT m.name,m.access,m.role,m.status,COALESCE(s.source,'') AS manual_source
261
- FROM room_members m LEFT JOIN member_manual_sources s ON s.member_id=m.id
262
- WHERE m.room_id=? AND m.status<>'removed' ORDER BY m.id""", (room_id,)).fetchall()
263
- experts = {row["name"]: "online" if row["manual_source"] == "web" else "cli" for row in members}
264
- host = next((row["name"] for row in members if row["role"] == "host" and row["status"] == "active"), "用户")
265
- connection.execute("UPDATE topic_settings SET experts=?,host=? WHERE room_id=?",
266
- (json.dumps(experts, ensure_ascii=False), host, room_id))
267
-
268
-
269
- def execution_minutes(connection, room_id):
270
- """Free rooms always bound one execution; zero in the shared limits means the default."""
271
- session = connection.execute("""SELECT l.execution_minutes FROM session_limits l
272
- JOIN discussion_sessions s ON s.id=l.session_id
273
- WHERE s.room_id=? AND s.status='active' AND EXISTS(SELECT 1 FROM session_state st WHERE st.session_id=s.id)
274
- ORDER BY s.id DESC LIMIT 1""", (room_id,)).fetchone()
275
- if session:
276
- return session[0] or FREE_EXECUTION_MINUTES
277
- row = connection.execute("SELECT execution_minutes FROM discussion_limits WHERE room_id=?", (room_id,)).fetchone()
278
- return (row[0] if row and row[0] else FREE_EXECUTION_MINUTES)
279
-
280
-
281
- def public_execution(row):
282
- """Return execution state without any credential material."""
283
- return {key: row[key] for key in EXECUTION_FIELDS} if row else None
284
-
285
-
286
- def execution_retry(connection, execution_id):
287
- """What the runner reported about a waiting retry of one execution, or None."""
288
- row = connection.execute("SELECT attempt,retry_at,reason,stopped FROM execution_retries WHERE execution_id=?", (execution_id,)).fetchone()
289
- return dict(row) if row else None
290
-
291
-
292
- def member_descriptions(connection, room_id):
293
- """The owner's descriptions of members by name; everyone who can read the room may read them."""
294
- return {row["name"]: row["description"] for row in connection.execute(
295
- "SELECT name,description FROM member_descriptions WHERE room_id=? ORDER BY name", (room_id,))}
296
-
297
-
298
- def describe_members(connection, room_id, token, payload):
299
- """Owner sets members' descriptions by name; an empty text removes that member's description."""
300
- require_owner(connection, room_id, token)
301
- descriptions = payload.get("descriptions")
302
- if (not isinstance(descriptions, dict) or not descriptions or len(descriptions) > MAX_ROOM_AGENTS
303
- or any(not isinstance(name, str) or not 0 < len(name) <= MAX_MEMBER_NAME or not isinstance(text, str)
304
- or len(text) > MAX_MEMBER_DESCRIPTION for name, text in descriptions.items())):
305
- raise ValueError(f"descriptions 须为 {{成员名: 描述}},最多 {MAX_ROOM_AGENTS} 位,每段最多 {MAX_MEMBER_DESCRIPTION} 字")
306
- begin_write(connection)
307
- now = int(time.time())
308
- for name, text in descriptions.items():
309
- if text.strip():
310
- connection.execute("""INSERT INTO member_descriptions (room_id,name,description,updated_at) VALUES (?,?,?,?)
311
- ON CONFLICT(room_id,name) DO UPDATE SET description=excluded.description,updated_at=excluded.updated_at""",
312
- (room_id, name, text.strip(), now))
313
- else:
314
- connection.execute("DELETE FROM member_descriptions WHERE room_id=? AND name=?", (room_id, name))
315
- return {"descriptions": member_descriptions(connection, room_id)}
316
-
317
-
318
- def member_labels(connection, room_id):
319
- """The owner's display labels of members by name; only screens use them, never addressing or credentials."""
320
- return {row["name"]: row["label"] for row in connection.execute(
321
- "SELECT name,label FROM member_labels WHERE room_id=? ORDER BY name", (room_id,))}
322
-
323
-
324
- def label_members(connection, room_id, token, payload):
325
- """Owner sets members' display labels by name; an empty text removes that member's label."""
326
- require_owner(connection, room_id, token)
327
- labels = payload.get("labels")
328
- if (not isinstance(labels, dict) or not labels or len(labels) > MAX_ROOM_AGENTS
329
- or any(not isinstance(name, str) or not 0 < len(name) <= MAX_MEMBER_NAME or not isinstance(text, str)
330
- or len(text.strip()) > MAX_MEMBER_LABEL for name, text in labels.items())):
331
- raise ValueError(f"labels 须为 {{成员名: 显示名}},最多 {MAX_ROOM_AGENTS} 位,每个最多 {MAX_MEMBER_LABEL} 字")
332
- begin_write(connection)
333
- now = int(time.time())
334
- for name, text in labels.items():
335
- if text.strip():
336
- connection.execute("""INSERT INTO member_labels (room_id,name,label,updated_at) VALUES (?,?,?,?)
337
- ON CONFLICT(room_id,name) DO UPDATE SET label=excluded.label,updated_at=excluded.updated_at""",
338
- (room_id, name, text.strip(), now))
339
- else:
340
- connection.execute("DELETE FROM member_labels WHERE room_id=? AND name=?", (room_id, name))
341
- return {"labels": member_labels(connection, room_id)}
342
-
343
- def note_count(connection, execution_id):
344
- """How many progress notes an execution has; the texts are read separately so room views stay small."""
345
- return connection.execute("SELECT COUNT(*) FROM execution_notes WHERE execution_id=?", (execution_id,)).fetchone()[0]
346
-
347
-
348
- def execution_notes(connection, room_id, execution_id, token=""):
349
- """Read one execution's progress notes in order, with the same access as the room view."""
350
- execution = connection.execute("SELECT member_id FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
351
- if not execution:
352
- raise LookupError("执行不存在")
353
- from .session_room import session_message_access
354
-
355
- boundary = session_message_access(connection, room_id, {}, token)
356
- if boundary is not None:
357
- try:
358
- member = require_member(connection, room_id, token)
359
- except PermissionError:
360
- return {"notes": []}
361
- if member["id"] != execution["member_id"]:
362
- return {"notes": []}
363
- return {"notes": [dict(row) for row in connection.execute(
364
- "SELECT seq,text,created_at FROM execution_notes WHERE execution_id=? ORDER BY seq", (execution_id,))]}
365
-
366
-
367
- def execution_timeline(connection, room_id, after=0):
368
- """Read the room's recent executions of both kinds with their phase segments and note times, for the timeline page.
369
-
370
- Times are epoch seconds and segments are millisecond offsets from `dispatched_at`. A free execution's parent is the
371
- execution that wrote the message it answers; discussion executions have none. `state` is running, done, failed
372
- or cancelled, so the page never interprets execution statuses itself. A positive `after` reads only executions
373
- still running or ended since then, so a page following live work rereads little.
374
- """
375
- if not connection.execute("SELECT 1 FROM rooms WHERE id=?", (room_id,)).fetchone():
376
- raise LookupError("房间不存在")
377
- params = (room_id, TIMELINE_EXECUTIONS, max(0, int(after)))
378
- rows = [dict(row) for row in connection.execute(TIMELINE_SQL, params)]
379
- segments, notes = {}, {}
380
- for row in connection.execute(TIMELINE_SEGMENTS_SQL, params):
381
- segments.setdefault((row["source"], row["execution_id"]), []).append(
382
- {key: row[key] for key in ("phase", "tool", "start_ms", "end_ms")})
383
- for row in connection.execute(TIMELINE_NOTES_SQL, params):
384
- notes.setdefault(row["execution_id"], []).append(row["created_at"])
385
- for row in rows:
386
- row["state"] = TIMELINE_STATES.get(row["status"], "running")
387
- row["segments"] = segments.get((row["source"], row["id"]), [])
388
- row["notes"] = notes.get(row["id"], []) if row["source"] == "free" else []
389
- return {"now": int(time.time()), "after": params[2], "executions": rows, "execution_limit": TIMELINE_EXECUTIONS,
390
- "segment_limit": MAX_EXECUTION_SEGMENTS}
391
-
392
-
393
- def recent_executions(connection, room_id):
394
- """Return bounded public reports, including requests no longer in the recent request list."""
395
- rows = connection.execute("""SELECT e.*,m.name AS member,
396
- (SELECT json_group_array(id) FROM member_requests WHERE execution_id=e.id) AS request_ids,
397
- (SELECT MAX(answer_id) FROM member_requests WHERE execution_id=e.id) AS answer_id,
398
- (SELECT MIN(message_id) FROM member_requests WHERE execution_id=e.id) AS request_message_id,
399
- (SELECT COUNT(*) FROM execution_notes WHERE execution_id=e.id) AS note_count,
400
- (SELECT denials FROM execution_denials WHERE execution_id=e.id) AS denials
401
- FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.room_id=? ORDER BY e.id DESC LIMIT ?""", (room_id, RECENT_EXECUTIONS))
402
- executions = []
403
- for row in rows:
404
- requests = []
405
- for request in connection.execute("SELECT id,message_id,purpose,status,answer_id FROM member_requests WHERE execution_id=? ORDER BY id", (row["id"],)):
406
- requests.append({**dict(request), **session_request_source(connection, request["id"], request["message_id"])})
407
- executions.append({**public_execution(row), "member": row["member"], "cwd": row["cwd"], "changes": json.loads(row["changes"] or "[]"),
408
- "changes_recorded": bool(row["changes"]), "request_ids": json.loads(row["request_ids"]),
409
- "answer_id": row["answer_id"], "request_message_id": row["request_message_id"], "requests": requests,
410
- "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"),
411
- "retry": execution_retry(connection, row["id"])})
412
- return executions
413
-
414
-
415
- def session_request_source(connection, member_request_id, message_id):
416
- """Expose session provenance and a visible transcript anchor for a member request."""
417
- row = connection.execute("""SELECT q.id AS session_request_id,q.session_id AS discussion_session_id,q.round,
418
- q.question AS source_question,t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id,
419
- CASE WHEN q.id IS NULL THEN r.message_id ELSE COALESCE((SELECT MAX(m.id) FROM messages m
420
- WHERE m.room_id=r.room_id AND m.id<r.message_id
421
- AND NOT EXISTS(SELECT 1 FROM task_message_sources hidden WHERE hidden.message_id=m.id)),0) END AS session_anchor
422
- FROM member_requests r LEFT JOIN session_requests q ON q.member_request_id=r.id
423
- LEFT JOIN task_message_sources t ON t.session_request_id=q.id WHERE r.id=?""", (member_request_id,)).fetchone()
424
- if row and row["session_request_id"] is not None:
425
- return {"session_request_id": row["session_request_id"], "discussion_session_id": row["discussion_session_id"],
426
- "round": row["round"], "source_question": row["source_question"],
427
- "source_message_id": row["source_message_id"], "cause_kind": row["cause_kind"],
428
- "cause_request_id": row["cause_request_id"], "after_message_id": row["session_anchor"]}
429
- return {"session_request_id": None, "discussion_session_id": None, "round": None, "source_question": "",
430
- "source_message_id": None, "cause_kind": None, "cause_request_id": None, "after_message_id": message_id}
431
-
432
-
433
- def possible_conflicts(connection, room_id, names):
434
- """Report files changed by executions of different members whose time windows overlapped.
435
-
436
- This is an observation, not attribution: it cannot tell who wrote which part or catch
437
- writes outside the scanned working directory.
438
- """
439
- now = int(time.time())
440
- rows = [dict(row) for row in connection.execute(
441
- """SELECT id,member_id,created_at,finished_at,changes,cwd FROM member_executions
442
- WHERE room_id=? AND changes<>'' ORDER BY id DESC LIMIT ?""", (room_id, RECENT_CHANGES))]
443
- for row in rows:
444
- row["files"] = set(json.loads(row["changes"]))
445
- row["end"] = row["finished_at"] or now
446
- conflicts = []
447
- for index, first in enumerate(rows):
448
- for second in rows[index + 1:]:
449
- if first["member_id"] == second["member_id"] or first["cwd"] != second["cwd"]:
450
- continue
451
- if first["created_at"] > second["end"] or second["created_at"] > first["end"]:
452
- continue
453
- files = sorted(first["files"] & second["files"])
454
- if files:
455
- conflicts.append({"members": [names.get(second["member_id"], ""), names.get(first["member_id"], "")],
456
- "executions": [second["id"], first["id"]], "files": files})
457
- return conflicts
458
-
459
-
460
- # An invited manual member that has not registered counts as absent: it receives no request and is never a target.
461
- REGISTERED_MEMBER = """(room_members.access<>'manual' OR EXISTS(SELECT 1 FROM member_manual_sources source
462
- WHERE source.member_id=room_members.id AND source.source='web') OR EXISTS(SELECT 1 FROM member_registrations r
463
- WHERE r.member_id=room_members.id AND r.token_hash=room_members.token_hash))"""
464
-
465
-
466
- def free_view(connection, room_id):
467
- """Summarize members, their live execution, recent requests and possible file conflicts."""
468
- now = int(time.time())
469
- members = []
470
- for row in connection.execute("SELECT * FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id", (room_id,)):
471
- member = {key: row[key] for key in MEMBER_FIELDS}
472
- source = connection.execute("SELECT source FROM member_manual_sources WHERE member_id=?", (row["id"],)).fetchone()
473
- member["manual_source"] = source[0] if source else ""
474
- member["registered_at"] = registered_at(connection, row)
475
- reported = connection.execute("SELECT session_id,client FROM member_sessions WHERE member_id=?", (row["id"],)).fetchone()
476
- member["reported_session"], member["reported_client"] = (reported["session_id"], reported["client"]) if reported else ("", "")
477
- latest = connection.execute("SELECT * FROM member_executions WHERE member_id=? ORDER BY id DESC LIMIT 1",
478
- (row["id"],)).fetchone()
479
- member["execution"] = public_execution(latest)
480
- if latest and latest["status"] in ACTIVE:
481
- member["execution"]["stale"] = latest["lease_until"] <= now
482
- member["execution"]["notes"] = note_count(connection, latest["id"])
483
- member["execution"]["retry"] = execution_retry(connection, latest["id"])
484
- member["pending"] = connection.execute("SELECT COUNT(*) FROM member_requests WHERE member_id=? AND status='pending'",
485
- (row["id"],)).fetchone()[0]
486
- members.append(member)
487
- names = {row["id"]: row["name"] for row in connection.execute("SELECT id,name FROM room_members WHERE room_id=?", (room_id,))}
488
- requests = [{**dict(row), "member": names.get(row["member_id"], ""),
489
- **session_request_source(connection, row["id"], row["message_id"])} for row in connection.execute(
490
- """SELECT id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose,created_by,created_at,
491
- (SELECT reason FROM request_cancel_reasons c WHERE c.request_id=member_requests.id) AS cancel_reason FROM member_requests
492
- WHERE room_id=? ORDER BY id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
493
- chains = [dict(row) for row in connection.execute(
494
- "SELECT chain_id,reason FROM free_chains WHERE room_id=? ORDER BY chain_id DESC LIMIT 10", (room_id,))]
495
- max_rounds = chain_rounds(connection, room_id)
496
- progress = [dict(row) for row in connection.execute(CHAIN_PROGRESS_SQL, (max_rounds, room_id))]
497
- return {"members": members, "requests": requests[::-1], "executions": recent_executions(connection, room_id), "execution_minutes": execution_minutes(connection, room_id),
498
- "conflicts": possible_conflicts(connection, room_id, names), "halted_chains": chains, "max_rounds": max_rounds,
499
- "chain_rounds": progress, "recommendations": recent_recommendations(connection, room_id, now)[::-1]}
500
-
501
-
502
- def require_member(connection, room_id, token, name=None):
503
- """Resolve an active member strictly from its own credential."""
504
- hashed = token_hash(token)
505
- row = connection.execute("SELECT * FROM room_members WHERE room_id=? AND token_hash=? AND status='active'",
506
- (room_id, hashed)).fetchone() if hashed else None
507
- if not row or (name is not None and row["name"] != name):
508
- raise PermissionError("成员凭证无效、已停用或与发言身份不符")
509
- if connection.execute("SELECT 1 FROM member_manual_sources WHERE member_id=? AND source='web'", (row["id"],)).fetchone():
510
- raise PermissionError("网页成员只读;由房主凭据代发其回答")
511
- return dict(row)
512
-
513
-
514
- def registered_at(connection, member):
515
- """Return when the member registered with its current credential, or '' while it has not."""
516
- row = connection.execute("SELECT registered_at FROM member_registrations WHERE member_id=? AND token_hash=?",
517
- (member["id"], member["token_hash"])).fetchone()
518
- return row[0] if row else ""
519
-
520
-
521
- def register_member(connection, room_id, token, now):
522
- """A manual member announces itself with its own credential; repeating it keeps the first time.
523
-
524
- The session ID is not part of the request: the CLI attaches it to every call and the room records it separately.
525
- """
526
- begin_write(connection)
527
- member = require_member(connection, room_id, token)
528
- if member["access"] != "manual":
529
- raise ValueError("只有手动接入的成员需要注册")
530
- previous = registered_at(connection, member)
531
- stamp = previous or now
532
- connection.execute("""INSERT INTO member_registrations (member_id,room_id,token_hash,registered_at) VALUES (?,?,?,?)
533
- ON CONFLICT(member_id) DO UPDATE SET token_hash=excluded.token_hash,registered_at=excluded.registered_at""",
534
- (member["id"], room_id, member["token_hash"], stamp))
535
- if not previous:
536
- queue_invited_expert(connection, room_id, member["name"], now)
537
- reported = connection.execute("SELECT client FROM member_sessions WHERE member_id=?", (member["id"],)).fetchone()
538
- return {"member": member["name"], "registered_at": stamp, "session_client": reported[0] if reported else ""}
539
-
540
-
541
- def authorize_free_write(connection, room_id, token, operation, payload):
542
- """Decide who is writing: the owner, or one member posting its own answer.
543
-
544
- Returns:
545
- "用户" for the owner, or the member row for a member credential.
546
- """
547
- begin_write(connection)
548
- if operation not in FREE_OPERATIONS:
549
- raise ValueError("自由房间不使用发言权、安排、阶段或轮次")
550
- try:
551
- require_owner(connection, room_id, token)
552
- return "用户"
553
- except PermissionError:
554
- if operation not in ("messages", "attachments"):
555
- raise
556
- author = payload.get("author")
557
- member = require_member(connection, room_id, token)
558
- if author == member["name"] and payload.get("submitted_by", author) == author:
559
- return member
560
- if member["role"] == "host" and author != member["name"] and payload.get("submitted_by") == member["name"]:
561
- proxy = proxy_member(connection, room_id, author)
562
- proxy["proxy_by"] = member["name"]
563
- return proxy
564
- raise PermissionError("成员只能以本人身份发言;只有主持人可以代发在线成员回答")
565
-
566
-
567
- def active_members(connection, room_id, registered_only=True):
568
- """Map active member names to their rows; unregistered manual members are left out unless a discussion start needs them pending."""
569
- return {row["name"]: row for row in connection.execute(
570
- f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND ({REGISTERED_MEMBER} OR ?=0)", (room_id, int(registered_only)))}
571
-
572
-
573
- def named_members(active, names, exclude=None):
574
- """Validate a structured recipient list against the active members."""
575
- if not isinstance(names, list) or any(name not in active or name == exclude for name in names):
576
- raise ValueError("点名对象须为本房间在场成员" + (",且不能点名自己" if exclude else ""))
577
- return [active[name]["id"] for name in dict.fromkeys(names)]
578
-
579
-
580
- def recipients(connection, room_id, payload):
581
- """Resolve an owner message's recipients as (member id, purpose) pairs.
582
-
583
- A single active member is named by default. With several, an unnamed message goes to the
584
- AI host for routing; only a room of online members has none, and then it stays a plain note.
585
- Naming everyone with order auto leaves the host a group request: the runner has everyone answer
586
- at once or one after another; a host the runner does not wake has them all answer at once.
587
- """
588
- # Rooms created while the user could host get their AI host on the next message.
589
- sync_participants(connection, room_id)
590
- active = active_members(connection, room_id)
591
- if payload.get("to") is not None:
592
- named = named_members(active, payload["to"])
593
- host = next((row for row in active.values() if row["role"] == "host"), None)
594
- if payload.get("order") == "auto" and len(named) > 1 and host and host["access"] == "runner":
595
- return [(host["id"], "group")]
596
- return [(member_id, "ask") for member_id in named]
597
- if len(active) == 1:
598
- return [(next(iter(active.values()))["id"], "ask")]
599
- host = next((row for row in active.values() if row["role"] == "host"), None)
600
- return [(host["id"], "route")] if host else []
601
-
602
-
603
- def route_held_messages(connection, room_id, host):
604
- """When a discussion ends, hand the user's messages its host never answered to the free room's recipients, as if just sent."""
605
- held = connection.execute("SELECT held_since FROM turn_relay WHERE room_id=?", (room_id,)).fetchone()
606
- if held and held[0]:
607
- rows = connection.execute("""SELECT id FROM messages m WHERE room_id=? AND author='用户' AND id>=?
608
- AND id>COALESCE((SELECT MAX(id) FROM messages WHERE room_id=? AND author=?),0)
609
- AND NOT EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id=m.id) ORDER BY id""",
610
- (room_id, held[0], room_id, host)).fetchall()
611
- for row in rows:
612
- for member_id, purpose in recipients(connection, room_id, {}):
613
- insert_request(connection, room_id, member_id, row["id"], row["id"], purpose, "user")
614
- connection.execute("UPDATE turn_relay SET held_since=0 WHERE room_id=?", (room_id,))
615
-
616
-
617
- def proxy_member(connection, room_id, author):
618
- """Return the active online member the owner may forward an answer for."""
619
- row = connection.execute("""SELECT m.*,s.source AS manual_source FROM room_members m
620
- JOIN member_manual_sources s ON s.member_id=m.id AND s.source='web'
621
- WHERE m.room_id=? AND m.name=? AND m.status='active' AND m.access='manual'""",
622
- (room_id, author)).fetchone()
623
- if not row:
624
- raise PermissionError("房间控制凭据只能以用户身份发言,或代发在线成员的回答")
625
- return dict(row)
626
-
627
-
628
- def check_answer(connection, room_id, member, payload):
629
- """A runner member completes a live execution; a manual member may close its own open requests.
630
-
631
- Only the AI host dispatches work; other members' targets remain suggestions.
632
- """
633
- if payload.get("to") is not None:
634
- named_members(active_members(connection, room_id), payload["to"], exclude=member["name"])
635
- if payload.get("handoff") not in (None, False) and (payload["handoff"] is not True or member["role"] != "host" or not payload.get("to")):
636
- raise ValueError("handoff 只能由主持人与 to 一起使用,值为 true")
637
- if member["access"] == "online":
638
- raise PermissionError("在线成员只读,回答由用户代发")
639
- if member["access"] == "manual":
640
- request_ids = payload.get("request_ids", [])
641
- if payload.get("execution_id") is not None or not isinstance(request_ids, list) or any(type(item) is not int for item in request_ids):
642
- raise ValueError("手动接入成员用 request_ids 关联请求,不使用执行编号")
643
- purposes = []
644
- requests = []
645
- for request_id in request_ids:
646
- row = connection.execute("SELECT * FROM member_requests WHERE room_id=? AND id=?", (room_id, request_id)).fetchone()
647
- if not row or row["member_id"] != member["id"] or row["status"] != "pending":
648
- raise FileExistsError(f"请求 {request_id} 不属于本成员或已处理")
649
- purposes.append(row["purpose"])
650
- requests.append(row)
651
- validate_session_request_answer(connection, room_id, requests)
652
- check_dispatch(member, payload, purposes)
653
- return None
654
- execution_id = payload.get("execution_id")
655
- if type(execution_id) is not int:
656
- raise ValueError("成员回答须关联本次执行编号 execution_id")
657
- row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
658
- if not row or row["member_id"] != member["id"]:
659
- raise PermissionError("执行编号不属于本成员")
660
- if row["status"] not in ACTIVE or row["lease_until"] <= int(time.time()):
661
- raise FileExistsError("本次执行已结束、被打断或已过期;回答不能改作普通发言,请保留草稿")
662
- requests = [dict(item) for item in connection.execute(
663
- "SELECT id,purpose FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,))]
664
- validate_session_request_answer(connection, room_id, requests)
665
- check_dispatch(member, payload, [item["purpose"] for item in requests])
666
- return row
667
-
668
-
669
- def check_dispatch(member, payload, purposes):
670
- """A host answering only its share of an everyone request answers as a member, so it may not dispatch others."""
671
- if member["role"] == "host" and payload.get("to") and purposes and all(purpose == "all" for purpose in purposes):
672
- raise ValueError("这次是请全体成员各自回应,其他成员已收到请求;主持人只回答自己的部分,不能用 --to 派活")
673
-
674
-
675
- def validate_session_request_answer(connection, room_id, requests):
676
- """Keep a discussion speaker request separate and live when answering it."""
677
- discussions = [request for request in requests if request["purpose"] == "discuss"]
678
- if not discussions:
679
- return
680
- if len(requests) != 1 or len(discussions) != 1:
681
- raise ValueError("讨论安排须单独回答,不能与普通请求合并")
682
- request_id = discussions[0]["id"]
683
- plan = connection.execute("""SELECT sr.status,s.status AS session_status FROM session_requests sr
684
- JOIN discussion_sessions s ON s.id=sr.session_id JOIN member_requests r ON r.id=sr.member_request_id
685
- WHERE s.room_id=? AND r.id=? AND sr.purpose='discuss'""", (room_id, request_id)).fetchone()
686
- if not plan or plan["session_status"] != "active" or plan["status"] != "open":
687
- raise FileExistsError("讨论安排已暂停、结束或取消,不能继续回答")
688
-
689
-
690
- def check_proxy(connection, room_id, member, payload):
691
- """The owner forwards an online member's answer and may close that member's open requests."""
692
- request_ids = payload.get("request_ids", [])
693
- if not isinstance(request_ids, list) or any(type(item) is not int for item in request_ids):
694
- raise ValueError("request_ids 须为请求编号列表")
695
- requests = []
696
- for request_id in request_ids:
697
- row = connection.execute("SELECT * FROM member_requests WHERE room_id=? AND id=?", (room_id, request_id)).fetchone()
698
- if not row or row["member_id"] != member["id"] or row["status"] != "pending":
699
- raise FileExistsError(f"请求 {request_id} 不属于该在线成员或已处理")
700
- requests.append(row)
701
- validate_session_request_answer(connection, room_id, requests)
702
-
703
-
704
- def insert_request(connection, room_id, member_id, message_id, chain_id, purpose, created_by, batch_id=0):
705
- """Queue one request; every request belongs to the chain its owner message started."""
706
- connection.execute("""INSERT INTO member_requests (room_id,member_id,message_id,chain_id,batch_id,purpose,created_by,created_at)
707
- VALUES (?,?,?,?,?,?,?,?)""", (room_id, member_id, message_id, chain_id, batch_id, purpose, created_by, int(time.time())))
708
-
709
-
710
- def mention_prose(text):
711
- """Remove Markdown code and quote blocks before interpreting response suggestions."""
712
- lines, fence, quoted = [], "", False
713
- for line in text.splitlines():
714
- marker = re.match(r"^ {0,3}(`{3,}|~{3,})", line)
715
- if marker:
716
- value = marker[1]
717
- if not fence:
718
- fence = value
719
- elif value[0] == fence[0] and len(value) >= len(fence):
720
- fence = ""
721
- continue
722
- if fence or re.match(r"^( {4}|\t)", line):
723
- continue
724
- if re.match(r"^ {0,3}>", line):
725
- quoted = True
726
- continue
727
- if not line.strip():
728
- quoted = False
729
- if not quoted:
730
- lines.append(line)
731
- return re.sub(r"(`+)[\s\S]*?\1(?!`)", "", "\n".join(lines))
732
-
733
-
734
- def save_suggestions(connection, room_id, message_id, member, payload):
735
- """Save ordinary members' explicit targets and prose mentions without waking anyone."""
736
- if member == "用户" or member["role"] == "host":
737
- return
738
- active = active_members(connection, room_id)
739
- targets = set(named_members(active, payload["to"] if payload.get("to") is not None else [], exclude=member["name"]))
740
- prose = mention_prose(str(payload.get("text", "")))
741
- for name, target in active.items():
742
- if name != member["name"] and re.search(r"(^|[\s((,,。;;::])@" + re.escape(name) + r"(?![A-Za-z0-9_\-\u4e00-\u9fff])", prose):
743
- targets.add(target["id"])
744
- for target_id in targets:
745
- connection.execute("INSERT INTO member_suggestions (message_id,member_id) VALUES (?,?)", (message_id, target_id))
746
-
747
-
748
- def message_suggestions(connection, message_id):
749
- """Expose suggested members and the durable request, including terminal conversions."""
750
- return [dict(row) for row in connection.execute("""SELECT s.member_id,m.name AS member,m.status,
751
- r.id AS request_id,r.status AS request_status FROM member_suggestions s
752
- JOIN room_members m ON m.id=s.member_id
753
- LEFT JOIN member_requests r ON r.message_id=s.message_id AND r.member_id=s.member_id
754
- WHERE s.message_id=? ORDER BY s.member_id""", (message_id,))]
755
-
756
-
757
- def convert_suggestion(connection, room_id, token, payload):
758
- """Let the owner turn a saved suggestion into one request and a fresh user chain."""
759
- begin_write(connection)
760
- require_owner(connection, room_id, token)
761
- message_id, member_id = payload.get("message_id"), payload.get("member_id")
762
- if type(message_id) is not int or type(member_id) is not int:
763
- raise ValueError("须提供原消息编号 message_id 与成员编号 member_id")
764
- target = connection.execute("""SELECT m.name,m.status FROM member_suggestions s
765
- JOIN messages source ON source.id=s.message_id JOIN room_members m ON m.id=s.member_id
766
- WHERE source.room_id=? AND m.room_id=? AND s.message_id=? AND s.member_id=?""",
767
- (room_id, room_id, message_id, member_id)).fetchone()
768
- if not target:
769
- raise LookupError("这条消息没有该成员的回应建议")
770
- if target["status"] != "active":
771
- raise FileExistsError("该成员已离开,不能转为请求")
772
- if connection.execute("SELECT 1 FROM room_directory WHERE room_id=? AND archived=1", (room_id,)).fetchone():
773
- raise ValueError("房间已存档;恢复后才能继续协作")
774
- previous = connection.execute("SELECT * FROM member_requests WHERE message_id=? AND member_id=?", (message_id, member_id)).fetchone()
775
- if previous:
776
- return {"request": dict(previous), "duplicate": True}
777
- confirmation = connection.execute("""INSERT INTO messages (room_id,author,text,reply_to,source,submission_id,created_at)
778
- VALUES (?,'用户',?,?,'user',?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))""",
779
- (room_id, f"请 @{target['name']} 回应 #{message_id} 的建议。", message_id, uuid.uuid4().hex))
780
- connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,'chat','用户')", (confirmation.lastrowid,))
781
- insert_request(connection, room_id, member_id, message_id, confirmation.lastrowid, "ask", "user")
782
- request = connection.execute("SELECT * FROM member_requests WHERE message_id=? AND member_id=?", (message_id, member_id)).fetchone()
783
- return {"request": dict(request), "duplicate": False}
784
-
785
-
786
- def halt_chain(connection, room_id, chain_id, reason):
787
- """Stop automatic progress on a chain; the user's next message starts a new one."""
788
- connection.execute("INSERT OR IGNORE INTO free_chains (room_id,chain_id,reason) VALUES (?,?,?)", (room_id, chain_id, reason))
789
-
790
-
791
- def rounds_left(connection, room_id, chain_id):
792
- """Rounds a chain may still start: the room's limit plus what the owner added, less the dispatches made; none once halted."""
793
- if connection.execute("SELECT 1 FROM free_chains WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone():
794
- return 0
795
- used = connection.execute("SELECT COUNT(*) FROM free_batches WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()[0]
796
- extra = connection.execute("SELECT extra_rounds FROM free_chain_holds WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()
797
- return chain_rounds(connection, room_id) + (extra[0] if extra else 0) - used
798
-
799
-
800
- def chain_rounds(connection, room_id):
801
- """Rounds a host may run from one owner message in this room."""
802
- row = connection.execute("SELECT max_rounds FROM free_round_limits WHERE room_id=?", (room_id,)).fetchone()
803
- return row[0] if row else CHAIN_ROUNDS
804
-
805
-
806
- def set_chain_rounds(connection, room_id, token, payload):
807
- """Owner sets the room's round limit; it applies to chains still running and to later ones."""
808
- require_owner(connection, room_id, token)
809
- value = payload.get("max_rounds")
810
- if type(value) is not int or not 1 <= value <= MAX_CHAIN_ROUNDS:
811
- raise ValueError(f"max_rounds 须为 1–{MAX_CHAIN_ROUNDS} 的整数")
812
- begin_write(connection)
813
- connection.execute("""INSERT INTO free_round_limits (room_id,max_rounds) VALUES (?,?)
814
- ON CONFLICT(room_id) DO UPDATE SET max_rounds=excluded.max_rounds""", (room_id, value))
815
- return {"max_rounds": value}
816
-
817
-
818
- def continue_chain(connection, room_id, token, chain_id, payload):
819
- """Owner lets a chain the round limit stopped run on: adds rounds and sends the dispatch the limit held back.
820
-
821
- Bound to one known chain, so it takes no revision; a chain that is not stopped by its limit is refused.
822
- """
823
- require_owner(connection, room_id, token)
824
- rounds = payload.get("rounds")
825
- if type(rounds) is not int or not 1 <= rounds <= MAX_CHAIN_ROUNDS:
826
- raise ValueError(f"rounds 须为 1–{MAX_CHAIN_ROUNDS} 的整数")
827
- begin_write(connection)
828
- halted = connection.execute("SELECT reason FROM free_chains WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()
829
- if not halted or halted[0] != "budget":
830
- raise FileExistsError("这条任务链没有因轮数上限停下,无需继续")
831
- host = connection.execute("SELECT * FROM room_members WHERE room_id=? AND role='host' AND status='active'", (room_id,)).fetchone()
832
- if not host:
833
- raise ValueError("房间没有在场的主持人,无法继续")
834
- connection.execute("""INSERT INTO free_chain_holds (room_id,chain_id,extra_rounds) VALUES (?,?,?)
835
- ON CONFLICT(room_id,chain_id) DO UPDATE SET extra_rounds=extra_rounds+excluded.extra_rounds""", (room_id, chain_id, rounds))
836
- connection.execute("DELETE FROM free_chains WHERE room_id=? AND chain_id=?", (room_id, chain_id))
837
- held = connection.execute("SELECT message_id,names,handoff FROM free_chain_holds WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()
838
- connection.execute("UPDATE free_chain_holds SET message_id=0,host_id=0,names='[]',handoff=0 WHERE room_id=? AND chain_id=?", (room_id, chain_id))
839
- if held["message_id"]:
840
- dispatch(connection, room_id, host, held["message_id"], json.loads(held["names"]), chain_id, bool(held["handoff"]))
841
- return free_view(connection, room_id)
842
-
843
-
844
- def hold_dispatch(connection, room_id, host, message_id, names, chain_id, handoff):
845
- """Stop a chain at its round limit, keeping the dispatch it held back so the owner can send it by continuing."""
846
- halt_chain(connection, room_id, chain_id, "budget")
847
- connection.execute("""INSERT INTO free_chain_holds (room_id,chain_id,message_id,host_id,names,handoff) VALUES (?,?,?,?,?,?)
848
- ON CONFLICT(room_id,chain_id) DO UPDATE SET message_id=excluded.message_id,host_id=excluded.host_id,names=excluded.names,
849
- handoff=excluded.handoff""", (room_id, chain_id, message_id, host["id"], json.dumps(list(names), ensure_ascii=False), int(handoff)))
850
-
851
-
852
- def dispatch(connection, room_id, host, message_id, names, chain_id, handoff=False):
853
- """Queue the host's named members as one batch, one round; several members, or one the host asked back, hand back when it ends."""
854
- member_ids = named_members(active_members(connection, room_id), names, exclude=host["name"])
855
- if not member_ids or not chain_id:
856
- return
857
- if rounds_left(connection, room_id, chain_id) < 1:
858
- hold_dispatch(connection, room_id, host, message_id, names, chain_id, handoff)
859
- return
860
- for member_id in member_ids:
861
- insert_request(connection, room_id, member_id, message_id, chain_id, "ask", "host", batch_id=message_id)
862
- connection.execute("INSERT INTO free_batches (room_id,batch_id,chain_id,host_id) VALUES (?,?,?,?)",
863
- (room_id, message_id, chain_id, host["id"]))
864
- if handoff:
865
- connection.execute("INSERT INTO free_handoffs (room_id,batch_id) VALUES (?,?)", (room_id, message_id))
866
-
867
-
868
- def settle_batches(connection, room_id):
869
- """Hand each finished batch back to its host once; an all-failed batch halts its chain instead."""
870
- for batch in connection.execute("SELECT * FROM free_batches WHERE room_id=? AND settled=0", (room_id,)).fetchall():
871
- statuses = [row[0] for row in connection.execute("SELECT status FROM member_requests WHERE room_id=? AND batch_id=?",
872
- (room_id, batch["batch_id"]))]
873
- if any(status not in TERMINAL for status in statuses):
874
- continue
875
- connection.execute("UPDATE free_batches SET settled=1 WHERE room_id=? AND batch_id=?", (room_id, batch["batch_id"]))
876
- host = connection.execute("SELECT * FROM room_members WHERE id=? AND status='active' AND role='host'", (batch["host_id"],)).fetchone()
877
- if "completed" not in statuses:
878
- halt_chain(connection, room_id, batch["chain_id"], "all_failed")
879
- elif not host or len(statuses) < 2 and not connection.execute(
880
- "SELECT 1 FROM free_handoffs WHERE room_id=? AND batch_id=?", (room_id, batch["batch_id"])).fetchone():
881
- # One member's answer reaches the user directly unless the host asked for it back, e.g. to send it to a reviewer.
882
- continue
883
- else:
884
- # The hand-back closes the round it belongs to, so it is never held back: the last round still gets its summary.
885
- insert_request(connection, room_id, host["id"], batch["batch_id"], batch["chain_id"], "handoff", "host")
886
- advance_queues(connection, room_id)
887
-
888
-
889
- def queue_in_turn(connection, room_id, message_id, member_ids):
890
- """Line the named members up for one owner message in the room's speaking order; only the first is asked now."""
891
- chosen = set(member_ids)
892
- members = [dict(row) for row in connection.execute("SELECT id,name,role FROM room_members WHERE room_id=?", (room_id,))]
893
- for member in default_order(connection, room_id, [member for member in members if member["id"] in chosen]):
894
- connection.execute("INSERT INTO free_queue (room_id,message_id,member_id) VALUES (?,?,?)", (room_id, message_id, member["id"]))
895
- advance_queues(connection, room_id)
896
-
897
-
898
- def advance_queues(connection, room_id):
899
- """Ask the next queued member of each message whose previous request ended; members no longer present are skipped.
900
-
901
- Asked rows stay, so the speaking order can still show who already answered.
902
- """
903
- connection.execute(f"""DELETE FROM free_queue WHERE room_id=? AND NOT {QUEUE_ASKED.format(row="free_queue")}
904
- AND NOT EXISTS(SELECT 1 FROM room_members m WHERE m.id=free_queue.member_id AND m.status='active')""", (room_id,))
905
- connection.execute(f"""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,batch_id,purpose,created_by,created_at)
906
- SELECT q.room_id,q.member_id,q.message_id,q.message_id,0,'ask','user',? FROM free_queue q
907
- WHERE q.room_id=? AND q.id=(SELECT MIN(x.id) FROM free_queue x WHERE x.message_id=q.message_id AND NOT {QUEUE_ASKED.format(row="x")})
908
- AND NOT EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id=q.message_id AND r.status IN ('pending','delivering'))""",
909
- (int(time.time()), room_id))
910
-
911
-
912
- def default_order(connection, room_id, members):
913
- """Members in the room's saved speaking order; without one (or for members it lacks), the host first, then by joining order."""
914
- row = connection.execute("SELECT member_ids FROM speaking_orders WHERE room_id=?", (room_id,)).fetchone()
915
- rank = {member_id: index for index, member_id in enumerate(json.loads(row[0]) if row else [])}
916
- return sorted(members, key=lambda member: (member["id"] not in rank, rank.get(member["id"], 0), member["role"] != "host", member["id"]))
917
-
918
-
919
- def speaking_order(connection, room):
920
- """Who spoke, who speaks now and who is next, shared by free rooms and discussions; only the not-yet-spoken part may be reordered.
921
-
922
- A free room shows its latest unfinished one-after-another queue, else every member in the room's default order;
923
- a discussion shows the open round: speakers so far, the current turn, then this round's queued turns; a plan reaching into
924
- later rounds lists them apart in `later` (one name list per round), read-only. The revision changes with any of it.
925
- """
926
- active = [member for member in room["members"] if member["status"] == "active"]
927
- by_id = {member["id"]: member for member in active}
928
- ordered = [member["name"] for member in default_order(connection, room["id"], active)]
929
- items, kind, target, later = [], "default", 0, []
930
- session_plan_state = []
931
- if room["mode"] == "free":
932
- from .session_room import current_session
933
- session = current_session(connection, room["id"], active_only=True)
934
- if session:
935
- kind = "turns"
936
- target = session["id"]
937
- session_plan_state = [list(row) for row in connection.execute("""SELECT id,round,position,member_id,question,status,submission_id
938
- FROM session_requests WHERE session_id=? AND purpose='discuss' ORDER BY round,position,id""", (session["id"],))]
939
- active_round = connection.execute("SELECT MIN(round) FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued')",
940
- (session["id"],)).fetchone()[0]
941
- if active_round is None:
942
- active_round = connection.execute("SELECT COALESCE(MAX(round),1) FROM session_requests WHERE session_id=? AND purpose='discuss'",
943
- (session["id"],)).fetchone()[0]
944
- answered = [row["name"] for row in connection.execute("""SELECT m.name FROM session_requests sr JOIN room_members m ON m.id=sr.member_id
945
- WHERE sr.session_id=? AND sr.purpose='discuss' AND sr.round=? AND sr.status='answered' ORDER BY sr.position,sr.id""",
946
- (session["id"], active_round))]
947
- items.extend({"name": name, "state": "done"} for name in answered)
948
- open_turn = connection.execute("""SELECT m.name FROM session_requests sr JOIN room_members m ON m.id=sr.member_id
949
- WHERE sr.session_id=? AND sr.purpose='discuss' AND sr.round=? AND sr.status='open'
950
- ORDER BY sr.position,sr.id LIMIT 1""", (session["id"], active_round)).fetchone()
951
- if open_turn:
952
- items.append({"name": open_turn["name"], "state": "speaking"})
953
- queued = connection.execute("""SELECT sr.round,m.name FROM session_requests sr JOIN room_members m ON m.id=sr.member_id
954
- WHERE sr.session_id=? AND sr.purpose='discuss' AND sr.status='queued' ORDER BY sr.round,sr.position,sr.id""",
955
- (session["id"],)).fetchall()
956
- for row in queued:
957
- if row["round"] == active_round:
958
- items.append({"name": row["name"], "state": "queued"})
959
- later = [[row["name"] for row in queued if row["round"] == round_number]
960
- for round_number in sorted({row["round"] for row in queued if row["round"] > active_round})]
961
- else:
962
- target = connection.execute("""SELECT MAX(q.message_id) FROM free_queue q LEFT JOIN member_requests r ON r.message_id=q.message_id
963
- AND r.member_id=q.member_id WHERE q.room_id=? AND (r.id IS NULL OR r.status IN ('pending','delivering'))""", (room["id"],)).fetchone()[0] or 0
964
- if target:
965
- kind = "queue"
966
- for row in connection.execute("""SELECT q.member_id,r.status FROM free_queue q LEFT JOIN member_requests r
967
- ON r.message_id=q.message_id AND r.member_id=q.member_id WHERE q.message_id=? ORDER BY q.id""", (target,)):
968
- if row["member_id"] in by_id:
969
- state = "queued" if row["status"] is None else "speaking" if row["status"] in ("pending", "delivering") else "done"
970
- items.append({"name": by_id[row["member_id"]]["name"], "state": state})
971
- else:
972
- kind = "turns"
973
- last = room["rounds"][-1] if room["rounds"] else None
974
- turn = room["current_turn"]
975
- speaking = turn["expert"] if turn and turn["status"] in ("pending", "notified") else None
976
- items = [{"name": name, "state": "done"} for name in (last["speakers"] if last and not last["completed"] else []) if name != speaking]
977
- if speaking:
978
- items.append({"name": speaking, "state": "speaking"})
979
- rounds = split_rounds([item["expert"] for item in room["queued_turns"]], {item["name"] for item in items})
980
- items += [{"name": name, "state": "queued"} for name in rounds[0]]
981
- later = rounds[1:]
982
- # The user may still hold the host seat of an old discussion; only AI participants have a place.
983
- ordered = [name for name in [room["host"], *ordered, *room["experts"]] if (name in room["experts"] or name == room["host"]) and name != "用户"]
984
- listed = {item["name"] for item in items}
985
- items += [{"name": name, "state": "idle"} for name in dict.fromkeys(ordered) if name not in listed]
986
- movable = "queued" if kind != "default" else "idle"
987
- state = json.dumps([kind, target, [[item["name"], item["state"]] for item in items], later, session_plan_state], ensure_ascii=False)
988
- return {"kind": kind, "message_id": target, "items": items, "later": later, "movable": [item["name"] for item in items if item["state"] == movable],
989
- "default": [member["name"] for member in default_order(connection, room["id"], active)],
990
- "revision": hashlib.sha256(state.encode("utf-8")).hexdigest()[:12]}
991
-
992
-
993
- def split_rounds(names, spoken):
994
- """Cut a turn queue into rounds: an expert who already spoke in the round being filled starts the next one."""
995
- rounds, seen = [[]], set(spoken)
996
- for name in names:
997
- if name in seen:
998
- rounds.append([])
999
- seen = set()
1000
- rounds[-1].append(name)
1001
- seen.add(name)
1002
- return rounds
1003
-
1004
-
1005
- def reorder_speakers(connection, room, token, payload):
1006
- """Owner reorders the not-yet-spoken part of the speaking order; who already spoke or speaks now stays put.
1007
-
1008
- Read the speaking order first and send its revision: a missing revision is refused, a changed one conflicts,
1009
- and the new order must list exactly the movable members.
1010
- """
1011
- require_owner(connection, room["id"], token)
1012
- current = room["speaking_order"]
1013
- if payload.get("revision") is None:
1014
- raise ValueError("调整发言顺序前须先读取最新顺序(speaking-order),并带上其 revision")
1015
- if payload["revision"] != current["revision"]:
1016
- raise FileExistsError("发言顺序已变化,请重新读取后再调整")
1017
- order = payload.get("order")
1018
- movable = current["movable"]
1019
- if not isinstance(order, list) or sorted(map(str, order)) != sorted(movable):
1020
- given = [str(name) for name in order] if isinstance(order, list) else []
1021
- missing = [name for name in dict.fromkeys(movable) if given.count(name) < movable.count(name)]
1022
- extra = [name for name in dict.fromkeys(given) if movable.count(name) < given.count(name)]
1023
- raise ValueError("新顺序须恰好包含尚未发言的成员" + (f";缺少:{'、'.join(missing)}" if missing else "") + (f";多出:{'、'.join(extra)}" if extra else ""))
1024
- names = {member["name"]: member["id"] for member in room["members"] if member["status"] == "active"}
1025
- if current["kind"] == "queue":
1026
- connection.execute(f"DELETE FROM free_queue WHERE message_id=? AND NOT {QUEUE_ASKED.format(row='free_queue')}", (current["message_id"],))
1027
- for name in order:
1028
- connection.execute("INSERT INTO free_queue (room_id,message_id,member_id) VALUES (?,?,?)", (room["id"], current["message_id"], names[name]))
1029
- elif current["kind"] == "turns":
1030
- from .session_room import current_session
1031
- session = current_session(connection, room["id"], active_only=True)
1032
- if session:
1033
- active_round = connection.execute("SELECT MIN(round) FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued')",
1034
- (session["id"],)).fetchone()[0]
1035
- active_round = active_round or 1
1036
- open_position = connection.execute("SELECT COALESCE(MAX(position),0) FROM session_requests WHERE session_id=? AND purpose='discuss' AND round=? AND status IN ('answered','open')",
1037
- (session["id"], active_round)).fetchone()[0]
1038
- rows = connection.execute("SELECT id FROM session_requests WHERE session_id=? AND purpose='discuss' AND round=? AND status='queued'",
1039
- (session["id"], active_round)).fetchall()
1040
- connection.execute("UPDATE session_requests SET position=-id WHERE id IN (%s)" % ",".join("?" for _ in rows),
1041
- [row["id"] for row in rows]) if rows else None
1042
- for offset, name in enumerate(order, 1):
1043
- connection.execute("UPDATE session_requests SET position=? WHERE session_id=? AND purpose='discuss' AND round=? AND status='queued' AND member_id=?",
1044
- (open_position + offset, session["id"], active_round, names[name]))
1045
- connection.execute("UPDATE session_state SET revision=revision+1 WHERE session_id=?", (session["id"],))
1046
- else:
1047
- reorder_turns(connection, room["id"], order)
1048
- else:
1049
- connection.execute("INSERT OR REPLACE INTO speaking_orders (room_id,member_ids) VALUES (?,?)",
1050
- (room["id"], json.dumps([names[name] for name in order])))
1051
-
1052
-
1053
- def reorder_turns(connection, room_id, order):
1054
- """Move this round's queued turns into the new order; ids keep the relay order, so each turn's content moves to the id at its new place.
1055
-
1056
- This round's turns lead the queue, so they are its first rows; later rounds keep theirs.
1057
- """
1058
- rows = [dict(row) for row in connection.execute("SELECT * FROM discussion_turns WHERE room_id=? AND status='queued' ORDER BY id LIMIT ?",
1059
- (room_id, len(order)))]
1060
- remaining, moved = list(rows), []
1061
- for name in order:
1062
- moved.append(remaining.pop(next(index for index, row in enumerate(remaining) if row["expert"] == name)))
1063
- # Submission ids are unique, so free them before writing them to their new rows.
1064
- for slot in rows:
1065
- connection.execute("UPDATE discussion_turns SET submission_id=submission_id||':moving:'||id WHERE id=?", (slot["id"],))
1066
- for slot, content in zip(rows, moved):
1067
- connection.execute("UPDATE discussion_turns SET expert=?,question=?,submission_id=?,created_at=? WHERE id=?",
1068
- (content["expert"], content["question"], content["submission_id"], content["created_at"], slot["id"]))
1069
-
1070
-
1071
- def answered_chain(connection, payload, actor):
1072
- """The chain an answer continues: the newest chain among the requests it completes."""
1073
- if actor["access"] == "manual":
1074
- ids = payload.get("request_ids") or [0]
1075
- marks = ",".join("?" * len(ids))
1076
- row = connection.execute(f"SELECT MAX(chain_id) FROM member_requests WHERE id IN ({marks})", ids).fetchone()
1077
- else:
1078
- row = connection.execute("SELECT MAX(chain_id) FROM member_requests WHERE execution_id=?", (payload["execution_id"],)).fetchone()
1079
- return row[0] or 0
1080
-
1081
-
1082
- def after_free_message(connection, room_id, message_id, actor, payload):
1083
- """Create requests for the owner's message, or close what the member's answer covers."""
1084
- now = int(time.time())
1085
- if actor == "用户":
1086
- from .session_room import create_host_request, current_session
1087
- session = current_session(connection, room_id, active_only=True)
1088
- if session and session["status"] == "active" and payload.get("to") is None:
1089
- create_host_request(connection, session["id"],
1090
- f"用户留言 #{message_id}:请处理并决定是否安排专家。",
1091
- {"kind": "user_message", "message_id": message_id, "key": f"message-{message_id}"})
1092
- connection.execute("UPDATE session_state SET held_since=?,revision=revision+1 WHERE session_id=?",
1093
- (message_id, session["id"]))
1094
- return
1095
- pairs = recipients(connection, room_id, payload)
1096
- if payload.get("sequential") is True and payload.get("to") is not None:
1097
- queue_in_turn(connection, room_id, message_id, [member_id for member_id, _ in pairs])
1098
- return
1099
- for member_id, purpose in pairs:
1100
- insert_request(connection, room_id, member_id, message_id, message_id, purpose, "user")
1101
- return
1102
- if actor.get("manual_source") == "web":
1103
- for request_id in payload.get("request_ids", []):
1104
- connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE id=?", (message_id, request_id))
1105
- settle_batches(connection, room_id)
1106
- return
1107
- chain_id = answered_chain(connection, payload, actor)
1108
- if actor["access"] == "manual":
1109
- for request_id in payload.get("request_ids", []):
1110
- connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE id=?", (message_id, request_id))
1111
- else:
1112
- execution_id = payload["execution_id"]
1113
- connection.execute("UPDATE member_executions SET status='completed',finished_at=?,result=? WHERE id=?",
1114
- (now, f"message:{message_id}", execution_id))
1115
- connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE execution_id=? AND status='delivering'",
1116
- (message_id, execution_id))
1117
- connection.execute("UPDATE room_members SET read_until=MAX(read_until,?) WHERE id=?", (message_id, actor["id"]))
1118
- if actor["role"] == "host" and payload.get("to"):
1119
- dispatch(connection, room_id, actor, message_id, payload["to"], chain_id, payload.get("handoff") is True)
1120
- settle_batches(connection, room_id)
1121
-
1122
-
1123
- def discussion_host_handles(connection, room):
1124
- """A running discussion already wakes its host for every user message, so a question to the host needs no request of its own."""
1125
- return room["phase"] not in ("paused", "concluded") and bool(connection.execute(
1126
- "SELECT 1 FROM discussion_runtime WHERE room_id=? AND status='running'", (room["id"],)).fetchone())
1127
-
1128
-
1129
- def checked_asks(connection, room, payload):
1130
- """Validate the user's direct questions to members of a discussion before the message is stored."""
1131
- names = payload.get("to")
1132
- if names is None:
1133
- return []
1134
- return named_members(active_members(connection, room["id"]), names)
1135
-
1136
-
1137
- def ask_members(connection, room, message_id, member_ids):
1138
- """Queue one 'ask' request per named member, outside the discussion's turns, rounds and limits."""
1139
- host_busy = discussion_host_handles(connection, room)
1140
- for member_id in member_ids:
1141
- row = connection.execute("SELECT name FROM room_members WHERE id=?", (member_id,)).fetchone()
1142
- if host_busy and row["name"] == room["host"]:
1143
- continue
1144
- insert_request(connection, room["id"], member_id, message_id, message_id, "ask", "user")
1145
-
1146
-
1147
- def asks_view(connection, room_id):
1148
- """Direct questions of a discussion room: recent requests with their member, for status badges beside messages."""
1149
- names = {row["id"]: row["name"] for row in connection.execute("SELECT id,name FROM room_members WHERE room_id=?", (room_id,))}
1150
- requests = [{**dict(row), "member": names.get(row["member_id"], "")} for row in connection.execute(
1151
- """SELECT id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose,created_by,created_at,
1152
- (SELECT reason FROM request_cancel_reasons c WHERE c.request_id=member_requests.id) AS cancel_reason FROM member_requests
1153
- WHERE room_id=? ORDER BY id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
1154
- return {"requests": requests[::-1], "executions": recent_executions(connection, room_id), "execution_minutes": execution_minutes(connection, room_id)}
1155
-
1156
-
1157
- def expire_executions(connection, room_id):
1158
- """Fail executions whose lease lapsed; their requests stay visible as failed, never silently retried."""
1159
- now = int(time.time())
1160
- limit_seconds = execution_minutes(connection, room_id) * 60
1161
- stale = connection.execute(
1162
- "SELECT id,created_at,lease_until FROM member_executions WHERE room_id=? AND status IN ('dispatched','started') AND lease_until<=?", (room_id, now)).fetchall()
1163
- for row in stale:
1164
- reason = "已达到单次执行时限" if row["lease_until"] >= row["created_at"] + limit_seconds else "执行租约到期,接入程序未续租"
1165
- finish_execution(connection, row["id"], "failed", reason, "failed")
1166
- if stale:
1167
- settle_batches(connection, room_id)
1168
-
1169
-
1170
- def record_cancel_reasons(connection, where, params, reason):
1171
- """Remember why requests are about to be cancelled; call before the status change selects them."""
1172
- connection.execute(f"INSERT OR REPLACE INTO request_cancel_reasons (request_id,reason) SELECT id,? FROM member_requests WHERE {where}", (reason, *params))
1173
-
1174
-
1175
- def finish_execution(connection, execution_id, status, result, request_status, cancel_reason=""):
1176
- """End one execution and move its delivered requests in the same transaction."""
1177
- if request_status == "cancelled" and cancel_reason:
1178
- record_cancel_reasons(connection, "execution_id=? AND status='delivering'", (execution_id,), cancel_reason)
1179
- session_requests = connection.execute("""SELECT r.id FROM member_requests r JOIN session_requests sr
1180
- ON sr.member_request_id=r.id WHERE r.execution_id=? AND sr.purpose='discuss' AND sr.status='open'""",
1181
- (execution_id,)).fetchall()
1182
- connection.execute("UPDATE member_executions SET status=?,finished_at=?,result=? WHERE id=? AND status IN ('dispatched','started')",
1183
- (status, int(time.time()), result[:500], execution_id))
1184
- connection.execute("UPDATE member_requests SET status=?,execution_id=CASE WHEN ?='pending' THEN NULL ELSE execution_id END WHERE execution_id=? AND status='delivering'",
1185
- (request_status, request_status, execution_id))
1186
- if status == "failed" and request_status == "failed":
1187
- from .session_room import fail_session_request
1188
- for row in session_requests:
1189
- fail_session_request(connection, row["id"], result)
1190
-
1191
-
1192
- def open_route_messages(connection, member_id, pending_only=False):
1193
- """(message, purpose) of host requests still open, in order; they need a new host if this one leaves."""
1194
- states = "'pending'" if pending_only else "'pending','delivering'"
1195
- return [(row[0], row[1]) for row in connection.execute(
1196
- f"""SELECT message_id,purpose FROM member_requests WHERE member_id=? AND purpose IN ('route','group')
1197
- AND status IN ({states}) ORDER BY message_id""", (member_id,))]
1198
-
1199
-
1200
- def hand_over_routes(connection, room_id, routes, departed_id):
1201
- """Ask the current host to route messages left behind by the previous host."""
1202
- host = connection.execute("SELECT id FROM room_members WHERE room_id=? AND role='host' AND status='active' AND id<>?",
1203
- (room_id, departed_id or 0)).fetchone()
1204
- for message_id, purpose in routes if host else []:
1205
- connection.execute("""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1206
- VALUES (?,?,?,?,?,'user',?)""", (room_id, host["id"], message_id, message_id, purpose, int(time.time())))
1207
-
1208
-
1209
- def stop_member_work(connection, member_id, reason, cancel_reason):
1210
- """Void a member's live execution and every open request, so nothing restarts by itself."""
1211
- for row in connection.execute("SELECT id FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
1212
- (member_id,)).fetchall():
1213
- finish_execution(connection, row["id"], "cancelled", reason, "cancelled", cancel_reason)
1214
- record_cancel_reasons(connection, "member_id=? AND status='pending'", (member_id,), cancel_reason)
1215
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE member_id=? AND status='pending'", (member_id,))
1216
- from .session_room import advance_session, create_host_request, current_session
1217
-
1218
- member = connection.execute("SELECT room_id,name FROM room_members WHERE id=?", (member_id,)).fetchone()
1219
- session = current_session(connection, member["room_id"], active_only=True) if member else None
1220
- if not session:
1221
- return
1222
- plans = connection.execute("""SELECT id,member_request_id FROM session_requests
1223
- WHERE session_id=? AND member_id=? AND purpose='discuss' AND status='open'""",
1224
- (session["id"], member_id)).fetchall()
1225
- for plan in plans:
1226
- connection.execute("UPDATE session_requests SET status='cancelled' WHERE id=?", (plan["id"],))
1227
- if not plans:
1228
- return
1229
- connection.execute("UPDATE session_state SET revision=revision+1 WHERE session_id=?", (session["id"],))
1230
- if advance_session(connection, session["id"]):
1231
- return
1232
- request_id = plans[0]["member_request_id"]
1233
- create_host_request(connection, session["id"],
1234
- f"专家 {member['name']} 的讨论发言已被打断,请检查余下安排并决定如何继续。",
1235
- {"kind": "request_failed", "request_id": request_id, "key": f"interrupted-{request_id or plans[0]['id']}"})
1236
-
1237
-
1238
- def stop_room_work(connection, room_id, reason, cancel_reason):
1239
- """Void every live execution and open request of a room, e.g. when it is archived."""
1240
- for row in connection.execute("SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')",
1241
- (room_id,)).fetchall():
1242
- finish_execution(connection, row["id"], "cancelled", reason, "cancelled", cancel_reason)
1243
- record_cancel_reasons(connection, "room_id=? AND status='pending'", (room_id,), cancel_reason)
1244
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND status='pending'", (room_id,))
1245
- settle_batches(connection, room_id)
1246
-
1247
-
1248
- def inbox(connection, room_id, token):
1249
- """List what the runner should deliver or reconcile; owner credential only."""
1250
- require_owner(connection, room_id, token)
1251
- begin_write(connection)
1252
- enforce_session_limits(connection, room_id)
1253
- expire_executions(connection, room_id)
1254
- release_recommendations(connection, room_id)
1255
- archived = connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0]
1256
- members, observers = [], []
1257
- # Manual and online members are never delivered to; the runner only reads them so smart scheduling can route to them too.
1258
- for row in connection.execute(f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER} ORDER BY id", (room_id,)):
1259
- pending = [dict(item) for item in connection.execute("""SELECT r.id,r.message_id,r.purpose,
1260
- sr.id AS session_request_id,sr.session_id,sr.round,sr.position,sr.read_until,sr.question AS source_question,
1261
- t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id
1262
- FROM member_requests r LEFT JOIN session_requests sr ON sr.member_request_id=r.id
1263
- LEFT JOIN task_message_sources t ON t.session_request_id=sr.id
1264
- WHERE r.member_id=? AND r.status='pending' ORDER BY r.id""", (row["id"],))]
1265
- manual_source = connection.execute("SELECT source FROM member_manual_sources WHERE member_id=?", (row["id"],)).fetchone()
1266
- member_view = {key: row[key] for key in MEMBER_FIELDS}
1267
- member_view["manual_source"] = manual_source[0] if manual_source else ""
1268
- (members if row["access"] == "runner" else observers).append({**member_view, "pending": pending})
1269
- executions = [{**public_execution(row), "member": row["name"], "retry": execution_retry(connection, row["id"])} for row in connection.execute(
1270
- """SELECT member_executions.*,room_members.name FROM member_executions JOIN room_members ON room_members.id=member_id
1271
- WHERE member_executions.room_id=? AND member_executions.status IN ('dispatched','started') ORDER BY member_executions.id""", (room_id,))]
1272
- return {"room_id": room_id, "archived": bool(archived), "members": members, "observers": observers, "executions": executions,
1273
- "execution_minutes": execution_minutes(connection, room_id)}
1274
-
1275
-
1276
- def host_route_request(connection, message_id):
1277
- """The host's request for one unnamed owner message, if the message was routed."""
1278
- return connection.execute("SELECT * FROM member_requests WHERE message_id=? AND purpose='route'", (message_id,)).fetchone()
1279
-
1280
-
1281
- def recommend_member(connection, room_id, token, payload):
1282
- """Smart scheduling suggests another member for an unnamed message; the host keeps it until the user adopts."""
1283
- require_owner(connection, room_id, token)
1284
- begin_write(connection)
1285
- confidence = payload.get("confidence")
1286
- if payload.get("provider") not in SCHEDULER_PROVIDERS or type(confidence) not in (int, float) or not 0 <= confidence <= 1:
1287
- raise ValueError("须提供智能调度供应商 provider 与 0–1 的置信度 confidence")
1288
- message_id = payload.get("message_id")
1289
- route = host_route_request(connection, message_id) if type(message_id) is int else None
1290
- if not route or route["room_id"] != room_id:
1291
- raise LookupError("只能为交给主持人的未点名消息给出推荐")
1292
- target = connection.execute(f"""SELECT * FROM room_members WHERE room_id=? AND id=? AND status='active'
1293
- AND {REGISTERED_MEMBER} AND id<>?""", (room_id, payload.get("member_id"), route["member_id"])).fetchone()
1294
- if not target:
1295
- raise LookupError("推荐对象须为在场的其他成员")
1296
- now = int(time.time())
1297
- connection.execute("""INSERT OR IGNORE INTO member_recommendations (message_id,room_id,member_id,provider,confidence,created_at,expires_at)
1298
- VALUES (?,?,?,?,?,?,?)""", (message_id, room_id, target["id"], payload["provider"], float(confidence), now, now + RECOMMEND_SECONDS))
1299
- return dict(connection.execute("SELECT * FROM member_recommendations WHERE message_id=?", (message_id,)).fetchone())
1300
-
1301
-
1302
- def release_recommendations(connection, room_id):
1303
- """Ask each adopted-later member once the host's request for that message has ended in any way."""
1304
- for row in connection.execute("""SELECT rec.* FROM member_recommendations rec JOIN member_requests r ON r.message_id=rec.message_id AND r.purpose='route'
1305
- WHERE rec.room_id=? AND rec.status='waiting' AND r.status IN ('completed','cancelled','failed')""", (room_id,)).fetchall():
1306
- connection.execute("UPDATE member_recommendations SET status='adopted' WHERE message_id=?", (row["message_id"],))
1307
- if connection.execute("SELECT 1 FROM room_members WHERE id=? AND status='active'", (row["member_id"],)).fetchone():
1308
- connection.execute("""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1309
- VALUES (?,?,?,?,'ask','user',?)""", (room_id, row["member_id"], row["message_id"], row["message_id"], int(time.time())))
1310
-
1311
-
1312
- def route_wide(connection, room_id, message_id, action):
1313
- """Smart scheduling answers an unnamed message with everyone (each member once, as if the user named them all) or no one.
1314
-
1315
- A message naming everyone (a group request) is answered by all at once or, with action sequential, one after another.
1316
- Only a host request that has not started changes; a started host already handles the message its own way.
1317
- """
1318
- route = host_route_request(connection, message_id)
1319
- group = connection.execute("SELECT * FROM member_requests WHERE message_id=? AND purpose='group'", (message_id,)).fetchone()
1320
- if group and group["room_id"] == room_id:
1321
- if action not in ("all", "sequential"):
1322
- raise ValueError("请全体成员回应的消息只能选 action=all 或 sequential")
1323
- if group["status"] != "pending":
1324
- raise FileExistsError("这条消息已不再等待安排")
1325
- if action == "sequential":
1326
- # The row is removed rather than ended so the host takes its place in the queue like everyone else.
1327
- connection.execute("DELETE FROM member_requests WHERE id=?", (group["id"],))
1328
- members = connection.execute(f"SELECT id FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER}", (room_id,))
1329
- queue_in_turn(connection, room_id, message_id, [row["id"] for row in members])
1330
- requests = connection.execute("SELECT * FROM member_requests WHERE message_id=? ORDER BY id", (message_id,)).fetchall()
1331
- return {"action": action, "requests": [dict(row) for row in requests]}
1332
- route = group
1333
- elif action == "sequential":
1334
- raise ValueError("只有请全体成员回应的消息可以依次回答")
1335
- if not route or route["room_id"] != room_id:
1336
- raise LookupError("只能处理交给主持人的未点名消息")
1337
- if route["status"] != "pending":
1338
- raise FileExistsError("主持人已开始处理这条消息,不再改派")
1339
- if action == "none":
1340
- record_cancel_reasons(connection, "id=?", (route["id"],), "no_reply")
1341
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE id=?", (route["id"],))
1342
- else:
1343
- # The host keeps its row (one request per message and member) and now answers its own share, without dispatching.
1344
- connection.execute("UPDATE member_requests SET purpose='all' WHERE id=?", (route["id"],))
1345
- connection.execute(f"""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1346
- SELECT room_id,id,?,?,'all','user',? FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER} ORDER BY id""",
1347
- (message_id, message_id, int(time.time()), room_id))
1348
- requests = connection.execute("SELECT * FROM member_requests WHERE message_id=? ORDER BY id", (message_id,)).fetchall()
1349
- return {"action": action, "requests": [dict(row) for row in requests]}
1350
-
1351
-
1352
- def adopt_recommendation(connection, room_id, token, message_id, payload):
1353
- """The user adopts a recommendation before it expires: interrupt the host now, or ask the member after the host.
1354
-
1355
- Smart scheduling also sends action all or none here to have everyone or no one answer an unnamed message.
1356
- """
1357
- require_owner(connection, room_id, token)
1358
- begin_write(connection)
1359
- if payload.get("action") in ("all", "none", "sequential"):
1360
- return route_wide(connection, room_id, message_id, payload["action"])
1361
- if payload.get("action") != "adopt" or payload.get("mode") not in ("interrupt", "after"):
1362
- raise ValueError("采纳须为 action=adopt,mode 为 interrupt 或 after;全体、依次或无需回应为 action=all、sequential 或 none")
1363
- row = connection.execute("SELECT * FROM member_recommendations WHERE room_id=? AND message_id=?", (room_id, message_id)).fetchone()
1364
- if not row:
1365
- raise LookupError("这条消息没有智能调度推荐")
1366
- if row["status"] != "open":
1367
- return {"recommendation": dict(row), "duplicate": True}
1368
- if int(time.time()) > row["expires_at"] + RECOMMEND_GRACE_SECONDS:
1369
- raise FileExistsError("推荐已过期,可直接 @ 该成员")
1370
- if not connection.execute("SELECT 1 FROM room_members WHERE id=? AND status='active'", (row["member_id"],)).fetchone():
1371
- raise FileExistsError("推荐的成员已离开")
1372
- route = host_route_request(connection, message_id)
1373
- mode = payload["mode"]
1374
- if mode == "interrupt" and route["status"] == "delivering":
1375
- # The host's execution may carry other messages too; stopping it voids that whole execution.
1376
- finish_execution(connection, route["execution_id"], "cancelled", "智能调度改派,改由其他成员回答", "cancelled", "rerouted")
1377
- elif mode == "interrupt" and route["status"] == "pending":
1378
- record_cancel_reasons(connection, "id=?", (route["id"],), "rerouted")
1379
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE id=?", (route["id"],))
1380
- connection.execute("UPDATE member_recommendations SET status='waiting',mode=? WHERE message_id=?", (mode, message_id))
1381
- release_recommendations(connection, room_id)
1382
- settle_batches(connection, room_id)
1383
- return {"recommendation": dict(connection.execute("SELECT * FROM member_recommendations WHERE message_id=?", (message_id,)).fetchone()),
1384
- "duplicate": False}
1385
-
1386
-
1387
- def recent_recommendations(connection, room_id, now):
1388
- """Recommendations shown beside their messages, with seconds left to adopt an open one."""
1389
- return [{**dict(row), "expires_in": max(0, row["expires_at"] - now)} for row in connection.execute(
1390
- """SELECT rec.*,m.name AS member FROM member_recommendations rec JOIN room_members m ON m.id=rec.member_id
1391
- WHERE rec.room_id=? ORDER BY rec.message_id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
1392
-
1393
-
1394
- def reserve_execution(connection, room_id, token, payload):
1395
- """Bundle a member's open requests into one execution; a retried client_id returns the same one."""
1396
- require_owner(connection, room_id, token)
1397
- begin_write(connection)
1398
- if enforce_session_limits(connection, room_id):
1399
- connection.commit()
1400
- client_id = str(payload.get("client_id", ""))
1401
- if not 8 <= len(client_id) <= 100:
1402
- raise ValueError("client_id 须为 8–100 字符的本地投递编号")
1403
- previous = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND client_id=?", (room_id, client_id)).fetchone()
1404
- if previous:
1405
- return execution_detail(connection, previous)
1406
- expire_executions(connection, room_id)
1407
- if connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0]:
1408
- raise FileExistsError("房间已存档,不再投递")
1409
- member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND id=? AND status='active' AND access='runner'",
1410
- (room_id, payload.get("member_id"))).fetchone()
1411
- if not member:
1412
- raise LookupError("成员不存在、已离开或为手动接入")
1413
- if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
1414
- (member["id"],)).fetchone():
1415
- raise FileExistsError("该成员已有进行中的执行;同一会话不并发续接")
1416
- # A group request waits for the runner to choose how everyone answers; it is never delivered itself.
1417
- pending = connection.execute("""SELECT purpose FROM member_requests
1418
- WHERE member_id=? AND status='pending' AND purpose<>'group' ORDER BY id""", (member["id"],)).fetchall()
1419
- session_purpose = next((row["purpose"] for row in pending if row["purpose"] == "discuss"), None)
1420
- if not pending:
1421
- raise FileExistsError("该成员没有待投递的请求")
1422
- if session_purpose:
1423
- request_filter = "purpose=?"
1424
- request_values = (session_purpose,)
1425
- else:
1426
- request_filter = "purpose<>'group'"
1427
- request_values = ()
1428
- now = int(time.time())
1429
- cursor = connection.execute("""INSERT INTO member_executions (room_id,member_id,client_id,lease_until,created_at,cwd)
1430
- VALUES (?,?,?,?,?,?)""", (room_id, member["id"], client_id, now + LEASE_SECONDS, now, str(payload.get("cwd") or "")[:MAX_PATH_LENGTH]))
1431
- connection.execute(f"UPDATE member_requests SET status='delivering',execution_id=? WHERE member_id=? AND status='pending' AND {request_filter}",
1432
- (cursor.lastrowid, member["id"], *request_values))
1433
- return execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (cursor.lastrowid,)).fetchone())
1434
-
1435
-
1436
- def execution_detail(connection, row):
1437
- """Describe one execution with the requests it carries and the member's read cursor."""
1438
- member = connection.execute("SELECT * FROM room_members WHERE id=?", (row["member_id"],)).fetchone()
1439
- requests = [dict(item) for item in connection.execute("""SELECT r.id,r.message_id,r.status,r.purpose,
1440
- sr.id AS session_request_id,sr.session_id,sr.round,sr.position,sr.read_until,sr.question AS source_question,
1441
- t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id
1442
- FROM member_requests r LEFT JOIN session_requests sr ON sr.member_request_id=r.id
1443
- LEFT JOIN task_message_sources t ON t.session_request_id=sr.id
1444
- WHERE r.execution_id=? ORDER BY r.id""", (row["id"],))]
1445
- return {**public_execution(row), "member": member["name"], "read_until": member["read_until"], "requests": requests,
1446
- "rewound_executions": member_rewinds(connection, member["id"]), "retry": execution_retry(connection, row["id"])}
1447
-
1448
-
1449
- def view_execution(connection, room_id, execution_id, token):
1450
- """Let the owner or the executing member read one execution."""
1451
- row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
1452
- if not row:
1453
- raise LookupError("执行不存在")
1454
- try:
1455
- require_owner(connection, room_id, token)
1456
- except PermissionError:
1457
- member = require_member(connection, room_id, token)
1458
- if member["id"] != row["member_id"]:
1459
- raise
1460
- return execution_detail(connection, row)
1461
-
1462
-
1463
- def changed_files(payload):
1464
- """Validate the runner's observed file list; paths are relative to the execution's cwd."""
1465
- files = payload.get("changes")
1466
- if (not isinstance(files, list) or len(files) > MAX_CHANGED_FILES
1467
- or any(not isinstance(item, str) or not item or len(item) > MAX_PATH_LENGTH for item in files)):
1468
- raise ValueError(f"changes 须为最多 {MAX_CHANGED_FILES} 个相对路径")
1469
- return sorted(set(files))
1470
-
1471
-
1472
- def denied_actions(payload):
1473
- """Validate the operations a member's software refused: the tool, what it tried, and the rule that would allow it."""
1474
- denials = payload.get("denials")
1475
- def valid(item):
1476
- return (isinstance(item, dict) and isinstance(item.get("tool"), str) and 0 < len(item["tool"]) <= 40
1477
- and all(isinstance(item.get(key, ""), str) and len(item.get(key, "")) <= MAX_DENIAL_FIELD for key in ("detail", "rule")))
1478
- if not isinstance(denials, list) or not 0 < len(denials) <= MAX_DENIALS or not all(map(valid, denials)):
1479
- raise ValueError(f"denials 须为 1–{MAX_DENIALS} 条 {{tool, detail, rule}}")
1480
- return [{key: item.get(key, "") for key in ("tool", "detail", "rule")} for item in denials]
1481
-
1482
-
1483
- def renewed_activity(payload, row, now):
1484
- """Validate the runner's reported phase; its output time is kept within the execution, since the runner's clock may differ."""
1485
- activity, activity_at = payload.get("activity"), payload.get("activity_at")
1486
- if activity not in ACTIVITY_PHASES:
1487
- raise ValueError(f"activity 须为 {'、'.join(item for item in ACTIVITY_PHASES if item)} 或空")
1488
- if type(activity_at) is not int:
1489
- raise ValueError("activity_at 须为秒级时间戳")
1490
- return activity, min(max(activity_at, row["created_at"]), now)
1491
-
1492
-
1493
- def renewed_notes(payload):
1494
- """Validate progress notes carried by a renewal; a repeated sequence number is the same note resent."""
1495
- notes = payload.get("notes", [])
1496
- if (not isinstance(notes, list) or len(notes) > MAX_NOTES_PER_RENEW or any(
1497
- not isinstance(note, dict) or type(note.get("seq")) is not int or not 1 <= note["seq"] <= MAX_EXECUTION_NOTES
1498
- or not isinstance(note.get("text"), str) or not 0 < len(note["text"]) <= MAX_NOTE_LENGTH for note in notes)):
1499
- raise ValueError(f"notes 须为最多 {MAX_NOTES_PER_RENEW} 条 {{seq: 1–{MAX_EXECUTION_NOTES}, text: 1–{MAX_NOTE_LENGTH} 字}}")
1500
- return notes
1501
-
1502
-
1503
- def execution_action(connection, room_id, execution_id, token, payload):
1504
- """Runner-side lifecycle: renew, fail, release undelivered work, or report observed file changes."""
1505
- begin_write(connection)
1506
- action = payload.get("action")
1507
- member = None
1508
- if action == "fail":
1509
- try:
1510
- require_owner(connection, room_id, token)
1511
- except PermissionError:
1512
- member = require_member(connection, room_id, token)
1513
- else:
1514
- require_owner(connection, room_id, token)
1515
- if enforce_session_limits(connection, room_id):
1516
- connection.commit()
1517
- row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
1518
- if not row:
1519
- raise LookupError("执行不存在")
1520
- if member and member["id"] != row["member_id"]:
1521
- raise PermissionError("只能报告自己执行的失败")
1522
- now = int(time.time())
1523
- if action == "report":
1524
- # Observed after the process ends, so the execution may already be complete; recorded once.
1525
- if row["changes"]:
1526
- raise FileExistsError("本次执行的改动已记录")
1527
- connection.execute("UPDATE member_executions SET changes=? WHERE id=?", (json.dumps(changed_files(payload), ensure_ascii=False), execution_id))
1528
- elif action == "denials":
1529
- # Like file changes, read from the software's output once its process ends; recorded once.
1530
- saved = connection.execute("INSERT OR IGNORE INTO execution_denials (execution_id,room_id,denials) VALUES (?,?,?)",
1531
- (execution_id, room_id, json.dumps(denied_actions(payload), ensure_ascii=False)))
1532
- if not saved.rowcount:
1533
- raise FileExistsError("本次执行的拒绝记录已记录")
1534
- elif action == "segments":
1535
- # The last segments and notes arrive after the member's answer ended the execution; such notes are dated at its end.
1536
- finished = 0 if row["status"] in ACTIVE else (row["finished_at"] or 1)
1537
- notes = renewed_notes(payload)
1538
- save_segments(connection, "free", room_id, execution_id, row["created_at"], finished, payload, optional=bool(notes))
1539
- connection.executemany("INSERT OR IGNORE INTO execution_notes (execution_id,seq,room_id,text,created_at) VALUES (?,?,?,?,?)",
1540
- [(execution_id, note["seq"], room_id, note["text"], min(now, finished) if finished else now) for note in notes])
1541
- elif row["status"] not in ACTIVE:
1542
- raise FileExistsError("执行已结束")
1543
- elif action == "renew":
1544
- limit = row["created_at"] + execution_minutes(connection, room_id) * 60
1545
- if row["lease_until"] <= now or limit <= now:
1546
- raise FileExistsError("执行租约或单次时限已到,不能续租")
1547
- # Older runners renew without activity; the last reported one is kept.
1548
- activity, activity_at = renewed_activity(payload, row, now) if "activity" in payload else (row["activity"], row["activity_at"])
1549
- notes = renewed_notes(payload)
1550
- connection.execute("UPDATE member_executions SET lease_until=?,activity=?,activity_at=? WHERE id=?",
1551
- (min(now + LEASE_SECONDS, limit), activity, activity_at, execution_id))
1552
- connection.executemany("INSERT OR IGNORE INTO execution_notes (execution_id,seq,room_id,text,created_at) VALUES (?,?,?,?,?)",
1553
- [(execution_id, note["seq"], room_id, note["text"], now) for note in notes])
1554
- elif action == "retry_wait":
1555
- # A manual member's session refused the delivery: the runner keeps the execution and delivers again at retry_at.
1556
- attempt, retry_at, reason = payload.get("attempt"), payload.get("retry_at"), payload.get("reason")
1557
- if (type(attempt) is not int or not 1 <= attempt <= MAX_RETRIES or type(retry_at) is not int or retry_at <= 0
1558
- or not isinstance(reason, str) or not 0 < len(reason) <= MAX_RETRY_REASON):
1559
- raise ValueError(f"retry_wait 须带 attempt(1–{MAX_RETRIES})、秒级 retry_at 与 reason(最多 {MAX_RETRY_REASON} 字)")
1560
- connection.execute("""INSERT INTO execution_retries (execution_id,room_id,attempt,retry_at,reason,stopped) VALUES (?,?,?,?,?,0)
1561
- ON CONFLICT(execution_id) DO UPDATE SET attempt=excluded.attempt,retry_at=excluded.retry_at,reason=excluded.reason,stopped=0""",
1562
- (execution_id, room_id, attempt, retry_at, reason))
1563
- elif action == "retry_start":
1564
- connection.execute("UPDATE execution_retries SET retry_at=0 WHERE execution_id=?", (execution_id,))
1565
- elif action in ("retry_now", "retry_stop"):
1566
- # The owner's answer to a waiting retry: deliver now, or stop so the runner fails the execution.
1567
- change = "retry_at=?" if action == "retry_now" else "stopped=1"
1568
- updated = connection.execute(f"UPDATE execution_retries SET {change} WHERE execution_id=? AND retry_at>0 AND stopped=0",
1569
- ((now, execution_id) if action == "retry_now" else (execution_id,)))
1570
- if not updated.rowcount:
1571
- raise FileExistsError("本次执行没有在等待自动重试")
1572
- elif action == "fail":
1573
- finish_execution(connection, execution_id, "failed", str(payload.get("reason") or "执行失败"), "failed")
1574
- settle_batches(connection, room_id)
1575
- elif action == "release":
1576
- # Only for proven non-delivery: the requests return to the queue unchanged.
1577
- finish_execution(connection, execution_id, "cancelled", str(payload.get("reason") or "未送达"), "pending")
1578
- else:
1579
- raise ValueError("action 须为 renew、fail、release、report、segments、retry_wait、retry_start、retry_now 或 retry_stop")
1580
- return execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (execution_id,)).fetchone())
1581
-
1582
-
1583
- def owned_member(connection, room_id, member_id, token):
1584
- """Read one member after proving the owner's credential."""
1585
- require_owner(connection, room_id, token)
1586
- begin_write(connection)
1587
- member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND id=?", (room_id, member_id)).fetchone()
1588
- if not member or member["status"] == "removed":
1589
- raise LookupError("成员不存在")
1590
- return member
1591
-
1592
-
1593
- def interrupt_member(connection, room_id, member_id, token):
1594
- """Owner stop: void the live execution and every open request."""
1595
- owned_member(connection, room_id, member_id, token)
1596
- stop_member_work(connection, member_id, "用户打断", "user_stop")
1597
- settle_batches(connection, room_id)
1598
- return free_view(connection, room_id)
1599
-
1600
-
1601
- def withdrawals(connection, room_id):
1602
- """The room's taken-back messages by id, so the page keeps them in place while AI readers skip them."""
1603
- return [dict(row) for row in connection.execute("""SELECT w.message_id,w.kind FROM message_withdrawals w
1604
- JOIN messages m ON m.id=w.message_id WHERE m.room_id=? ORDER BY w.message_id""", (room_id,))]
1605
-
1606
-
1607
- def owner_message(connection, room_id, message_id):
1608
- """One visible message of the user in a free room without an open discussion, which a retract or rewind may take back."""
1609
- row = connection.execute("SELECT * FROM messages WHERE room_id=? AND id=?", (room_id, message_id)).fetchone()
1610
- if not row:
1611
- raise LookupError("消息不存在")
1612
- if row["author"] != "用户":
1613
- raise ValueError("只能撤回或编辑用户自己的消息")
1614
- if room_mode(connection, room_id) != "free":
1615
- raise ValueError("只有协作房间的消息可以撤回或编辑")
1616
- if connection.execute("SELECT 1 FROM room_directory WHERE room_id=? AND archived=1", (room_id,)).fetchone():
1617
- raise ValueError("房间已存档;恢复后才能撤回或编辑")
1618
- # A discussion's host reads the user's messages itself, with no request that shows whether it began.
1619
- if connection.execute("SELECT 1 FROM discussion_sessions WHERE room_id=? AND (status IN ('active','paused') OR started_message_id>=?)",
1620
- (room_id, message_id)).fetchone():
1621
- raise FileExistsError("讨论进行中,或这条消息之后开启过讨论,不能撤回或编辑")
1622
- return row
1623
-
1624
-
1625
- def retract_message(connection, room_id, message_id, token):
1626
- """Owner takes back a message no member began to handle: its queued requests end and AI readers no longer see it.
1627
-
1628
- Bound to one known message, so it takes no revision; a message any member started, answered or failed is refused.
1629
- A member working on an earlier message may still have read it, which the room cannot know.
1630
-
1631
- Returns:
1632
- `{"message_id", "text", "duplicate"}`; the text lets the page put it back in the input for editing.
1633
- """
1634
- require_owner(connection, room_id, token)
1635
- begin_write(connection)
1636
- message = owner_message(connection, room_id, message_id)
1637
- if connection.execute("SELECT 1 FROM message_withdrawals WHERE message_id=?", (message_id,)).fetchone():
1638
- return {"message_id": message_id, "text": message["text"], "duplicate": True}
1639
- if connection.execute("SELECT 1 FROM member_requests WHERE message_id=? AND status IN ('delivering','completed','failed')", (message_id,)).fetchone():
1640
- raise FileExistsError("已有成员开始处理这条消息,不能撤回;可以编辑这条消息回退到它之前")
1641
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE message_id=? AND status='pending'", (message_id,))
1642
- connection.execute("DELETE FROM free_queue WHERE message_id=?", (message_id,))
1643
- connection.execute("INSERT INTO message_withdrawals (message_id,kind,created_at) VALUES (?,'retracted',?)", (message_id, int(time.time())))
1644
- settle_batches(connection, room_id)
1645
- return {"message_id": message_id, "text": message["text"], "duplicate": False}
1646
-
1647
-
1648
- # Software whose session the runner can cut before a taken-back execution; an API member rebuilds its context each time.
1649
- CUTTABLE_ADAPTERS = ("claude", "codex", "codex_cli", "antigravity_cli")
1650
- # Executions a rewind takes back: any touching a message from the rewind point on, and any still running.
1651
- REWOUND_EXECUTIONS = """SELECT e.id,e.member_id FROM member_executions e WHERE e.room_id=? AND (e.status IN ('dispatched','started')
1652
- OR EXISTS(SELECT 1 FROM member_requests r WHERE r.execution_id=e.id AND (r.message_id>=? OR r.answer_id>=?))) ORDER BY e.id"""
1653
-
1654
-
1655
- def rewind_plan(connection, room_id, message_id):
1656
- """What rewinding to just before a message takes back, and a revision of the state it was read from.
1657
-
1658
- Each member reports what happens to its session: `cut` (the runner cuts it before the first taken-back execution),
1659
- `fresh` (an API member, which rebuilds its context), `unchanged` (no taken-back execution) or `kept` (manual, online or
1660
- App software whose own window keeps what it saw).
1661
- """
1662
- owner_message(connection, room_id, message_id)
1663
- if connection.execute("SELECT 1 FROM message_withdrawals WHERE message_id=?", (message_id,)).fetchone():
1664
- raise FileExistsError("这条消息已被撤回或回退")
1665
- executions = {}
1666
- for row in connection.execute(REWOUND_EXECUTIONS, (room_id, message_id, message_id)):
1667
- executions.setdefault(row["member_id"], []).append(row["id"])
1668
- members = []
1669
- for row in connection.execute("SELECT id,name,access,adapter FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id", (room_id,)):
1670
- taken = executions.get(row["id"], [])
1671
- session = ("kept" if row["access"] != "runner" or row["adapter"] not in (*CUTTABLE_ADAPTERS, "api")
1672
- else "unchanged" if not taken else "fresh" if row["adapter"] == "api" else "cut")
1673
- members.append({"id": row["id"], "name": row["name"], "executions": taken, "session": session})
1674
- count = connection.execute("""SELECT COUNT(*) FROM messages m WHERE m.room_id=? AND m.id>=?
1675
- AND NOT EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id=m.id)""", (room_id, message_id)).fetchone()[0]
1676
- latest = connection.execute("SELECT COALESCE(MAX(id),0) FROM messages WHERE room_id=?", (room_id,)).fetchone()[0]
1677
- state = json.dumps([message_id, latest, count, members])
1678
- return {"message_id": message_id, "messages": count, "members": members,
1679
- "revision": hashlib.sha256(state.encode("utf-8")).hexdigest()[:12]}
1680
-
1681
-
1682
- def rewind_room(connection, room_id, token, payload):
1683
- """Owner returns the room to just before one of its messages, as editing that message does.
1684
-
1685
- Read the plan first (`GET rewind?message_id=`) and send its revision: a missing revision is refused and a changed
1686
- one conflicts. The message and everything after it stay on the page but leave AI reads; running work stops, open
1687
- requests on them end, members read again from before the message, and each runner member's session is cut before
1688
- its first taken-back execution when it next works. Files the members changed are not restored.
1689
- """
1690
- require_owner(connection, room_id, token)
1691
- begin_write(connection)
1692
- message_id = payload.get("message_id")
1693
- if type(message_id) is not int:
1694
- raise ValueError("须提供要回退到其之前的消息编号 message_id")
1695
- if payload.get("revision") is None:
1696
- raise ValueError("回退前须先读取回退计划(GET rewind?message_id=),并带上其 revision")
1697
- plan = rewind_plan(connection, room_id, message_id)
1698
- if payload["revision"] != plan["revision"]:
1699
- raise FileExistsError("房间已有新的消息或执行,请重新读取回退计划后再确认")
1700
- now = int(time.time())
1701
- for row in connection.execute("SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')", (room_id,)).fetchall():
1702
- finish_execution(connection, row["id"], "cancelled", "用户回退了对话", "cancelled", "user_stop")
1703
- record_cancel_reasons(connection, "room_id=? AND message_id>=? AND status='pending'", (room_id, message_id), "user_stop")
1704
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND message_id>=? AND status='pending'", (room_id, message_id))
1705
- connection.execute("DELETE FROM free_queue WHERE room_id=? AND message_id>=?", (room_id, message_id))
1706
- # Batches of taken-back dispatches never hand back, and a dispatch the round limit held from them is never sent.
1707
- connection.execute("UPDATE free_batches SET settled=1 WHERE room_id=? AND batch_id>=?", (room_id, message_id))
1708
- connection.execute("UPDATE free_chain_holds SET message_id=0,host_id=0,names='[]',handoff=0 WHERE room_id=? AND message_id>=?", (room_id, message_id))
1709
- connection.execute("""INSERT INTO message_withdrawals (message_id,kind,created_at) SELECT id,'rewound',? FROM messages m
1710
- WHERE m.room_id=? AND m.id>=? AND NOT EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id=m.id)""", (now, room_id, message_id))
1711
- connection.execute("UPDATE room_members SET read_until=MIN(read_until,?) WHERE room_id=?", (message_id - 1, room_id))
1712
- cuts = {str(member["id"]): member["executions"] for member in plan["members"] if member["session"] == "cut"}
1713
- cursor = connection.execute("INSERT INTO room_rewinds (room_id,message_id,cuts,created_at) VALUES (?,?,?,?)",
1714
- (room_id, message_id, json.dumps(cuts), now))
1715
- settle_batches(connection, room_id)
1716
- return {"rewind_id": cursor.lastrowid, **plan}
1717
-
1718
-
1719
- # The runner checks this many of a member's latest rewinds before each execution.
1720
- RECENT_REWINDS = 50
1721
-
1722
-
1723
- def member_rewinds(connection, member_id):
1724
- """Executions taken back from one member by recent rewinds, oldest first; the runner cuts before the earliest it finds."""
1725
- taken = set()
1726
- for row in connection.execute("SELECT cuts FROM room_rewinds WHERE room_id=(SELECT room_id FROM room_members WHERE id=?) ORDER BY id DESC LIMIT ?",
1727
- (member_id, RECENT_REWINDS)):
1728
- taken.update(json.loads(row["cuts"]).get(str(member_id), []))
1729
- return sorted(taken)
1730
-
1731
-
1732
- def add_member(connection, room_id, token, payload, now):
1733
- """Owner adds a member while the room keeps running; other members are not interrupted."""
1734
- require_owner(connection, room_id, token)
1735
- begin_write(connection)
1736
- member = member_value(payload)
1737
- existing = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, member["name"])).fetchone()
1738
- if existing and existing["status"] == "active" and existing["token_hash"] == token_hash(member["token"]) and all(
1739
- existing[key] == member[key] for key in ("adapter", "access", "session_mode")):
1740
- return free_view(connection, room_id)
1741
- if existing:
1742
- raise FileExistsError(f"{member['name']} 已是本房间成员;离开的成员请用请回")
1743
- require_fresh_member_token(connection, room_id, member["token"])
1744
- insert_member(connection, room_id, member, now)
1745
- queue_invited_expert(connection, room_id, member["name"], now)
1746
- sync_participants(connection, room_id)
1747
- return free_view(connection, room_id)
1748
-
1749
-
1750
- def discussion_roster(connection, room_id):
1751
- """Return a discussion's host, active experts and phase; away experts keep only their member row."""
1752
- row = connection.execute("SELECT host,experts,phase FROM topic_settings WHERE room_id=?", (room_id,)).fetchone()
1753
- return row["host"], json.loads(row["experts"]), row["phase"]
1754
-
1755
-
1756
- def save_discussion_experts(connection, room_id, experts):
1757
- """Write the active roster; additions preserve its plan, other changes ask the host to re-plan."""
1758
- connection.execute("UPDATE topic_settings SET experts=? WHERE room_id=?", (json.dumps(experts, ensure_ascii=False), room_id))
1759
-
1760
-
1761
- def queue_invited_expert(connection, room_id, name, now):
1762
- """Queue a new expert at the tail of an existing live plan, without changing the current speaker or hold.
1763
-
1764
- A manual expert is queued only once it has registered (the invite alone does not), and only once per invitation.
1765
- """
1766
- member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status='active'", (room_id, name)).fetchone()
1767
- if not member or (member["adapter"] == "manual" and not registered_at(connection, member)):
1768
- return
1769
- from .session_room import current_session
1770
- session = current_session(connection, room_id)
1771
- if session and session["status"] != "concluded":
1772
- planned = connection.execute("SELECT 1 FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued') LIMIT 1",
1773
- (session["id"],)).fetchone()
1774
- if not planned:
1775
- return
1776
- round_number = connection.execute("SELECT MIN(round) FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued')",
1777
- (session["id"],)).fetchone()[0]
1778
- if round_number is None:
1779
- round_number = 1
1780
- position = connection.execute("SELECT COALESCE(MAX(position),0)+1 FROM session_requests WHERE session_id=? AND purpose='discuss' AND round=?",
1781
- (session["id"], round_number)).fetchone()[0]
1782
- invitation = connection.execute("SELECT COUNT(*) FROM session_requests WHERE session_id=? AND member_id=? AND submission_id LIKE 'invite:%'",
1783
- (session["id"], member["id"])).fetchone()[0] + 1
1784
- state = connection.execute("SELECT phase,read_until FROM session_state WHERE session_id=?", (session["id"],)).fetchone()
1785
- question = ("欢迎加入:请先读取议题,独立给出你的开场观点。" if state and state["phase"] == "initial"
1786
- else "欢迎加入:请先读取议题和已有回答,给出你的观点。")
1787
- read_until = state["read_until"] if state and state["phase"] == "initial" and round_number == 1 else None
1788
- connection.execute("""INSERT OR IGNORE INTO session_requests
1789
- (session_id,round,position,member_id,purpose,question,status,submission_id,read_until,created_at)
1790
- VALUES(?,?,?,?,'discuss',?,'queued',?,?,?)""",
1791
- (session["id"], round_number, position, member["id"], question,
1792
- f"invite:{member['id']}:{invitation}", read_until,
1793
- time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())))
1794
- return
1795
- connection.execute("""INSERT OR IGNORE INTO discussion_turns (room_id,expert,question,status,submission_id,created_at)
1796
- SELECT settings.room_id,member.name,
1797
- CASE WHEN settings.phase='initial' THEN '欢迎加入:请先读取议题,独立给出你的开场观点。'
1798
- ELSE '欢迎加入:请先读取议题和已有回答,给出你的观点。' END,
1799
- 'queued','invite:'||member.id,?
1800
- FROM topic_settings AS settings JOIN room_members AS member ON member.room_id=settings.room_id
1801
- WHERE settings.room_id=? AND member.name=? AND member.status='active'
1802
- AND settings.phase NOT IN ('paused','concluded')
1803
- AND EXISTS (SELECT 1 FROM discussion_turns WHERE room_id=settings.room_id AND status IN ('pending','notified','queued'))""",
1804
- (now, room_id, name))
1805
-
1806
-
1807
- def add_discussion_member(connection, room_id, token, payload, now):
1808
- """Owner invites one expert into a discussion using the room's delivery method."""
1809
- require_owner(connection, room_id, token)
1810
- begin_write(connection)
1811
- member = member_value(payload)
1812
- _, experts, phase = discussion_roster(connection, room_id)
1813
- run = connection.execute("SELECT mode FROM discussion_runtime WHERE room_id=?", (room_id,)).fetchone()
1814
- if not discussion_access_ok(member["access"], "cli", bool(run and run["mode"] == "automatic"), False):
1815
- raise ValueError("新专家的接入方式须与讨论的推进方式一致")
1816
- existing = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, member["name"])).fetchone()
1817
- if existing and existing["status"] == "active" and existing["token_hash"] == token_hash(member["token"]):
1818
- return
1819
- if existing:
1820
- raise FileExistsError(f"{member['name']} 已是本房间成员;离开的成员请用请回")
1821
- if phase == "concluded":
1822
- raise ValueError("讨论已收束,不能再邀请专家")
1823
- if len(experts) >= MAX_ROOM_AGENTS:
1824
- raise ValueError("房间成员已达上限")
1825
- require_fresh_member_token(connection, room_id, member["token"])
1826
- insert_member(connection, room_id, mark_manual(member, bool(run and run["mode"] == "automatic")), now)
1827
- save_discussion_experts(connection, room_id, {**experts, member["name"]: "cli"})
1828
- queue_invited_expert(connection, room_id, member["name"], now)
1829
-
1830
-
1831
- def discussion_member_action(connection, room_id, member_id, token, payload):
1832
- """Owner sends an expert away (keeping its seat), brings it back with a new credential, or removes it.
1833
-
1834
- Leaving cancels the expert's open assignments; the host keeps its role and cannot leave, and an
1835
- leaving cancels its active plan and asks the host to re-plan without pausing the discussion.
1836
- """
1837
- member = owned_member(connection, room_id, member_id, token)
1838
- host, experts, phase = discussion_roster(connection, room_id)
1839
- action = payload.get("action")
1840
- if action in ("away", "remove"):
1841
- if member["name"] == host:
1842
- raise ValueError("主持人不能离开或移除;请先更换主持人")
1843
- from .session_room import session_member_change
1844
- session_member_change(connection, room_id, member, action)
1845
- connection.execute("UPDATE discussion_turns SET status='cancelled' WHERE room_id=? AND expert=? AND status IN ('pending','notified')",
1846
- (room_id, member["name"]))
1847
- connection.execute("UPDATE discussion_turns SET status='skipped' WHERE room_id=? AND expert=? AND status='queued'", (room_id, member["name"]))
1848
- connection.execute("UPDATE room_members SET status=? WHERE id=?", ("away" if action == "away" else "removed", member_id))
1849
- experts.pop(member["name"], None)
1850
- elif action == "active":
1851
- hashed = token_hash(payload.get("token"))
1852
- if member["status"] == "active" and hashed and hmac.compare_digest(hashed, member["token_hash"]):
1853
- return
1854
- if member["status"] != "away" or not hashed or hmac.compare_digest(hashed, member["token_hash"]):
1855
- raise ValueError("只有离开的成员可以请回,且须提供新的成员凭证")
1856
- require_fresh_member_token(connection, room_id, payload.get("token"))
1857
- connection.execute("UPDATE room_members SET status='active',token_hash=? WHERE id=?", (hashed, member_id))
1858
- experts[member["name"]] = "online" if member["access"] == "online" else "cli"
1859
- from .session_room import current_session, session_member_change
1860
- if current_session(connection, room_id, active_only=True):
1861
- session_member_change(connection, room_id, member, action)
1862
- else:
1863
- queue_invited_expert(connection, room_id, member["name"], int(time.time()))
1864
- elif action == "adopt":
1865
- adopt_manual_member(connection, room_id, member, payload)
1866
- return
1867
- else:
1868
- raise ValueError("action 须为 away、active、remove 或 adopt")
1869
- save_discussion_experts(connection, room_id, experts)
1870
-
1871
-
1872
- ADOPTABLE_ADAPTERS = ("claude", "codex", "codex_cli", "antigravity", "antigravity_cli")
1873
-
1874
-
1875
- def adopt_manual_member(connection, room_id, member, payload):
1876
- """Hand a manual expert to the local service once its CLI reported the session it runs in; the owner's service resumes that session."""
1877
- reported = connection.execute("SELECT session_id FROM member_sessions WHERE member_id=?", (member["id"],)).fetchone()
1878
- run = connection.execute("SELECT mode FROM discussion_runtime WHERE room_id=?", (room_id,)).fetchone()
1879
- if not registered_at(connection, member):
1880
- raise ValueError("成员尚未注册,不能转为托管")
1881
- if not reported or reported["session_id"] != payload.get("session_id") or payload.get("adapter") not in ADOPTABLE_ADAPTERS:
1882
- raise ValueError("成员尚未上报与之相符的会话,不能转为托管")
1883
- if member["access"] != "manual" or member["status"] != "active" or not (room_mode(connection, room_id) == "free" or (run and run["mode"] == "automatic")):
1884
- raise ValueError("只有自由协作或全自动讨论中在场的手动专家可以转为托管")
1885
- connection.execute("UPDATE room_members SET access='runner',adapter=?,session_mode='borrowed' WHERE id=?", (payload["adapter"], member["id"]))
1886
- connection.execute("DELETE FROM member_sessions WHERE member_id=?", (member["id"],))
1887
- # A free room's service answers as the member, so it takes over with a credential the owner's side generated.
1888
- if payload.get("token") is not None:
1889
- require_fresh_member_token(connection, room_id, payload["token"])
1890
- connection.execute("UPDATE room_members SET token_hash=? WHERE id=?", (token_hash(payload["token"]), member["id"]))
1891
-
1892
-
1893
- def require_fresh_member_token(connection, room_id, token):
1894
- """Prevent owner or another member's credential from being reused for a new identity."""
1895
- hashed = token_hash(token)
1896
- if not hashed or connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND token_hash=? UNION ALL SELECT 1 FROM room_modes WHERE room_id=? AND control_hash=?",
1897
- (room_id, hashed, room_id, hashed)).fetchone():
1898
- raise ValueError("须提供独立的新成员凭证")
1899
-
1900
-
1901
- def member_action(connection, room_id, member_id, token, payload):
1902
- """Owner sends a member away, brings it back with a new credential, or removes it.
1903
-
1904
- Leaving voids live work at once. Coming back requires a fresh credential, so copies of the
1905
- old one never revive; the software session is kept by the local runner, not here. The
1906
- `role` action makes one runner or manual member the AI host, replacing any previous host.
1907
- """
1908
- member = owned_member(connection, room_id, member_id, token)
1909
- manual_source = connection.execute("SELECT source FROM member_manual_sources WHERE member_id=?", (member_id,)).fetchone()
1910
- is_web_member = bool(manual_source and manual_source["source"] == "web")
1911
- action = payload.get("action")
1912
- routed = []
1913
- if action in ("away", "remove"):
1914
- from .session_room import pause_session_for_host_change, session_member_change
1915
- if member["role"] == "host":
1916
- pause_session_for_host_change(connection, room_id)
1917
- else:
1918
- session_member_change(connection, room_id, member, action)
1919
- # Unnamed messages still waiting on a departing host move to its successor instead of being dropped.
1920
- routed = open_route_messages(connection, member_id)
1921
- stop_member_work(connection, member_id, "成员已离开" if action == "away" else "成员已移除",
1922
- "member_away" if action == "away" else "member_removed")
1923
- connection.execute("UPDATE room_members SET status=? WHERE id=?", ("away" if action == "away" else "removed", member_id))
1924
- elif action == "active":
1925
- hashed = token_hash(payload.get("token"))
1926
- if member["status"] == "active" and hashed and hmac.compare_digest(hashed, member["token_hash"]):
1927
- return free_view(connection, room_id)
1928
- if member["status"] != "away" or not hashed or hmac.compare_digest(hashed, member["token_hash"]):
1929
- raise ValueError("只有离开的成员可以请回,且须提供新的成员凭证")
1930
- require_fresh_member_token(connection, room_id, payload.get("token"))
1931
- connection.execute("UPDATE room_members SET status='active',token_hash=? WHERE id=?", (hashed, member_id))
1932
- from .session_room import current_session, session_member_change
1933
- if current_session(connection, room_id, active_only=True):
1934
- session_member_change(connection, room_id, member, action)
1935
- else:
1936
- queue_invited_expert(connection, room_id, member["name"], int(time.time()))
1937
- elif action == "adopt":
1938
- adopt_manual_member(connection, room_id, member, payload)
1939
- elif action == "role":
1940
- role = payload.get("role")
1941
- if role not in ("host", "member") or (role == "host" and (member["access"] == "online" or is_web_member)):
1942
- raise ValueError("role 须为 host 或 member;在线成员不能担任主持人")
1943
- if role == "member" and member["role"] == "host":
1944
- raise ValueError("自由房间须由一位 AI 主持;请指定另一位成员担任主持人")
1945
- if role == "host":
1946
- from .session_room import pause_session_for_host_change
1947
- pause_session_for_host_change(connection, room_id)
1948
- # Unnamed messages the old host has not started move to the new host, which carries the host rules.
1949
- old_host = connection.execute("SELECT id FROM room_members WHERE room_id=? AND role='host' AND id<>?", (room_id, member_id)).fetchone()
1950
- if old_host:
1951
- routed = open_route_messages(connection, old_host["id"], pending_only=True)
1952
- record_cancel_reasons(connection, "member_id=? AND purpose IN ('route','group') AND status='pending'", (old_host["id"],), "rerouted")
1953
- connection.execute("UPDATE member_requests SET status='cancelled' WHERE member_id=? AND purpose IN ('route','group') AND status='pending'", (old_host["id"],))
1954
- connection.execute("UPDATE room_members SET role='member' WHERE room_id=? AND role='host'", (room_id,))
1955
- connection.execute("UPDATE room_members SET role=? WHERE id=?", (role, member_id))
1956
- else:
1957
- raise ValueError("action 须为 away、active、remove、role 或 adopt")
1958
- settle_batches(connection, room_id)
1959
- sync_participants(connection, room_id)
1960
- hand_over_routes(connection, room_id, routed, member_id if action in ("away", "remove") else None)
1961
- return free_view(connection, room_id)
1
+ """Free collaboration rooms: member credentials, durable requests and per-member executions.
2
+
3
+ A free room has no floor, turns or rounds. The user (holding the room control credential)
4
+ names members; each named member gets one durable request per message. The local runner
5
+ delivers a runner member's open requests as one execution, and the member's answer completes
6
+ them. A manual member finds its own requests and answers by request id; an online member's
7
+ answer is forwarded by the owner. The user is the client, never the host: one member that
8
+ answers by itself always hosts, routes unnamed messages, names members in its answers, and is
9
+ woken once when everything it dispatched has finished. No software is launched here.
10
+ """
11
+
12
+ import hashlib
13
+ import hmac
14
+ import json
15
+ import re
16
+ import time
17
+ import uuid
18
+
19
+ from .identity import MAX_ROOM_AGENTS, is_ai
20
+ from .runtime import (LEASE_SECONDS, MAX_EXECUTION_SEGMENTS, begin_write, enforce_session_limits,
21
+ require_owner, save_segments, token_hash)
22
+
23
+ REVIEW_ADAPTERS = ("codex_cli",)
24
+ MAX_REVIEW_SCOPE = 2000
25
+ MAX_REVIEW_INPUT = 60000
26
+ REVIEW_STATE_SQL = """SELECT json_object(
27
+ 'room',json_array(id,title,goal,(SELECT archived FROM room_directory WHERE room_id=rooms.id)),
28
+ 'latest',(SELECT COALESCE(MAX(id),0) FROM messages WHERE room_id=rooms.id),
29
+ 'members',(SELECT json_group_array(json_array(id,name,role,status,access,session_mode,adapter,token_hash)) FROM (SELECT * FROM room_members WHERE room_id=rooms.id ORDER BY id)),
30
+ 'caps',(SELECT json_group_array(json_array(c.member_id,c.member_revision,c.config_version,c.generation)) FROM member_review_capabilities c JOIN room_members m ON m.id=c.member_id WHERE m.room_id=rooms.id),
31
+ 'requests',(SELECT json_group_array(json_array(id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose)) FROM (SELECT * FROM member_requests WHERE room_id=rooms.id ORDER BY id)),
32
+ 'executions',(SELECT json_group_array(json_array(id,status,result,changes)) FROM (SELECT * FROM member_executions WHERE room_id=rooms.id ORDER BY id)),
33
+ 'batches',(SELECT json_group_array(json_array(batch_id,settled,host_id,chain_id)) FROM free_batches WHERE room_id=rooms.id),
34
+ 'plans',(SELECT json_group_array(json_array(batch_id,status,reviewer_id,config_version,member_revision,scope,review_batch_id)) FROM review_plans WHERE room_id=rooms.id),
35
+ 'limit',COALESCE((SELECT max_rounds FROM free_round_limits WHERE room_id=rooms.id),3),
36
+ 'holds',(SELECT json_group_array(json_array(chain_id,extra_rounds,message_id)) FROM free_chain_holds WHERE room_id=rooms.id),
37
+ 'stopped',(SELECT json_group_array(json_array(chain_id,reason)) FROM free_chains WHERE room_id=rooms.id),
38
+ 'withdrawn',(SELECT json_group_array(message_id) FROM message_withdrawals WHERE message_id IN (SELECT id FROM messages WHERE room_id=rooms.id))
39
+ ) AS state FROM rooms WHERE id=?"""
40
+ RECENT_REQUESTS = 100
41
+ RECENT_EXECUTIONS = 100
42
+ # The timeline page reads this many recent executions of each kind; with `after` (?3) only those running or ended since.
43
+ # Parameters: ?1 room, ?2 limit, ?3 after (0 reads all). Shared verbatim with the Worker.
44
+ TIMELINE_EXECUTIONS = 100
45
+ # Rounds used and allowed in the room's recent chains, for "第 2/3 轮"; parameters: the room's limit, the room.
46
+ CHAIN_PROGRESS_SQL = """SELECT b.chain_id,COUNT(*) AS used,? + COALESCE((SELECT h.extra_rounds FROM free_chain_holds h
47
+ WHERE h.room_id=b.room_id AND h.chain_id=b.chain_id),0) AS allowed FROM free_batches b WHERE b.room_id=?
48
+ GROUP BY b.chain_id ORDER BY b.chain_id DESC LIMIT 10"""
49
+ TIMELINE_STATES = {"completed": "done", "failed": "failed", "cancelled": "cancelled"}
50
+ TIMELINE_FREE_IDS = "SELECT id FROM member_executions WHERE room_id=?1 AND (?3=0 OR finished_at=0 OR finished_at>=?3) ORDER BY id DESC LIMIT ?2"
51
+ TIMELINE_DISCUSSION_IDS = """SELECT e.id FROM discussion_events e LEFT JOIN event_timings t ON t.event_id=e.id
52
+ WHERE e.room_id=?1 AND (t.dispatched_at>0 OR e.status='pending') AND (?3=0 OR COALESCE(t.finished_at,0)=0 OR t.finished_at>=?3)
53
+ ORDER BY e.id DESC LIMIT ?2"""
54
+ # Besides times: the task an execution took on (its request message, or the discussion turn's question), its result
55
+ # (the answer's summary, else the answer's opening), its latest progress note, how many files it changed (NULL when
56
+ # unobserved), its last output time (free executions only) and the discussion run it belongs to (discussion only).
57
+ TIMELINE_SQL = f"""SELECT x.*,(SELECT COALESCE(NULLIF(s.text,''),substr(a.text,1,200)) FROM messages a
58
+ LEFT JOIN message_summaries s ON s.message_id=a.id WHERE a.id=x.answer_id) AS result FROM (
59
+ SELECT 'free' AS source,e.id,m.name AS member,m.role,e.status,
60
+ COALESCE((SELECT MIN(r.created_at) FROM member_requests r WHERE r.execution_id=e.id),e.created_at) AS queued_at,
61
+ e.created_at AS dispatched_at,0 AS started_at,e.finished_at,
62
+ CASE WHEN e.status='failed' THEN e.result ELSE '' END AS reason,
63
+ (SELECT parent.execution_id FROM member_requests r JOIN member_requests parent ON parent.answer_id=r.message_id
64
+ WHERE r.execution_id=e.id AND parent.execution_id IS NOT NULL ORDER BY r.id LIMIT 1) AS parent_id,
65
+ e.activity_at,(SELECT MIN(r.message_id) FROM member_requests r WHERE r.execution_id=e.id) AS task_id,
66
+ (SELECT substr(q.text,1,160) FROM messages q WHERE q.id=(SELECT MIN(r.message_id) FROM member_requests r WHERE r.execution_id=e.id)) AS task,
67
+ (SELECT MAX(r.answer_id) FROM member_requests r WHERE r.execution_id=e.id) AS answer_id,
68
+ (SELECT n.text FROM execution_notes n WHERE n.execution_id=e.id ORDER BY n.seq DESC LIMIT 1) AS last_note,
69
+ CASE WHEN e.changes='' THEN NULL ELSE json_array_length(e.changes) END AS changes,NULL AS run_id
70
+ FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.id IN ({TIMELINE_FREE_IDS})
71
+ UNION ALL SELECT 'discussion',e.id,e.participant,e.role,e.status,CAST(strftime('%s',e.created_at) AS INTEGER),
72
+ COALESCE(t.dispatched_at,0),e.started_at,COALESCE(t.finished_at,0),CASE WHEN e.status='failed' THEN e.result ELSE '' END,NULL,
73
+ 0,NULL,(SELECT substr(q.question,1,160) FROM discussion_turns q WHERE q.id=e.turn_id),
74
+ CASE WHEN e.result LIKE 'message:%' THEN CAST(substr(e.result,9) AS INTEGER) END,NULL,NULL,e.run_id
75
+ FROM discussion_events e LEFT JOIN event_timings t ON t.event_id=e.id WHERE e.id IN ({TIMELINE_DISCUSSION_IDS})) x"""
76
+ TIMELINE_SEGMENTS_SQL = f"""SELECT source,execution_id,phase,tool,start_ms,end_ms FROM execution_segments WHERE room_id=?1 AND (
77
+ (source='free' AND execution_id IN ({TIMELINE_FREE_IDS})) OR (source='discussion' AND execution_id IN ({TIMELINE_DISCUSSION_IDS})))
78
+ ORDER BY source,execution_id,seq"""
79
+ # Only the times of progress notes: the texts are read when the reader hovers one.
80
+ TIMELINE_NOTES_SQL = f"""SELECT execution_id,created_at FROM execution_notes
81
+ WHERE room_id=?1 AND execution_id IN ({TIMELINE_FREE_IDS}) ORDER BY execution_id,seq"""
82
+ RECENT_CHANGES = 50
83
+ MAX_CHANGED_FILES = 200
84
+ # What a member's software last showed it doing, as reported by the runner with each renewal.
85
+ ACTIVITY_PHASES = ("", "thinking", "command", "tool", "editing", "writing")
86
+ # Progress notes per execution, their length, and how many one renewal may carry.
87
+ MAX_EXECUTION_NOTES = 50
88
+ MAX_NOTE_LENGTH = 500
89
+ MAX_NOTES_PER_RENEW = 10
90
+ # A member description is a short note for the scheduler and the host, keyed by the member's name.
91
+ MAX_MEMBER_DESCRIPTION = 500
92
+ # A display label replaces the member's name on screen only; the name stays the member's identity everywhere else.
93
+ MAX_MEMBER_LABEL = 32
94
+ MAX_MEMBER_NAME = 80
95
+ MAX_PATH_LENGTH = 500
96
+ # Refused operations one execution may report, and the length of each field.
97
+ MAX_DENIALS = 20
98
+ MAX_DENIAL_FIELD = 300
99
+ # A manual member's delivery is retried at most this often before the execution fails.
100
+ MAX_RETRIES = 3
101
+ MAX_RETRY_REASON = 500
102
+ ACTIVE = ("dispatched", "started")
103
+ ACCESS_MODES = ("runner", "manual")
104
+ LEGACY_ACCESS_MODES = ("runner", "manual", "online")
105
+ SCHEDULER_PROVIDERS = ("jev", "decisions")
106
+ RECOMMEND_SECONDS = 60
107
+ # A click sent just before the hint disappears still counts.
108
+ RECOMMEND_GRACE_SECONDS = 5
109
+ # Rounds a host may run from one owner message by default (a round: one host dispatch, its members' answers and the
110
+ # hand-back); each owner message starts a chain. Counted in rounds, so a room with more members gets no fewer of them.
111
+ CHAIN_ROUNDS = 3
112
+ # The most rounds an owner may allow per chain, or add at once when continuing a stopped chain.
113
+ MAX_CHAIN_ROUNDS = 20
114
+ # A host that left gives up the role; the first active runner member (else manual) then takes it.
115
+ RELEASE_HOST = "UPDATE room_members SET role='member' WHERE room_id=? AND role='host' AND status<>'active'"
116
+ ASSIGN_HOST = """UPDATE room_members SET role='host' WHERE id=(SELECT id FROM room_members WHERE room_id=? AND status='active'
117
+ AND NOT EXISTS(SELECT 1 FROM member_manual_sources source WHERE source.member_id=room_members.id AND source.source='web')
118
+ ORDER BY access='runner' DESC, id LIMIT 1)
119
+ AND NOT EXISTS (SELECT 1 FROM room_members WHERE room_id=? AND role='host' AND status='active')"""
120
+ TERMINAL = ("completed", "cancelled", "failed")
121
+ # A queued member has been asked once its request for that message exists.
122
+ QUEUE_ASKED = "EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id={row}.message_id AND r.member_id={row}.member_id)"
123
+ SESSION_MODES = ("new", "borrowed")
124
+ FREE_OPERATIONS = ("messages", "attachments", "move", "folder", "rename", "archive", "restore", "delete")
125
+ MEMBER_FIELDS = ("id", "name", "adapter", "role", "status", "access", "session_mode", "read_until")
126
+ EXECUTION_FIELDS = ("id", "member_id", "status", "session_id", "lease_until", "created_at", "finished_at", "result",
127
+ "activity", "activity_at")
128
+ # Columns added after the first free-room tables; Python databases created by that build gain them here.
129
+ LATER_COLUMNS = {"room_members": {"access": "TEXT NOT NULL DEFAULT 'runner'", "session_mode": "TEXT NOT NULL DEFAULT 'new'"},
130
+ "member_executions": {"changes": "TEXT NOT NULL DEFAULT ''", "cwd": "TEXT NOT NULL DEFAULT ''",
131
+ "activity": "TEXT NOT NULL DEFAULT ''", "activity_at": "INTEGER NOT NULL DEFAULT 0"},
132
+ "member_requests": {"chain_id": "INTEGER NOT NULL DEFAULT 0", "batch_id": "INTEGER NOT NULL DEFAULT 0",
133
+ "purpose": "TEXT NOT NULL DEFAULT 'ask'", "created_by": "TEXT NOT NULL DEFAULT 'user'"}}
134
+
135
+
136
+ def migrate_free_tables(connection):
137
+ """Add columns that early free-room databases lack; repeated runs change nothing."""
138
+ for table, columns in LATER_COLUMNS.items():
139
+ present = {row[1] for row in connection.execute(f"PRAGMA table_info({table})")}
140
+ for name, definition in columns.items():
141
+ if name not in present:
142
+ connection.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")
143
+ connection.execute("""CREATE TABLE IF NOT EXISTS member_manual_sources (
144
+ member_id INTEGER PRIMARY KEY REFERENCES room_members(id) ON DELETE CASCADE,
145
+ source TEXT NOT NULL CHECK(source='web'))""")
146
+ connection.execute("""INSERT OR IGNORE INTO member_manual_sources(member_id,source)
147
+ SELECT id,'web' FROM room_members WHERE access='online'""")
148
+ connection.execute("UPDATE room_members SET access='manual' WHERE access='online'")
149
+ connection.execute("UPDATE room_modes SET mode='free' WHERE mode='brainstorm'")
150
+
151
+
152
+ def room_mode(connection, room_id):
153
+ """Return 'free' for free rooms; every legacy room is a brainstorm room."""
154
+ row = connection.execute("SELECT mode FROM room_modes WHERE room_id=?", (room_id,)).fetchone()
155
+ return row[0] if row else "brainstorm"
156
+
157
+
158
+ def review_member_revision(member, generation=0):
159
+ """Bind an attestation to the exact member identity and access configuration without exposing credentials."""
160
+ state = ":".join(str(member[key]) for key in ("id", "status", "adapter", "access", "session_mode", "token_hash")) + f":{generation}"
161
+ return hashlib.sha256(state.encode("utf-8")).hexdigest()
162
+
163
+
164
+ def review_capability(connection, room_id, member_id, token, payload=None):
165
+ """Read or replace one owner's local read-only attestation, guarded by the member revision."""
166
+ require_owner(connection, room_id, token)
167
+ if payload is not None:
168
+ begin_write(connection)
169
+ member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND id=?", (room_id, member_id)).fetchone()
170
+ if not member:
171
+ raise LookupError("成员不存在")
172
+ previous = connection.execute("SELECT generation FROM member_review_capabilities WHERE member_id=?", (member_id,)).fetchone()
173
+ revision = review_member_revision(member, previous[0] if previous else 0)
174
+ if payload is not None:
175
+ if not payload.get("revision"):
176
+ raise ValueError("请先读取成员 review-capability,再带 revision 提交能力事实")
177
+ if payload["revision"] != revision:
178
+ raise FileExistsError("成员状态已变化,请重新读取能力状态")
179
+ if type(payload.get("read_only")) is not bool:
180
+ raise ValueError("read_only 须为布尔值")
181
+ if payload["read_only"]:
182
+ version = payload.get("config_version", "")
183
+ if not isinstance(version, str) or not re.fullmatch(r"[a-f0-9]{64}", version):
184
+ raise ValueError("config_version 须为本机配置的 SHA-256 摘要")
185
+ if member["status"] != "active" or member["access"] != "runner" or member["session_mode"] != "new" or member["adapter"] not in REVIEW_ADAPTERS:
186
+ raise FileExistsError("仅支持程序启动、可核验只读权限的本地 CLI 成员")
187
+ connection.execute("""INSERT INTO member_review_capabilities(member_id,member_revision,config_version,adapter,recorded_at) VALUES (?,?,?,?,?)
188
+ ON CONFLICT(member_id) DO UPDATE SET member_revision=excluded.member_revision,
189
+ config_version=excluded.config_version,adapter=excluded.adapter,recorded_at=excluded.recorded_at""",
190
+ (member_id, revision, version, member["adapter"], int(time.time())))
191
+ else:
192
+ connection.execute("UPDATE member_review_capabilities SET config_version='',member_revision='' WHERE member_id=?", (member_id,))
193
+ capability = connection.execute("SELECT config_version,adapter FROM member_review_capabilities WHERE member_id=? AND member_revision=?",
194
+ (member_id, revision)).fetchone()
195
+ return {"member_id": member_id, "member": member["name"], "revision": revision,
196
+ "capability": dict(capability) if capability else None}
197
+
198
+
199
+ def review_roster(connection, room_id, token):
200
+ """Return eligible local reviewers to the owner or current host; never publish member credentials."""
201
+ try:
202
+ require_owner(connection, room_id, token)
203
+ except PermissionError:
204
+ member = require_member(connection, room_id, token)
205
+ if member["role"] != "host":
206
+ raise PermissionError("只有房主或当前主持人可读取评审候选")
207
+ rows = connection.execute("""SELECT m.*,c.config_version,c.member_revision,c.generation FROM room_members m
208
+ JOIN member_review_capabilities c ON c.member_id=m.id WHERE m.room_id=? AND m.status='active'
209
+ AND m.access='runner' AND m.session_mode='new' ORDER BY m.id""", (room_id,)).fetchall()
210
+ members = [{"id": row["id"], "name": row["name"], "adapter": row["adapter"], "config_version": row["config_version"]}
211
+ for row in rows if row["adapter"] in REVIEW_ADAPTERS and row["member_revision"] == review_member_revision(row, row["generation"])]
212
+ state = connection.execute(REVIEW_STATE_SQL, (room_id,)).fetchone()["state"]
213
+ return {"members": members, "revision": hashlib.sha256(state.encode("utf-8")).hexdigest(),
214
+ "reason": "" if members else "没有可核验只读的评审成员"}
215
+
216
+
217
+ def checked_review_plan(connection, room_id, actor, payload):
218
+ """Validate one preauthorized review before the host message and implementation dispatch commit."""
219
+ if not payload.get("next_review"):
220
+ if payload.get("review_scope") or payload.get("review_roster"):
221
+ raise ValueError("review_scope / review_roster 须与 next_review 一起提交")
222
+ return None
223
+ if not isinstance(actor, dict) or actor["role"] != "host" or not payload.get("to") or payload.get("kind") == "moderation":
224
+ raise PermissionError("只有主持人派实现任务时可以声明下一步评审")
225
+ if not isinstance(payload["next_review"], str):
226
+ raise ValueError("next_review 须为成员名称")
227
+ if not payload.get("review_roster"):
228
+ raise ValueError("请先读取 review roster,再带 review_roster 声明评审")
229
+ state = connection.execute(REVIEW_STATE_SQL, (room_id,)).fetchone()["state"]
230
+ if payload["review_roster"] != hashlib.sha256(state.encode("utf-8")).hexdigest():
231
+ raise FileExistsError("评审候选或任务状态已变化,请重新读取 review roster")
232
+ scope = payload.get("review_scope", "")
233
+ if not isinstance(scope, str) or not 1 <= len(scope.strip()) <= MAX_REVIEW_SCOPE:
234
+ raise ValueError(f"评审范围须为 1–{MAX_REVIEW_SCOPE} 字")
235
+ if payload["next_review"] in payload["to"]:
236
+ raise ValueError("评审者不能是该批次的实现者")
237
+ reviewer = connection.execute("""SELECT m.*,c.config_version,c.member_revision,c.generation FROM room_members m
238
+ JOIN member_review_capabilities c ON c.member_id=m.id WHERE m.room_id=? AND m.name=?""", (room_id, payload["next_review"])).fetchone()
239
+ if not reviewer or reviewer["status"] != "active" or reviewer["member_revision"] != review_member_revision(reviewer, reviewer["generation"]) or not reviewer["config_version"]:
240
+ raise FileExistsError("没有可核验只读的评审成员:指定成员未上报有效能力或已失效")
241
+ chain_id = answered_chain(connection, payload, actor)
242
+ if not chain_id or rounds_left(connection, room_id, chain_id) < 1:
243
+ raise FileExistsError("任务链剩余额度不足,不能保存实现批次及评审授权")
244
+ return {"chain_id": chain_id, "host_id": actor["id"], "reviewer_id": reviewer["id"], "reviewer_name": reviewer["name"],
245
+ "config_version": reviewer["config_version"], "member_revision": reviewer["member_revision"], "scope": scope.strip(),
246
+ "implementers": json.dumps(sorted(set(payload["to"])), ensure_ascii=False)}
247
+
248
+
249
+ def save_review_plan(connection, room_id, batch_id, plan):
250
+ """Persist the next step only inside the implementation message transaction."""
251
+ if plan:
252
+ fields = ("chain_id", "host_id", "reviewer_id", "reviewer_name", "config_version", "member_revision", "scope", "implementers")
253
+ connection.execute(f"INSERT INTO review_plans(room_id,batch_id,{','.join(fields)}) VALUES ({','.join('?' for _ in range(10))})",
254
+ (room_id, batch_id, *(plan[key] for key in fields)))
255
+
256
+
257
+ def check_review_retry(connection, room_id, message_id, payload):
258
+ """A repeated host message cannot silently change or remove its preauthorized review."""
259
+ plan = connection.execute("SELECT * FROM review_plans WHERE room_id=? AND batch_id=?", (room_id, message_id)).fetchone()
260
+ if not plan and not payload.get("next_review"):
261
+ return
262
+ if not plan or (plan["reviewer_name"], plan["scope"], json.loads(plan["implementers"])) != (
263
+ payload.get("next_review"), str(payload.get("review_scope", "")).strip(), sorted(set(payload.get("to", [])))):
264
+ raise FileExistsError("这个提交编号已绑定不同的评审授权,请为新内容使用新编号")
265
+
266
+
267
+ def review_ready(connection, room_id, batch_id, token):
268
+ """Read original delivery evidence and the exact reasons a preauthorized step cannot advance."""
269
+ roster = review_roster(connection, room_id, token)
270
+ plan = connection.execute("SELECT * FROM review_plans WHERE room_id=? AND batch_id=?", (room_id, batch_id)).fetchone()
271
+ if not plan:
272
+ raise LookupError("该批次没有预授权评审")
273
+ plan = dict(plan)
274
+ batch = connection.execute("SELECT * FROM free_batches WHERE room_id=? AND batch_id=?", (room_id, batch_id)).fetchone()
275
+ requests = [dict(row) for row in connection.execute("""SELECT r.id,r.member_id,m.name AS member,r.status,r.answer_id,
276
+ a.text AS answer,e.id AS execution_id,e.status AS execution_status,e.result,e.changes
277
+ FROM member_requests r JOIN room_members m ON m.id=r.member_id LEFT JOIN messages a ON a.id=r.answer_id
278
+ LEFT JOIN member_executions e ON e.id=r.execution_id WHERE r.room_id=? AND r.batch_id=? ORDER BY r.id""", (room_id, batch_id))]
279
+ handoff = connection.execute("SELECT * FROM member_requests WHERE room_id=? AND message_id=? AND member_id=? AND purpose='handoff'",
280
+ (room_id, batch_id, plan["host_id"])).fetchone()
281
+ host = connection.execute("SELECT id FROM room_members WHERE room_id=? AND role='host' AND status='active'", (room_id,)).fetchone()
282
+ candidate = next((member for member in roster["members"] if member["id"] == plan["reviewer_id"]), None)
283
+ capability = connection.execute("SELECT member_revision FROM member_review_capabilities WHERE member_id=?", (plan["reviewer_id"],)).fetchone()
284
+ remaining = rounds_left(connection, room_id, plan["chain_id"])
285
+ reason = review_block_reason(plan, requests, {
286
+ "batch": bool(batch and batch["settled"]), "handoff": bool(handoff and handoff["status"] in ("pending", "delivering")),
287
+ "host": bool(host and host[0] == plan["host_id"]), "remaining": remaining,
288
+ "capability": bool(candidate and candidate["config_version"] == plan["config_version"] and capability[0] == plan["member_revision"]),
289
+ "archived": connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0]})
290
+ original = connection.execute("SELECT id,author,text FROM messages WHERE room_id=? AND id=?", (room_id, batch_id)).fetchone()
291
+ if not original:
292
+ reason = reason or "缺少原委派,不能自动交评审"
293
+ elif len(json.dumps([dict(original), requests], ensure_ascii=False, separators=(",", ":"))) > MAX_REVIEW_INPUT:
294
+ reason = reason or "交付原文与执行报告超过 60000 字符,请主持人处理"
295
+ return {"plan": plan, "original": dict(original) if original else None, "deliveries": requests, "handoff": dict(handoff) if handoff else None,
296
+ "remaining_rounds": remaining, "revision": roster["revision"], "ready": not reason, "reason": reason}
297
+
298
+
299
+ def review_block_reason(plan, requests, facts):
300
+ """Choose a concrete host-facing explanation without interpreting delivery prose."""
301
+ if plan["status"] != "pending":
302
+ return "评审授权已经消费或仅为导入历史"
303
+ if facts["archived"] or not facts["host"]:
304
+ return "房间已存档或主持人已改变,原评审授权不再有效"
305
+ if not facts["batch"] or not requests or any(item["status"] != "completed" or not item["answer_id"] or item["answer"] is None for item in requests):
306
+ return "实现批次尚未全部成功交付,或缺少交付原文"
307
+ if any(item["member_id"] == plan["reviewer_id"] for item in requests):
308
+ return "评审者不能是该批次的实现者"
309
+ if not facts["handoff"]:
310
+ return "该批次交回主持人的请求已处理或取消"
311
+ if not facts["capability"]:
312
+ return "没有可核验只读的评审成员:既定评审者离开或能力配置已变化"
313
+ if facts["remaining"] < 1:
314
+ return "任务链剩余额度不足,需用户续额或主持人另行处理"
315
+ return ""
316
+
317
+
318
+ def advance_review(connection, room_id, token, payload):
319
+ """Consume one exact review authorization and close only its handoff in one transaction."""
320
+ begin_write(connection)
321
+ host = require_member(connection, room_id, token, payload.get("actor"))
322
+ if host["role"] != "host":
323
+ raise PermissionError("只有当前主持人可以推进预授权评审")
324
+ batch_id, submission = payload.get("batch_id"), payload.get("submission_id", "")
325
+ if type(batch_id) is not int or not isinstance(submission, str) or not re.fullmatch(r"[A-Za-z0-9_-]{8,100}", submission):
326
+ raise ValueError("须提供 batch_id 和有效 submission_id")
327
+ saved = connection.execute("SELECT batch_id,review_batch_id FROM review_plans WHERE room_id=? AND advance_submission=?", (room_id, submission)).fetchone()
328
+ if saved:
329
+ if saved["batch_id"] != batch_id:
330
+ raise FileExistsError("提交编号已用于其他评审批次")
331
+ execution = connection.execute("""SELECT e.status FROM member_requests r JOIN member_executions e ON e.id=r.execution_id
332
+ JOIN review_plans p ON p.room_id=r.room_id AND p.batch_id=r.message_id AND p.host_id=r.member_id
333
+ WHERE r.room_id=? AND p.batch_id=? AND r.purpose='handoff'""", (room_id, batch_id)).fetchone()
334
+ return {"batch_id": batch_id, "review_batch_id": saved["review_batch_id"], "duplicate": True,
335
+ "execution_completed": bool(execution and execution[0] == "completed")}
336
+ if not payload.get("revision"):
337
+ raise ValueError("请先读取 review ready,再携带 revision 推进")
338
+ state = review_ready(connection, room_id, batch_id, token)
339
+ if payload["revision"] != state["revision"]:
340
+ raise FileExistsError("评审状态已变化,请重新读取 review ready")
341
+ if not state["ready"]:
342
+ raise FileExistsError(state["reason"])
343
+ plan, handoff = state["plan"], state["handoff"]
344
+ if plan["host_id"] != host["id"]:
345
+ raise PermissionError("本主持人没有该批次的评审授权")
346
+ answer_ids = sorted({item["answer_id"] for item in state["deliveries"]})
347
+ question = f"请只读评审实现批次 #{batch_id}。范围:{plan['scope']}。先读原委派 #{batch_id},再读交付原文 " + "、".join(f"#{number}" for number in answer_ids) + "。不得修改项目;评审结束交回主持人。"
348
+ cursor = connection.execute("INSERT INTO messages(room_id,author,text,source,submission_id,created_at) VALUES(?, '系统任务',?,'system',?,?)",
349
+ (room_id, question, f"review-task-{batch_id}", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())))
350
+ review_batch_id = cursor.lastrowid
351
+ connection.execute("UPDATE review_plans SET status='advanced',review_batch_id=?,advance_submission=? WHERE room_id=? AND batch_id=?",
352
+ (review_batch_id, submission, room_id, batch_id))
353
+ connection.execute("INSERT INTO free_batches(room_id,batch_id,chain_id,host_id) VALUES(?,?,?,?)", (room_id, review_batch_id, plan["chain_id"], host["id"]))
354
+ connection.execute("INSERT INTO free_handoffs(room_id,batch_id) VALUES(?,?)", (room_id, review_batch_id))
355
+ insert_request(connection, room_id, plan["reviewer_id"], review_batch_id, plan["chain_id"], "ask", "host", batch_id=review_batch_id)
356
+ connection.execute("UPDATE member_requests SET status='completed' WHERE id=?", (handoff["id"],))
357
+ completed = finish_review_handoff(connection, handoff)
358
+ return {"batch_id": batch_id, "review_batch_id": review_batch_id, "execution_completed": completed, "duplicate": False}
359
+
360
+
361
+ def finish_review_handoff(connection, handoff):
362
+ """Finish the host execution only when its other requests have all been handled."""
363
+ execution_id = handoff["execution_id"]
364
+ if not execution_id or connection.execute("SELECT 1 FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,)).fetchone():
365
+ return False
366
+ connection.execute("UPDATE member_executions SET status='completed',finished_at=?,result='review_advanced' WHERE id=?",
367
+ (int(time.time()), execution_id))
368
+ return True
369
+
370
+
371
+ def member_value(member):
372
+ """Validate one member and its client-generated credential."""
373
+ if not isinstance(member, dict) or not is_ai(member.get("name")):
374
+ raise ValueError("成员须为有效 AI 身份")
375
+ if not token_hash(member.get("token")):
376
+ raise ValueError("每位成员须提供 32–256 字符的成员凭证")
377
+ adapter = member.get("adapter", "")
378
+ if not isinstance(adapter, str) or len(adapter) > 40:
379
+ raise ValueError("成员适配器名称无效")
380
+ access, session_mode = member.get("access", "runner"), member.get("session_mode", "new")
381
+ if access not in LEGACY_ACCESS_MODES or session_mode not in SESSION_MODES:
382
+ raise ValueError("成员接入方式须为 runner/manual/online,会话方式须为 new/borrowed")
383
+ manual_source = member.get("manual_source", "")
384
+ if access == "online":
385
+ manual_source, access = "web", "manual"
386
+ if manual_source not in ("", "web") or (manual_source == "web" and access != "manual"):
387
+ raise ValueError("manual_source 只能为 manual 成员配置 web")
388
+ return {"name": member["name"], "adapter": adapter, "token": member["token"],
389
+ "access": access, "session_mode": session_mode, "manual_source": manual_source}
390
+
391
+
392
+ def review_request_context(connection, request):
393
+ """Expose only the request's review provenance and local capability binding."""
394
+ plan = connection.execute("SELECT * FROM review_plans WHERE batch_id=? OR review_batch_id=?",
395
+ (request["message_id"], request["message_id"])).fetchone()
396
+ if not plan:
397
+ return {}
398
+ phase = "handoff" if request["message_id"] == plan["batch_id"] else "review" if request["purpose"] == "ask" else "result"
399
+ if phase == "handoff" and request["purpose"] != "handoff":
400
+ return {}
401
+ review = {key: plan[key] for key in ("batch_id", "reviewer_id", "reviewer_name", "config_version", "member_revision", "scope")}
402
+ review["phase"] = phase
403
+ result = {"review": review}
404
+ if phase != "handoff":
405
+ result.update(source_question=connection.execute("SELECT text FROM messages WHERE id=?", (request["message_id"],)).fetchone()[0],
406
+ source_message_id=plan["batch_id"], after_message_id=plan["batch_id"], cause_kind="review")
407
+ if phase == "result":
408
+ failed = connection.execute("""SELECT e.result FROM member_requests r JOIN member_executions e ON e.id=r.execution_id
409
+ WHERE r.batch_id=? AND r.status IN ('cancelled','failed') ORDER BY r.id""", (plan["review_batch_id"],)).fetchall()
410
+ review["reason"] = ";".join(row[0] for row in failed)
411
+ return result
412
+
413
+
414
+ def member_values(members):
415
+ """Validate independent member credentials for a room."""
416
+ if not isinstance(members, list) or not len(members) <= MAX_ROOM_AGENTS:
417
+ raise ValueError("房间成员须为列表,且不超过成员上限")
418
+ result = [member_value(member) for member in members]
419
+ if len({member["name"] for member in result}) != len(result):
420
+ raise ValueError("成员名称不能重复")
421
+ if len({member["token"] for member in result}) != len(result):
422
+ raise ValueError("每位成员须使用独立凭证")
423
+ return result
424
+
425
+
426
+ def insert_member(connection, room_id, member, now):
427
+ """Store one member with only its credential hash."""
428
+ connection.execute("""INSERT INTO room_members (room_id,name,adapter,token_hash,access,session_mode,created_at)
429
+ VALUES (?,?,?,?,?,?,?)""", (room_id, member["name"], member["adapter"], token_hash(member["token"]),
430
+ member["access"], member["session_mode"], now))
431
+ if member.get("manual_source") == "web" or member.get("access") == "online":
432
+ member_id = connection.execute("SELECT id FROM room_members WHERE room_id=? AND name=? AND token_hash=?",
433
+ (room_id, member["name"], token_hash(member["token"]))).fetchone()[0]
434
+ connection.execute("INSERT OR IGNORE INTO member_manual_sources(member_id,source) VALUES(?,'web')", (member_id,))
435
+
436
+
437
+ def save_room_access(connection, room_id, control_token, members, settings):
438
+ """Persist the mode, the owner's control hash and the members in the creating transaction."""
439
+ control = token_hash(control_token)
440
+ if not control:
441
+ raise ValueError("建房须提供 32–256 字符的房间控制凭据")
442
+ if any(token_hash(member["token"]) == control for member in members):
443
+ raise ValueError("成员凭证不能与房主控制凭据相同")
444
+ connection.execute("INSERT INTO room_modes (room_id,mode,control_hash) VALUES (?,?,?)", (room_id, settings["mode"], control))
445
+ for member in members:
446
+ insert_member(connection, room_id, member, settings["created_at"])
447
+ connection.execute("UPDATE room_members SET role='host' WHERE room_id=? AND name=?", (room_id, settings["host"]))
448
+
449
+
450
+ def discussion_access_ok(access, capability, automatic, is_host, manual_source=""):
451
+ """Require web relays to stay read-only while local participants use runner or manual access."""
452
+ if capability == "online":
453
+ return access == "manual" and manual_source == "web" and not is_host
454
+ if manual_source == "web":
455
+ return False
456
+ if not automatic:
457
+ return access == "manual"
458
+ return access == "runner" or (access == "manual" and not is_host)
459
+
460
+
461
+ def mark_manual(member, automatic):
462
+ """A manual expert of a woken discussion carries adapter 'manual', so mode switches never turn it into a woken member."""
463
+ return {**member, "adapter": "manual"} if automatic and member["access"] == "manual" else member
464
+
465
+
466
+ def discussion_members(payload, settings):
467
+ """Validate credentials against the room's declared participants and delivery mode."""
468
+ members = member_values(payload.get("members")) if settings["experts"] else []
469
+ if {member["name"] for member in members} != set(settings["experts"]):
470
+ raise ValueError("成员凭证名单须与参与者名单一致")
471
+ for member in members:
472
+ if not discussion_access_ok(member["access"], settings["experts"][member["name"]],
473
+ payload.get("runtime_mode") == "automatic", member["name"] == settings["host"],
474
+ member["manual_source"]):
475
+ raise ValueError("成员接入方式与房间参与能力、任务交付方式不符")
476
+ return [mark_manual(member, payload.get("runtime_mode") == "automatic") for member in members]
477
+
478
+
479
+ def sync_discussion_members(connection, room_id, payload, settings):
480
+ """Keep existing credentials; require fresh credentials for added or changed members."""
481
+ current = {row["name"]: row for row in connection.execute("""SELECT m.*,
482
+ COALESCE(s.source,'') AS manual_source FROM room_members m
483
+ LEFT JOIN member_manual_sources s ON s.member_id=m.id WHERE m.room_id=? AND m.status='active'""", (room_id,))}
484
+ supplied = {member["name"]: member_value(member) for member in payload.get("members", [])}
485
+ run = connection.execute("SELECT mode FROM discussion_runtime WHERE room_id=?", (room_id,)).fetchone()
486
+ for name, capability in settings["experts"].items():
487
+ automatic = bool(run and run[0] == "automatic")
488
+ old = current.get(name)
489
+ if old and (old["manual_source"] == "web") == (capability == "online"):
490
+ if name in supplied and token_hash(supplied[name]["token"]) != old["token_hash"]:
491
+ raise FileExistsError("成员凭证与已登记身份不符;请核对原接入文件")
492
+ continue
493
+ if name not in supplied or not discussion_access_ok(supplied[name]["access"], capability, automatic,
494
+ name == settings["host"], supplied[name]["manual_source"]):
495
+ raise ValueError(f"新增或改变接入方式的成员 {name} 须提供独立的新凭证")
496
+ member = mark_manual(supplied[name], automatic)
497
+ hashed = token_hash(member["token"])
498
+ if connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND token_hash=? UNION ALL SELECT 1 FROM room_modes WHERE room_id=? AND control_hash=?", (room_id, hashed, room_id, hashed)).fetchone():
499
+ raise ValueError("新成员凭证不能复用已有凭证")
500
+ connection.execute("UPDATE room_members SET status='removed' WHERE room_id=? AND name=?", (room_id, name))
501
+ insert_member(connection, room_id, member, int(time.time()))
502
+ for name in current.keys() - settings["experts"].keys():
503
+ connection.execute("UPDATE room_members SET status='removed' WHERE room_id=? AND name=?", (room_id, name))
504
+ connection.execute("UPDATE room_members SET role=CASE WHEN name=? THEN 'host' ELSE 'member' END WHERE room_id=?", (settings["host"], room_id))
505
+
506
+
507
+ def sync_participants(connection, room_id):
508
+ """Keep one active AI host, then mirror member capabilities and the host into shared room metadata."""
509
+ connection.execute(RELEASE_HOST, (room_id,))
510
+ connection.execute(ASSIGN_HOST, (room_id, room_id))
511
+ members = connection.execute("""SELECT m.name,m.access,m.role,m.status,COALESCE(s.source,'') AS manual_source
512
+ FROM room_members m LEFT JOIN member_manual_sources s ON s.member_id=m.id
513
+ WHERE m.room_id=? AND m.status<>'removed' ORDER BY m.id""", (room_id,)).fetchall()
514
+ experts = {row["name"]: "online" if row["manual_source"] == "web" else "cli" for row in members}
515
+ host = next((row["name"] for row in members if row["role"] == "host" and row["status"] == "active"), "用户")
516
+ connection.execute("UPDATE topic_settings SET experts=?,host=? WHERE room_id=?",
517
+ (json.dumps(experts, ensure_ascii=False), host, room_id))
518
+
519
+
520
+ def public_execution(row):
521
+ """Return execution state without any credential material."""
522
+ return {key: row[key] for key in EXECUTION_FIELDS} if row else None
523
+
524
+
525
+ def execution_retry(connection, execution_id):
526
+ """What the runner reported about a waiting retry of one execution, or None."""
527
+ row = connection.execute("SELECT attempt,retry_at,reason,stopped FROM execution_retries WHERE execution_id=?", (execution_id,)).fetchone()
528
+ return dict(row) if row else None
529
+
530
+
531
+ def member_descriptions(connection, room_id):
532
+ """The owner's descriptions of members by name; everyone who can read the room may read them."""
533
+ return {row["name"]: row["description"] for row in connection.execute(
534
+ "SELECT name,description FROM member_descriptions WHERE room_id=? ORDER BY name", (room_id,))}
535
+
536
+
537
+ def describe_members(connection, room_id, token, payload):
538
+ """Owner sets members' descriptions by name; an empty text removes that member's description."""
539
+ require_owner(connection, room_id, token)
540
+ descriptions = payload.get("descriptions")
541
+ if (not isinstance(descriptions, dict) or not descriptions or len(descriptions) > MAX_ROOM_AGENTS
542
+ or any(not isinstance(name, str) or not 0 < len(name) <= MAX_MEMBER_NAME or not isinstance(text, str)
543
+ or len(text) > MAX_MEMBER_DESCRIPTION for name, text in descriptions.items())):
544
+ raise ValueError(f"descriptions 须为 {{成员名: 描述}},最多 {MAX_ROOM_AGENTS} 位,每段最多 {MAX_MEMBER_DESCRIPTION} 字")
545
+ begin_write(connection)
546
+ now = int(time.time())
547
+ for name, text in descriptions.items():
548
+ if text.strip():
549
+ connection.execute("""INSERT INTO member_descriptions (room_id,name,description,updated_at) VALUES (?,?,?,?)
550
+ ON CONFLICT(room_id,name) DO UPDATE SET description=excluded.description,updated_at=excluded.updated_at""",
551
+ (room_id, name, text.strip(), now))
552
+ else:
553
+ connection.execute("DELETE FROM member_descriptions WHERE room_id=? AND name=?", (room_id, name))
554
+ return {"descriptions": member_descriptions(connection, room_id)}
555
+
556
+
557
+ def member_labels(connection, room_id):
558
+ """The owner's display labels of members by name; only screens use them, never addressing or credentials."""
559
+ return {row["name"]: row["label"] for row in connection.execute(
560
+ "SELECT name,label FROM member_labels WHERE room_id=? ORDER BY name", (room_id,))}
561
+
562
+
563
+ def label_members(connection, room_id, token, payload):
564
+ """Owner sets members' display labels by name; an empty text removes that member's label."""
565
+ require_owner(connection, room_id, token)
566
+ labels = payload.get("labels")
567
+ if (not isinstance(labels, dict) or not labels or len(labels) > MAX_ROOM_AGENTS
568
+ or any(not isinstance(name, str) or not 0 < len(name) <= MAX_MEMBER_NAME or not isinstance(text, str)
569
+ or len(text.strip()) > MAX_MEMBER_LABEL for name, text in labels.items())):
570
+ raise ValueError(f"labels 须为 {{成员名: 显示名}},最多 {MAX_ROOM_AGENTS} 位,每个最多 {MAX_MEMBER_LABEL} 字")
571
+ begin_write(connection)
572
+ now = int(time.time())
573
+ for name, text in labels.items():
574
+ if text.strip():
575
+ connection.execute("""INSERT INTO member_labels (room_id,name,label,updated_at) VALUES (?,?,?,?)
576
+ ON CONFLICT(room_id,name) DO UPDATE SET label=excluded.label,updated_at=excluded.updated_at""",
577
+ (room_id, name, text.strip(), now))
578
+ else:
579
+ connection.execute("DELETE FROM member_labels WHERE room_id=? AND name=?", (room_id, name))
580
+ return {"labels": member_labels(connection, room_id)}
581
+
582
+ def note_count(connection, execution_id):
583
+ """How many progress notes an execution has; the texts are read separately so room views stay small."""
584
+ return connection.execute("SELECT COUNT(*) FROM execution_notes WHERE execution_id=?", (execution_id,)).fetchone()[0]
585
+
586
+
587
+ def execution_notes(connection, room_id, execution_id, token=""):
588
+ """Read one execution's progress notes in order, with the same access as the room view."""
589
+ execution = connection.execute("SELECT member_id FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
590
+ if not execution:
591
+ raise LookupError("执行不存在")
592
+ from .session_room import session_message_access
593
+
594
+ boundary = session_message_access(connection, room_id, {}, token)
595
+ if boundary is not None:
596
+ try:
597
+ member = require_member(connection, room_id, token)
598
+ except PermissionError:
599
+ return {"notes": []}
600
+ if member["id"] != execution["member_id"]:
601
+ return {"notes": []}
602
+ return {"notes": [dict(row) for row in connection.execute(
603
+ "SELECT seq,text,created_at FROM execution_notes WHERE execution_id=? ORDER BY seq", (execution_id,))]}
604
+
605
+
606
+ def execution_timeline(connection, room_id, after=0):
607
+ """Read the room's recent executions of both kinds with their phase segments and note times, for the timeline page.
608
+
609
+ Times are epoch seconds and segments are millisecond offsets from `dispatched_at`. A free execution's parent is the
610
+ execution that wrote the message it answers; discussion executions have none. `state` is running, done, failed
611
+ or cancelled, so the page never interprets execution statuses itself. A positive `after` reads only executions
612
+ still running or ended since then, so a page following live work rereads little.
613
+ """
614
+ if not connection.execute("SELECT 1 FROM rooms WHERE id=?", (room_id,)).fetchone():
615
+ raise LookupError("房间不存在")
616
+ params = (room_id, TIMELINE_EXECUTIONS, max(0, int(after)))
617
+ rows = [dict(row) for row in connection.execute(TIMELINE_SQL, params)]
618
+ segments, notes = {}, {}
619
+ for row in connection.execute(TIMELINE_SEGMENTS_SQL, params):
620
+ segments.setdefault((row["source"], row["execution_id"]), []).append(
621
+ {key: row[key] for key in ("phase", "tool", "start_ms", "end_ms")})
622
+ for row in connection.execute(TIMELINE_NOTES_SQL, params):
623
+ notes.setdefault(row["execution_id"], []).append(row["created_at"])
624
+ for row in rows:
625
+ row["state"] = TIMELINE_STATES.get(row["status"], "running")
626
+ row["segments"] = segments.get((row["source"], row["id"]), [])
627
+ row["notes"] = notes.get(row["id"], []) if row["source"] == "free" else []
628
+ return {"now": int(time.time()), "after": params[2], "executions": rows, "execution_limit": TIMELINE_EXECUTIONS,
629
+ "segment_limit": MAX_EXECUTION_SEGMENTS}
630
+
631
+
632
+ def recent_executions(connection, room_id):
633
+ """Return bounded public reports, including requests no longer in the recent request list."""
634
+ rows = connection.execute("""SELECT e.*,m.name AS member,
635
+ (SELECT json_group_array(id) FROM member_requests WHERE execution_id=e.id) AS request_ids,
636
+ (SELECT MAX(answer_id) FROM member_requests WHERE execution_id=e.id) AS answer_id,
637
+ (SELECT MIN(message_id) FROM member_requests WHERE execution_id=e.id) AS request_message_id,
638
+ (SELECT COUNT(*) FROM execution_notes WHERE execution_id=e.id) AS note_count,
639
+ (SELECT denials FROM execution_denials WHERE execution_id=e.id) AS denials
640
+ FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.room_id=? ORDER BY e.id DESC LIMIT ?""", (room_id, RECENT_EXECUTIONS))
641
+ executions = []
642
+ for row in rows:
643
+ requests = []
644
+ for request in connection.execute("SELECT id,message_id,purpose,status,answer_id FROM member_requests WHERE execution_id=? ORDER BY id", (row["id"],)):
645
+ requests.append({**dict(request), **session_request_source(connection, request["id"], request["message_id"])})
646
+ executions.append({**public_execution(row), "member": row["member"], "cwd": row["cwd"], "changes": json.loads(row["changes"] or "[]"),
647
+ "changes_recorded": bool(row["changes"]), "request_ids": json.loads(row["request_ids"]),
648
+ "answer_id": row["answer_id"], "request_message_id": row["request_message_id"], "requests": requests,
649
+ "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"),
650
+ "retry": execution_retry(connection, row["id"])})
651
+ return executions
652
+
653
+
654
+ def session_request_source(connection, member_request_id, message_id):
655
+ """Expose session provenance and a visible transcript anchor for a member request."""
656
+ row = connection.execute("""SELECT q.id AS session_request_id,q.session_id AS discussion_session_id,q.round,
657
+ q.question AS source_question,t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id,
658
+ CASE WHEN q.id IS NULL THEN r.message_id ELSE COALESCE((SELECT MAX(m.id) FROM messages m
659
+ WHERE m.room_id=r.room_id AND m.id<r.message_id
660
+ AND NOT EXISTS(SELECT 1 FROM internal_task_messages hidden WHERE hidden.message_id=m.id)),0) END AS session_anchor
661
+ FROM member_requests r LEFT JOIN session_requests q ON q.member_request_id=r.id
662
+ LEFT JOIN task_message_sources t ON t.session_request_id=q.id WHERE r.id=?""", (member_request_id,)).fetchone()
663
+ if row and row["session_request_id"] is not None:
664
+ return {"session_request_id": row["session_request_id"], "discussion_session_id": row["discussion_session_id"],
665
+ "round": row["round"], "source_question": row["source_question"],
666
+ "source_message_id": row["source_message_id"], "cause_kind": row["cause_kind"],
667
+ "cause_request_id": row["cause_request_id"], "after_message_id": row["session_anchor"]}
668
+ request = connection.execute("SELECT message_id,purpose FROM member_requests WHERE id=?", (member_request_id,)).fetchone()
669
+ return {"session_request_id": None, "discussion_session_id": None, "round": None, "source_question": "",
670
+ "source_message_id": None, "cause_kind": None, "cause_request_id": None, "after_message_id": message_id,
671
+ **review_request_context(connection, request)}
672
+
673
+
674
+ def possible_conflicts(connection, room_id, names):
675
+ """Report files changed by executions of different members whose time windows overlapped.
676
+
677
+ This is an observation, not attribution: it cannot tell who wrote which part or catch
678
+ writes outside the scanned working directory.
679
+ """
680
+ now = int(time.time())
681
+ rows = [dict(row) for row in connection.execute(
682
+ """SELECT id,member_id,created_at,finished_at,changes,cwd FROM member_executions
683
+ WHERE room_id=? AND changes<>'' ORDER BY id DESC LIMIT ?""", (room_id, RECENT_CHANGES))]
684
+ for row in rows:
685
+ row["files"] = set(json.loads(row["changes"]))
686
+ row["end"] = row["finished_at"] or now
687
+ conflicts = []
688
+ for index, first in enumerate(rows):
689
+ for second in rows[index + 1:]:
690
+ if first["member_id"] == second["member_id"] or first["cwd"] != second["cwd"]:
691
+ continue
692
+ if first["created_at"] > second["end"] or second["created_at"] > first["end"]:
693
+ continue
694
+ files = sorted(first["files"] & second["files"])
695
+ if files:
696
+ conflicts.append({"members": [names.get(second["member_id"], ""), names.get(first["member_id"], "")],
697
+ "executions": [second["id"], first["id"]], "files": files})
698
+ return conflicts
699
+
700
+
701
+ # An invited manual member that has not registered counts as absent: it receives no request and is never a target.
702
+ REGISTERED_MEMBER = """(room_members.access<>'manual' OR EXISTS(SELECT 1 FROM member_manual_sources source
703
+ WHERE source.member_id=room_members.id AND source.source='web') OR EXISTS(SELECT 1 FROM member_registrations r
704
+ WHERE r.member_id=room_members.id AND r.token_hash=room_members.token_hash))"""
705
+
706
+ # One snapshot for group routing; the Worker uses the same SQL inside its atomic write assertion.
707
+ GROUP_STATE_SQL = f"""SELECT json_object(
708
+ 'latest_id',(SELECT COALESCE(MAX(id),0) FROM messages WHERE room_id=rooms.id),
709
+ 'title',rooms.title,'goal',rooms.goal,
710
+ 'archived',(SELECT archived FROM room_directory WHERE room_id=rooms.id),
711
+ 'order',COALESCE((SELECT member_ids FROM speaking_orders WHERE room_id=rooms.id),'[]'),
712
+ 'members',(SELECT json_group_array(json_object('id',id,'name',name,'role',role,'status',status,'access',access,
713
+ 'registered',{REGISTERED_MEMBER},'description',COALESCE((SELECT description FROM member_descriptions d
714
+ WHERE d.room_id=room_members.room_id AND d.name=room_members.name),'')))
715
+ FROM (SELECT * FROM room_members WHERE room_id=rooms.id ORDER BY id) AS room_members)) AS state
716
+ FROM rooms WHERE id=?"""
717
+
718
+
719
+ def free_view(connection, room_id):
720
+ """Summarize members, their live execution, recent requests and possible file conflicts."""
721
+ now = int(time.time())
722
+ members = []
723
+ for row in connection.execute("SELECT * FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id", (room_id,)):
724
+ member = {key: row[key] for key in MEMBER_FIELDS}
725
+ source = connection.execute("SELECT source FROM member_manual_sources WHERE member_id=?", (row["id"],)).fetchone()
726
+ member["manual_source"] = source[0] if source else ""
727
+ member["registered_at"] = registered_at(connection, row)
728
+ reported = connection.execute("SELECT session_id,client FROM member_sessions WHERE member_id=?", (row["id"],)).fetchone()
729
+ member["reported_session"], member["reported_client"] = (reported["session_id"], reported["client"]) if reported else ("", "")
730
+ latest = connection.execute("SELECT * FROM member_executions WHERE member_id=? ORDER BY id DESC LIMIT 1",
731
+ (row["id"],)).fetchone()
732
+ member["execution"] = public_execution(latest)
733
+ if latest and latest["status"] in ACTIVE:
734
+ member["execution"]["stale"] = latest["lease_until"] <= now
735
+ member["execution"]["notes"] = note_count(connection, latest["id"])
736
+ member["execution"]["retry"] = execution_retry(connection, latest["id"])
737
+ member["pending"] = connection.execute("SELECT COUNT(*) FROM member_requests WHERE member_id=? AND status='pending'",
738
+ (row["id"],)).fetchone()[0]
739
+ members.append(member)
740
+ names = {row["id"]: row["name"] for row in connection.execute("SELECT id,name FROM room_members WHERE room_id=?", (room_id,))}
741
+ requests = [{**dict(row), "member": names.get(row["member_id"], ""),
742
+ **session_request_source(connection, row["id"], row["message_id"])} for row in connection.execute(
743
+ """SELECT id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose,created_by,created_at,
744
+ (SELECT reason FROM request_cancel_reasons c WHERE c.request_id=member_requests.id) AS cancel_reason FROM member_requests
745
+ WHERE room_id=? ORDER BY id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
746
+ chains = [dict(row) for row in connection.execute(
747
+ "SELECT chain_id,reason FROM free_chains WHERE room_id=? ORDER BY chain_id DESC LIMIT 10", (room_id,))]
748
+ max_rounds = chain_rounds(connection, room_id)
749
+ progress = [dict(row) for row in connection.execute(CHAIN_PROGRESS_SQL, (max_rounds, room_id))]
750
+ return {"members": members, "requests": requests[::-1], "executions": recent_executions(connection, room_id),
751
+ "conflicts": possible_conflicts(connection, room_id, names), "halted_chains": chains, "max_rounds": max_rounds,
752
+ "chain_rounds": progress, "recommendations": recent_recommendations(connection, room_id, now)[::-1]}
753
+
754
+
755
+ def require_member(connection, room_id, token, name=None):
756
+ """Resolve an active member strictly from its own credential."""
757
+ hashed = token_hash(token)
758
+ row = connection.execute("SELECT * FROM room_members WHERE room_id=? AND token_hash=? AND status='active'",
759
+ (room_id, hashed)).fetchone() if hashed else None
760
+ if not row or (name is not None and row["name"] != name):
761
+ raise PermissionError("成员凭证无效、已停用或与发言身份不符")
762
+ if connection.execute("SELECT 1 FROM member_manual_sources WHERE member_id=? AND source='web'", (row["id"],)).fetchone():
763
+ raise PermissionError("网页成员只读;由房主凭据代发其回答")
764
+ return dict(row)
765
+
766
+
767
+ def registered_at(connection, member):
768
+ """Return when the member registered with its current credential, or '' while it has not."""
769
+ row = connection.execute("SELECT registered_at FROM member_registrations WHERE member_id=? AND token_hash=?",
770
+ (member["id"], member["token_hash"])).fetchone()
771
+ return row[0] if row else ""
772
+
773
+
774
+ def register_member(connection, room_id, token, now):
775
+ """A manual member announces itself with its own credential; repeating it keeps the first time.
776
+
777
+ The session ID is not part of the request: the CLI attaches it to every call and the room records it separately.
778
+ """
779
+ begin_write(connection)
780
+ member = require_member(connection, room_id, token)
781
+ if member["access"] != "manual":
782
+ raise ValueError("只有手动接入的成员需要注册")
783
+ previous = registered_at(connection, member)
784
+ stamp = previous or now
785
+ connection.execute("""INSERT INTO member_registrations (member_id,room_id,token_hash,registered_at) VALUES (?,?,?,?)
786
+ ON CONFLICT(member_id) DO UPDATE SET token_hash=excluded.token_hash,registered_at=excluded.registered_at""",
787
+ (member["id"], room_id, member["token_hash"], stamp))
788
+ if not previous:
789
+ queue_invited_expert(connection, room_id, member["name"], now)
790
+ reported = connection.execute("SELECT client FROM member_sessions WHERE member_id=?", (member["id"],)).fetchone()
791
+ return {"member": member["name"], "registered_at": stamp, "session_client": reported[0] if reported else ""}
792
+
793
+
794
+ def authorize_free_write(connection, room_id, token, operation, payload):
795
+ """Decide who is writing: the owner, or one member posting its own answer.
796
+
797
+ Returns:
798
+ "用户" for the owner, or the member row for a member credential.
799
+ """
800
+ begin_write(connection)
801
+ if operation not in FREE_OPERATIONS:
802
+ raise ValueError("自由房间不使用发言权、安排、阶段或轮次")
803
+ try:
804
+ require_owner(connection, room_id, token)
805
+ return "用户"
806
+ except PermissionError:
807
+ if operation not in ("messages", "attachments"):
808
+ raise
809
+ author = payload.get("author")
810
+ member = require_member(connection, room_id, token)
811
+ if author == member["name"] and payload.get("submitted_by", author) == author:
812
+ return member
813
+ if member["role"] == "host" and author != member["name"] and payload.get("submitted_by") == member["name"]:
814
+ proxy = proxy_member(connection, room_id, author)
815
+ proxy["proxy_by"] = member["name"]
816
+ return proxy
817
+ raise PermissionError("成员只能以本人身份发言;只有主持人可以代发在线成员回答")
818
+
819
+
820
+ def active_members(connection, room_id, registered_only=True):
821
+ """Map active member names to their rows; unregistered manual members are left out unless a discussion start needs them pending."""
822
+ return {row["name"]: row for row in connection.execute(
823
+ f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND ({REGISTERED_MEMBER} OR ?=0)", (room_id, int(registered_only)))}
824
+
825
+
826
+ def named_members(active, names, exclude=None):
827
+ """Validate a structured recipient list against the active members."""
828
+ if not isinstance(names, list) or any(name not in active or name == exclude for name in names):
829
+ raise ValueError("点名对象须为本房间在场成员" + (",且不能点名自己" if exclude else ""))
830
+ return [active[name]["id"] for name in dict.fromkeys(names)]
831
+
832
+
833
+ def recipients(connection, room_id, payload):
834
+ """Resolve an owner message's recipients as (member id, purpose) pairs.
835
+
836
+ A single active member is named by default. With several, an unnamed message goes to the
837
+ AI host for routing; only a room of online members has none, and then it stays a plain note.
838
+ Naming everyone with order auto leaves the host a group request: the runner has everyone answer
839
+ at once or one after another; a host the runner does not wake has them all answer at once.
840
+ """
841
+ # Rooms created while the user could host get their AI host on the next message.
842
+ sync_participants(connection, room_id)
843
+ active = active_members(connection, room_id)
844
+ if payload.get("to") is not None:
845
+ named = named_members(active, payload["to"])
846
+ host = next((row for row in active.values() if row["role"] == "host"), None)
847
+ if payload.get("order") == "auto" and len(named) > 1 and host and host["access"] == "runner":
848
+ return [(host["id"], "group")]
849
+ return [(member_id, "ask") for member_id in named]
850
+ if len(active) == 1:
851
+ return [(next(iter(active.values()))["id"], "ask")]
852
+ host = next((row for row in active.values() if row["role"] == "host"), None)
853
+ return [(host["id"], "route")] if host else []
854
+
855
+
856
+ def route_held_messages(connection, room_id, host):
857
+ """When a discussion ends, hand the user's messages its host never answered to the free room's recipients, as if just sent."""
858
+ held = connection.execute("SELECT held_since FROM turn_relay WHERE room_id=?", (room_id,)).fetchone()
859
+ if held and held[0]:
860
+ rows = connection.execute("""SELECT id FROM messages m WHERE room_id=? AND author='用户' AND id>=?
861
+ AND id>COALESCE((SELECT MAX(id) FROM messages WHERE room_id=? AND author=?),0)
862
+ AND NOT EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id=m.id) ORDER BY id""",
863
+ (room_id, held[0], room_id, host)).fetchall()
864
+ for row in rows:
865
+ for member_id, purpose in recipients(connection, room_id, {}):
866
+ insert_request(connection, room_id, member_id, row["id"], row["id"], purpose, "user")
867
+ connection.execute("UPDATE turn_relay SET held_since=0 WHERE room_id=?", (room_id,))
868
+
869
+
870
+ def proxy_member(connection, room_id, author):
871
+ """Return the active online member the owner may forward an answer for."""
872
+ row = connection.execute("""SELECT m.*,s.source AS manual_source FROM room_members m
873
+ JOIN member_manual_sources s ON s.member_id=m.id AND s.source='web'
874
+ WHERE m.room_id=? AND m.name=? AND m.status='active' AND m.access='manual'""",
875
+ (room_id, author)).fetchone()
876
+ if not row:
877
+ raise PermissionError("房间控制凭据只能以用户身份发言,或代发在线成员的回答")
878
+ return dict(row)
879
+
880
+
881
+ def check_answer(connection, room_id, member, payload):
882
+ """A runner member completes a live execution; a manual member may close its own open requests.
883
+
884
+ Only the AI host dispatches work; other members' targets remain suggestions.
885
+ """
886
+ if payload.get("to") is not None:
887
+ named_members(active_members(connection, room_id), payload["to"], exclude=member["name"])
888
+ if payload.get("handoff") not in (None, False) and (payload["handoff"] is not True or member["role"] != "host" or not payload.get("to")):
889
+ raise ValueError("handoff 只能由主持人与 to 一起使用,值为 true")
890
+ if member["access"] == "online":
891
+ raise PermissionError("在线成员只读,回答由用户代发")
892
+ if member["access"] == "manual":
893
+ request_ids = payload.get("request_ids", [])
894
+ if payload.get("execution_id") is not None or not isinstance(request_ids, list) or any(type(item) is not int for item in request_ids):
895
+ raise ValueError("手动接入成员用 request_ids 关联请求,不使用执行编号")
896
+ purposes = []
897
+ requests = []
898
+ for request_id in request_ids:
899
+ row = connection.execute("SELECT * FROM member_requests WHERE room_id=? AND id=?", (room_id, request_id)).fetchone()
900
+ if not row or row["member_id"] != member["id"] or row["status"] != "pending":
901
+ raise FileExistsError(f"请求 {request_id} 不属于本成员或已处理")
902
+ purposes.append(row["purpose"])
903
+ requests.append(row)
904
+ validate_session_request_answer(connection, room_id, requests)
905
+ check_dispatch(member, payload, purposes)
906
+ return None
907
+ execution_id = payload.get("execution_id")
908
+ if type(execution_id) is not int:
909
+ raise ValueError("成员回答须关联本次执行编号 execution_id")
910
+ row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
911
+ if not row or row["member_id"] != member["id"]:
912
+ raise PermissionError("执行编号不属于本成员")
913
+ if row["status"] not in ACTIVE or row["lease_until"] <= int(time.time()):
914
+ raise FileExistsError("本次执行已结束、被打断或已过期;回答不能改作普通发言,请保留草稿")
915
+ requests = [dict(item) for item in connection.execute(
916
+ "SELECT id,purpose FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,))]
917
+ validate_session_request_answer(connection, room_id, requests)
918
+ check_dispatch(member, payload, [item["purpose"] for item in requests])
919
+ return row
920
+
921
+
922
+ def check_dispatch(member, payload, purposes):
923
+ """A host answering only its share of an everyone request answers as a member, so it may not dispatch others."""
924
+ if member["role"] == "host" and payload.get("to") and purposes and all(purpose == "all" for purpose in purposes):
925
+ raise ValueError("这次是请全体成员各自回应,其他成员已收到请求;主持人只回答自己的部分,不能用 --to 派活")
926
+
927
+
928
+ def validate_session_request_answer(connection, room_id, requests):
929
+ """Keep a discussion speaker request separate and live when answering it."""
930
+ discussions = [request for request in requests if request["purpose"] == "discuss"]
931
+ if not discussions:
932
+ return
933
+ if len(requests) != 1 or len(discussions) != 1:
934
+ raise ValueError("讨论安排须单独回答,不能与普通请求合并")
935
+ request_id = discussions[0]["id"]
936
+ plan = connection.execute("""SELECT sr.status,s.status AS session_status FROM session_requests sr
937
+ JOIN discussion_sessions s ON s.id=sr.session_id JOIN member_requests r ON r.id=sr.member_request_id
938
+ WHERE s.room_id=? AND r.id=? AND sr.purpose='discuss'""", (room_id, request_id)).fetchone()
939
+ if not plan or plan["session_status"] != "active" or plan["status"] != "open":
940
+ raise FileExistsError("讨论安排已暂停、结束或取消,不能继续回答")
941
+
942
+
943
+ def check_proxy(connection, room_id, member, payload):
944
+ """The owner forwards an online member's answer and may close that member's open requests."""
945
+ request_ids = payload.get("request_ids", [])
946
+ if not isinstance(request_ids, list) or any(type(item) is not int for item in request_ids):
947
+ raise ValueError("request_ids 须为请求编号列表")
948
+ requests = []
949
+ for request_id in request_ids:
950
+ row = connection.execute("SELECT * FROM member_requests WHERE room_id=? AND id=?", (room_id, request_id)).fetchone()
951
+ if not row or row["member_id"] != member["id"] or row["status"] != "pending":
952
+ raise FileExistsError(f"请求 {request_id} 不属于该在线成员或已处理")
953
+ requests.append(row)
954
+ validate_session_request_answer(connection, room_id, requests)
955
+
956
+
957
+ def insert_request(connection, room_id, member_id, message_id, chain_id, purpose, created_by, batch_id=0):
958
+ """Queue one request; every request belongs to the chain its owner message started."""
959
+ connection.execute("""INSERT INTO member_requests (room_id,member_id,message_id,chain_id,batch_id,purpose,created_by,created_at)
960
+ VALUES (?,?,?,?,?,?,?,?)""", (room_id, member_id, message_id, chain_id, batch_id, purpose, created_by, int(time.time())))
961
+
962
+
963
+ def mention_prose(text):
964
+ """Remove Markdown code and quote blocks before interpreting response suggestions."""
965
+ lines, fence, quoted = [], "", False
966
+ for line in text.splitlines():
967
+ marker = re.match(r"^ {0,3}(`{3,}|~{3,})", line)
968
+ if marker:
969
+ value = marker[1]
970
+ if not fence:
971
+ fence = value
972
+ elif value[0] == fence[0] and len(value) >= len(fence):
973
+ fence = ""
974
+ continue
975
+ if fence or re.match(r"^( {4}|\t)", line):
976
+ continue
977
+ if re.match(r"^ {0,3}>", line):
978
+ quoted = True
979
+ continue
980
+ if not line.strip():
981
+ quoted = False
982
+ if not quoted:
983
+ lines.append(line)
984
+ return re.sub(r"(`+)[\s\S]*?\1(?!`)", "", "\n".join(lines))
985
+
986
+
987
+ def save_suggestions(connection, room_id, message_id, member, payload):
988
+ """Save ordinary members' explicit targets and prose mentions without waking anyone."""
989
+ if member == "用户" or member["role"] == "host":
990
+ return
991
+ active = active_members(connection, room_id)
992
+ targets = set(named_members(active, payload["to"] if payload.get("to") is not None else [], exclude=member["name"]))
993
+ prose = mention_prose(str(payload.get("text", "")))
994
+ for name, target in active.items():
995
+ if name != member["name"] and re.search(r"(^|[\s((,,。;;::])@" + re.escape(name) + r"(?![A-Za-z0-9_\-\u4e00-\u9fff])", prose):
996
+ targets.add(target["id"])
997
+ for target_id in targets:
998
+ connection.execute("INSERT INTO member_suggestions (message_id,member_id) VALUES (?,?)", (message_id, target_id))
999
+
1000
+
1001
+ def message_suggestions(connection, message_id):
1002
+ """Expose suggested members and the durable request, including terminal conversions."""
1003
+ return [dict(row) for row in connection.execute("""SELECT s.member_id,m.name AS member,m.status,
1004
+ r.id AS request_id,r.status AS request_status FROM member_suggestions s
1005
+ JOIN room_members m ON m.id=s.member_id
1006
+ LEFT JOIN member_requests r ON r.message_id=s.message_id AND r.member_id=s.member_id
1007
+ WHERE s.message_id=? ORDER BY s.member_id""", (message_id,))]
1008
+
1009
+
1010
+ def convert_suggestion(connection, room_id, token, payload):
1011
+ """Let the owner turn a saved suggestion into one request and a fresh user chain."""
1012
+ begin_write(connection)
1013
+ require_owner(connection, room_id, token)
1014
+ message_id, member_id = payload.get("message_id"), payload.get("member_id")
1015
+ if type(message_id) is not int or type(member_id) is not int:
1016
+ raise ValueError("须提供原消息编号 message_id 与成员编号 member_id")
1017
+ target = connection.execute("""SELECT m.name,m.status FROM member_suggestions s
1018
+ JOIN messages source ON source.id=s.message_id JOIN room_members m ON m.id=s.member_id
1019
+ WHERE source.room_id=? AND m.room_id=? AND s.message_id=? AND s.member_id=?""",
1020
+ (room_id, room_id, message_id, member_id)).fetchone()
1021
+ if not target:
1022
+ raise LookupError("这条消息没有该成员的回应建议")
1023
+ if target["status"] != "active":
1024
+ raise FileExistsError("该成员已离开,不能转为请求")
1025
+ if connection.execute("SELECT 1 FROM room_directory WHERE room_id=? AND archived=1", (room_id,)).fetchone():
1026
+ raise ValueError("房间已存档;恢复后才能继续协作")
1027
+ previous = connection.execute("SELECT * FROM member_requests WHERE message_id=? AND member_id=?", (message_id, member_id)).fetchone()
1028
+ if previous:
1029
+ return {"request": dict(previous), "duplicate": True}
1030
+ confirmation = connection.execute("""INSERT INTO messages (room_id,author,text,reply_to,source,submission_id,created_at)
1031
+ VALUES (?,'用户',?,?,'user',?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))""",
1032
+ (room_id, f"请 @{target['name']} 回应 #{message_id} 的建议。", message_id, uuid.uuid4().hex))
1033
+ connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,'chat','用户')", (confirmation.lastrowid,))
1034
+ insert_request(connection, room_id, member_id, message_id, confirmation.lastrowid, "ask", "user")
1035
+ request = connection.execute("SELECT * FROM member_requests WHERE message_id=? AND member_id=?", (message_id, member_id)).fetchone()
1036
+ return {"request": dict(request), "duplicate": False}
1037
+
1038
+
1039
+ def halt_chain(connection, room_id, chain_id, reason):
1040
+ """Stop automatic progress on a chain; the user's next message starts a new one."""
1041
+ connection.execute("INSERT OR IGNORE INTO free_chains (room_id,chain_id,reason) VALUES (?,?,?)", (room_id, chain_id, reason))
1042
+
1043
+
1044
+ def rounds_left(connection, room_id, chain_id):
1045
+ """Rounds a chain may still start: the room's limit plus what the owner added, less the dispatches made; none once halted."""
1046
+ if connection.execute("SELECT 1 FROM free_chains WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone():
1047
+ return 0
1048
+ used = connection.execute("SELECT COUNT(*) FROM free_batches WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()[0]
1049
+ extra = connection.execute("SELECT extra_rounds FROM free_chain_holds WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()
1050
+ return chain_rounds(connection, room_id) + (extra[0] if extra else 0) - used
1051
+
1052
+
1053
+ def chain_rounds(connection, room_id):
1054
+ """Rounds a host may run from one owner message in this room."""
1055
+ row = connection.execute("SELECT max_rounds FROM free_round_limits WHERE room_id=?", (room_id,)).fetchone()
1056
+ return row[0] if row else CHAIN_ROUNDS
1057
+
1058
+
1059
+ def set_chain_rounds(connection, room_id, token, payload):
1060
+ """Owner sets the room's round limit; it applies to chains still running and to later ones."""
1061
+ require_owner(connection, room_id, token)
1062
+ value = payload.get("max_rounds")
1063
+ if type(value) is not int or not 1 <= value <= MAX_CHAIN_ROUNDS:
1064
+ raise ValueError(f"max_rounds 须为 1–{MAX_CHAIN_ROUNDS} 的整数")
1065
+ begin_write(connection)
1066
+ connection.execute("""INSERT INTO free_round_limits (room_id,max_rounds) VALUES (?,?)
1067
+ ON CONFLICT(room_id) DO UPDATE SET max_rounds=excluded.max_rounds""", (room_id, value))
1068
+ return {"max_rounds": value}
1069
+
1070
+
1071
+ def continue_chain(connection, room_id, token, chain_id, payload):
1072
+ """Owner lets a chain the round limit stopped run on: adds rounds and sends the dispatch the limit held back.
1073
+
1074
+ Bound to one known chain, so it takes no revision; a chain that is not stopped by its limit is refused.
1075
+ """
1076
+ require_owner(connection, room_id, token)
1077
+ rounds = payload.get("rounds")
1078
+ if type(rounds) is not int or not 1 <= rounds <= MAX_CHAIN_ROUNDS:
1079
+ raise ValueError(f"rounds 须为 1–{MAX_CHAIN_ROUNDS} 的整数")
1080
+ begin_write(connection)
1081
+ halted = connection.execute("SELECT reason FROM free_chains WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()
1082
+ if not halted or halted[0] != "budget":
1083
+ raise FileExistsError("这条任务链没有因轮数上限停下,无需继续")
1084
+ host = connection.execute("SELECT * FROM room_members WHERE room_id=? AND role='host' AND status='active'", (room_id,)).fetchone()
1085
+ if not host:
1086
+ raise ValueError("房间没有在场的主持人,无法继续")
1087
+ connection.execute("""INSERT INTO free_chain_holds (room_id,chain_id,extra_rounds) VALUES (?,?,?)
1088
+ ON CONFLICT(room_id,chain_id) DO UPDATE SET extra_rounds=extra_rounds+excluded.extra_rounds""", (room_id, chain_id, rounds))
1089
+ connection.execute("DELETE FROM free_chains WHERE room_id=? AND chain_id=?", (room_id, chain_id))
1090
+ held = connection.execute("SELECT message_id,names,handoff FROM free_chain_holds WHERE room_id=? AND chain_id=?", (room_id, chain_id)).fetchone()
1091
+ connection.execute("UPDATE free_chain_holds SET message_id=0,host_id=0,names='[]',handoff=0 WHERE room_id=? AND chain_id=?", (room_id, chain_id))
1092
+ if held["message_id"]:
1093
+ dispatch(connection, room_id, host, held["message_id"], json.loads(held["names"]), chain_id, bool(held["handoff"]))
1094
+ return free_view(connection, room_id)
1095
+
1096
+
1097
+ def hold_dispatch(connection, room_id, host, message_id, names, chain_id, handoff):
1098
+ """Stop a chain at its round limit, keeping the dispatch it held back so the owner can send it by continuing."""
1099
+ halt_chain(connection, room_id, chain_id, "budget")
1100
+ connection.execute("""INSERT INTO free_chain_holds (room_id,chain_id,message_id,host_id,names,handoff) VALUES (?,?,?,?,?,?)
1101
+ ON CONFLICT(room_id,chain_id) DO UPDATE SET message_id=excluded.message_id,host_id=excluded.host_id,names=excluded.names,
1102
+ handoff=excluded.handoff""", (room_id, chain_id, message_id, host["id"], json.dumps(list(names), ensure_ascii=False), int(handoff)))
1103
+
1104
+
1105
+ def dispatch(connection, room_id, host, message_id, names, chain_id, handoff=False):
1106
+ """Queue the host's named members as one batch, one round; several members, or one the host asked back, hand back when it ends."""
1107
+ member_ids = named_members(active_members(connection, room_id), names, exclude=host["name"])
1108
+ if not member_ids or not chain_id:
1109
+ return
1110
+ if rounds_left(connection, room_id, chain_id) < 1:
1111
+ hold_dispatch(connection, room_id, host, message_id, names, chain_id, handoff)
1112
+ return
1113
+ for member_id in member_ids:
1114
+ insert_request(connection, room_id, member_id, message_id, chain_id, "ask", "host", batch_id=message_id)
1115
+ connection.execute("INSERT INTO free_batches (room_id,batch_id,chain_id,host_id) VALUES (?,?,?,?)",
1116
+ (room_id, message_id, chain_id, host["id"]))
1117
+ if handoff:
1118
+ connection.execute("INSERT INTO free_handoffs (room_id,batch_id) VALUES (?,?)", (room_id, message_id))
1119
+
1120
+
1121
+ def settle_batches(connection, room_id):
1122
+ """Hand each finished batch back to its host once; an all-failed batch halts its chain instead."""
1123
+ for batch in connection.execute("SELECT * FROM free_batches WHERE room_id=? AND settled=0", (room_id,)).fetchall():
1124
+ statuses = [row[0] for row in connection.execute("SELECT status FROM member_requests WHERE room_id=? AND batch_id=?",
1125
+ (room_id, batch["batch_id"]))]
1126
+ if any(status not in TERMINAL for status in statuses):
1127
+ continue
1128
+ connection.execute("UPDATE free_batches SET settled=1 WHERE room_id=? AND batch_id=?", (room_id, batch["batch_id"]))
1129
+ host = connection.execute("SELECT * FROM room_members WHERE id=? AND status='active' AND role='host'", (batch["host_id"],)).fetchone()
1130
+ review = connection.execute("SELECT 1 FROM review_plans WHERE room_id=? AND (batch_id=? OR review_batch_id=?)", (room_id, batch["batch_id"], batch["batch_id"])).fetchone()
1131
+ if "completed" not in statuses:
1132
+ halt_chain(connection, room_id, batch["chain_id"], "all_failed")
1133
+ if review and host:
1134
+ insert_request(connection, room_id, host["id"], batch["batch_id"], batch["chain_id"], "handoff", "host")
1135
+ elif not host or len(statuses) < 2 and not connection.execute(
1136
+ "SELECT 1 FROM free_handoffs WHERE room_id=? AND batch_id=?", (room_id, batch["batch_id"])).fetchone():
1137
+ # One member's answer reaches the user directly unless the host asked for it back, e.g. to send it to a reviewer.
1138
+ continue
1139
+ else:
1140
+ # The hand-back closes the round it belongs to, so it is never held back: the last round still gets its summary.
1141
+ insert_request(connection, room_id, host["id"], batch["batch_id"], batch["chain_id"], "handoff", "host")
1142
+ advance_queues(connection, room_id)
1143
+
1144
+
1145
+ def queue_in_turn(connection, room_id, message_id, member_ids):
1146
+ """Line the named members up for one owner message in the room's speaking order; only the first is asked now."""
1147
+ chosen = set(member_ids)
1148
+ members = [dict(row) for row in connection.execute("SELECT id,name,role FROM room_members WHERE room_id=?", (room_id,))]
1149
+ for member in default_order(connection, room_id, [member for member in members if member["id"] in chosen]):
1150
+ connection.execute("INSERT INTO free_queue (room_id,message_id,member_id) VALUES (?,?,?)", (room_id, message_id, member["id"]))
1151
+ advance_queues(connection, room_id)
1152
+
1153
+
1154
+ def advance_queues(connection, room_id):
1155
+ """Ask the next queued member of each message whose previous request ended; members no longer present are skipped.
1156
+
1157
+ Asked rows stay, so the speaking order can still show who already answered.
1158
+ """
1159
+ connection.execute(f"""DELETE FROM free_queue WHERE room_id=? AND NOT {QUEUE_ASKED.format(row="free_queue")}
1160
+ AND NOT EXISTS(SELECT 1 FROM room_members m WHERE m.id=free_queue.member_id AND m.status='active')""", (room_id,))
1161
+ connection.execute(f"""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,batch_id,purpose,created_by,created_at)
1162
+ SELECT q.room_id,q.member_id,q.message_id,q.message_id,0,'ask','user',? FROM free_queue q
1163
+ WHERE q.room_id=? AND q.id=(SELECT MIN(x.id) FROM free_queue x WHERE x.message_id=q.message_id AND NOT {QUEUE_ASKED.format(row="x")})
1164
+ AND NOT EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id=q.message_id AND r.status IN ('pending','delivering'))""",
1165
+ (int(time.time()), room_id))
1166
+
1167
+
1168
+ def default_order(connection, room_id, members):
1169
+ """Members in the room's saved speaking order; without one (or for members it lacks), the host first, then by joining order."""
1170
+ row = connection.execute("SELECT member_ids FROM speaking_orders WHERE room_id=?", (room_id,)).fetchone()
1171
+ rank = {member_id: index for index, member_id in enumerate(json.loads(row[0]) if row else [])}
1172
+ return sorted(members, key=lambda member: (member["id"] not in rank, rank.get(member["id"], 0), member["role"] != "host", member["id"]))
1173
+
1174
+
1175
+ def speaking_order(connection, room):
1176
+ """Who spoke, who speaks now and who is next, shared by free rooms and discussions; only the not-yet-spoken part may be reordered.
1177
+
1178
+ A free room shows its latest unfinished one-after-another queue, else every member in the room's default order;
1179
+ a discussion shows the open round: speakers so far, the current turn, then this round's queued turns; a plan reaching into
1180
+ later rounds lists them apart in `later` (one name list per round), read-only. The revision changes with any of it.
1181
+ """
1182
+ active = [member for member in room["members"] if member["status"] == "active"]
1183
+ by_id = {member["id"]: member for member in active}
1184
+ ordered = [member["name"] for member in default_order(connection, room["id"], active)]
1185
+ items, kind, target, later = [], "default", 0, []
1186
+ session_plan_state = []
1187
+ if room["mode"] == "free":
1188
+ from .session_room import current_session
1189
+ session = current_session(connection, room["id"], active_only=True)
1190
+ if session:
1191
+ kind = "turns"
1192
+ target = session["id"]
1193
+ session_plan_state = [list(row) for row in connection.execute("""SELECT id,round,position,member_id,question,status,submission_id
1194
+ FROM session_requests WHERE session_id=? AND purpose='discuss' ORDER BY round,position,id""", (session["id"],))]
1195
+ active_round = connection.execute("SELECT MIN(round) FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued')",
1196
+ (session["id"],)).fetchone()[0]
1197
+ if active_round is None:
1198
+ active_round = connection.execute("SELECT COALESCE(MAX(round),1) FROM session_requests WHERE session_id=? AND purpose='discuss'",
1199
+ (session["id"],)).fetchone()[0]
1200
+ answered = [row["name"] for row in connection.execute("""SELECT m.name FROM session_requests sr JOIN room_members m ON m.id=sr.member_id
1201
+ WHERE sr.session_id=? AND sr.purpose='discuss' AND sr.round=? AND sr.status='answered' ORDER BY sr.position,sr.id""",
1202
+ (session["id"], active_round))]
1203
+ items.extend({"name": name, "state": "done"} for name in answered)
1204
+ open_turn = connection.execute("""SELECT m.name FROM session_requests sr JOIN room_members m ON m.id=sr.member_id
1205
+ WHERE sr.session_id=? AND sr.purpose='discuss' AND sr.round=? AND sr.status='open'
1206
+ ORDER BY sr.position,sr.id LIMIT 1""", (session["id"], active_round)).fetchone()
1207
+ if open_turn:
1208
+ items.append({"name": open_turn["name"], "state": "speaking"})
1209
+ queued = connection.execute("""SELECT sr.round,m.name FROM session_requests sr JOIN room_members m ON m.id=sr.member_id
1210
+ WHERE sr.session_id=? AND sr.purpose='discuss' AND sr.status='queued' ORDER BY sr.round,sr.position,sr.id""",
1211
+ (session["id"],)).fetchall()
1212
+ for row in queued:
1213
+ if row["round"] == active_round:
1214
+ items.append({"name": row["name"], "state": "queued"})
1215
+ later = [[row["name"] for row in queued if row["round"] == round_number]
1216
+ for round_number in sorted({row["round"] for row in queued if row["round"] > active_round})]
1217
+ else:
1218
+ target = connection.execute("""SELECT MAX(q.message_id) FROM free_queue q LEFT JOIN member_requests r ON r.message_id=q.message_id
1219
+ AND r.member_id=q.member_id WHERE q.room_id=? AND (r.id IS NULL OR r.status IN ('pending','delivering'))""", (room["id"],)).fetchone()[0] or 0
1220
+ if target:
1221
+ kind = "queue"
1222
+ for row in connection.execute("""SELECT q.member_id,r.status FROM free_queue q LEFT JOIN member_requests r
1223
+ ON r.message_id=q.message_id AND r.member_id=q.member_id WHERE q.message_id=? ORDER BY q.id""", (target,)):
1224
+ if row["member_id"] in by_id:
1225
+ state = "queued" if row["status"] is None else "speaking" if row["status"] in ("pending", "delivering") else "done"
1226
+ items.append({"name": by_id[row["member_id"]]["name"], "state": state})
1227
+ else:
1228
+ kind = "turns"
1229
+ last = room["rounds"][-1] if room["rounds"] else None
1230
+ turn = room["current_turn"]
1231
+ speaking = turn["expert"] if turn and turn["status"] in ("pending", "notified") else None
1232
+ items = [{"name": name, "state": "done"} for name in (last["speakers"] if last and not last["completed"] else []) if name != speaking]
1233
+ if speaking:
1234
+ items.append({"name": speaking, "state": "speaking"})
1235
+ rounds = split_rounds([item["expert"] for item in room["queued_turns"]], {item["name"] for item in items})
1236
+ items += [{"name": name, "state": "queued"} for name in rounds[0]]
1237
+ later = rounds[1:]
1238
+ # The user may still hold the host seat of an old discussion; only AI participants have a place.
1239
+ ordered = [name for name in [room["host"], *ordered, *room["experts"]] if (name in room["experts"] or name == room["host"]) and name != "用户"]
1240
+ listed = {item["name"] for item in items}
1241
+ items += [{"name": name, "state": "idle"} for name in dict.fromkeys(ordered) if name not in listed]
1242
+ movable = "queued" if kind != "default" else "idle"
1243
+ state = json.dumps([kind, target, [[item["name"], item["state"]] for item in items], later, session_plan_state], ensure_ascii=False)
1244
+ return {"kind": kind, "message_id": target, "items": items, "later": later, "movable": [item["name"] for item in items if item["state"] == movable],
1245
+ "default": [member["name"] for member in default_order(connection, room["id"], active)],
1246
+ "revision": hashlib.sha256(state.encode("utf-8")).hexdigest()[:12]}
1247
+
1248
+
1249
+ def split_rounds(names, spoken):
1250
+ """Cut a turn queue into rounds: an expert who already spoke in the round being filled starts the next one."""
1251
+ rounds, seen = [[]], set(spoken)
1252
+ for name in names:
1253
+ if name in seen:
1254
+ rounds.append([])
1255
+ seen = set()
1256
+ rounds[-1].append(name)
1257
+ seen.add(name)
1258
+ return rounds
1259
+
1260
+
1261
+ def reorder_speakers(connection, room, token, payload):
1262
+ """Owner reorders the not-yet-spoken part of the speaking order; who already spoke or speaks now stays put.
1263
+
1264
+ Read the speaking order first and send its revision: a missing revision is refused, a changed one conflicts,
1265
+ and the new order must list exactly the movable members.
1266
+ """
1267
+ require_owner(connection, room["id"], token)
1268
+ current = room["speaking_order"]
1269
+ if payload.get("revision") is None:
1270
+ raise ValueError("调整发言顺序前须先读取最新顺序(speaking-order),并带上其 revision")
1271
+ if payload["revision"] != current["revision"]:
1272
+ raise FileExistsError("发言顺序已变化,请重新读取后再调整")
1273
+ order = payload.get("order")
1274
+ movable = current["movable"]
1275
+ if not isinstance(order, list) or sorted(map(str, order)) != sorted(movable):
1276
+ given = [str(name) for name in order] if isinstance(order, list) else []
1277
+ missing = [name for name in dict.fromkeys(movable) if given.count(name) < movable.count(name)]
1278
+ extra = [name for name in dict.fromkeys(given) if movable.count(name) < given.count(name)]
1279
+ raise ValueError("新顺序须恰好包含尚未发言的成员" + (f";缺少:{'、'.join(missing)}" if missing else "") + (f";多出:{'、'.join(extra)}" if extra else ""))
1280
+ names = {member["name"]: member["id"] for member in room["members"] if member["status"] == "active"}
1281
+ if current["kind"] == "queue":
1282
+ connection.execute(f"DELETE FROM free_queue WHERE message_id=? AND NOT {QUEUE_ASKED.format(row='free_queue')}", (current["message_id"],))
1283
+ for name in order:
1284
+ connection.execute("INSERT INTO free_queue (room_id,message_id,member_id) VALUES (?,?,?)", (room["id"], current["message_id"], names[name]))
1285
+ elif current["kind"] == "turns":
1286
+ from .session_room import current_session
1287
+ session = current_session(connection, room["id"], active_only=True)
1288
+ if session:
1289
+ active_round = connection.execute("SELECT MIN(round) FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued')",
1290
+ (session["id"],)).fetchone()[0]
1291
+ active_round = active_round or 1
1292
+ open_position = connection.execute("SELECT COALESCE(MAX(position),0) FROM session_requests WHERE session_id=? AND purpose='discuss' AND round=? AND status IN ('answered','open')",
1293
+ (session["id"], active_round)).fetchone()[0]
1294
+ rows = connection.execute("SELECT id FROM session_requests WHERE session_id=? AND purpose='discuss' AND round=? AND status='queued'",
1295
+ (session["id"], active_round)).fetchall()
1296
+ connection.execute("UPDATE session_requests SET position=-id WHERE id IN (%s)" % ",".join("?" for _ in rows),
1297
+ [row["id"] for row in rows]) if rows else None
1298
+ for offset, name in enumerate(order, 1):
1299
+ connection.execute("UPDATE session_requests SET position=? WHERE session_id=? AND purpose='discuss' AND round=? AND status='queued' AND member_id=?",
1300
+ (open_position + offset, session["id"], active_round, names[name]))
1301
+ connection.execute("UPDATE session_state SET revision=revision+1 WHERE session_id=?", (session["id"],))
1302
+ else:
1303
+ reorder_turns(connection, room["id"], order)
1304
+ else:
1305
+ connection.execute("INSERT OR REPLACE INTO speaking_orders (room_id,member_ids) VALUES (?,?)",
1306
+ (room["id"], json.dumps([names[name] for name in order])))
1307
+
1308
+
1309
+ def reorder_turns(connection, room_id, order):
1310
+ """Move this round's queued turns into the new order; ids keep the relay order, so each turn's content moves to the id at its new place.
1311
+
1312
+ This round's turns lead the queue, so they are its first rows; later rounds keep theirs.
1313
+ """
1314
+ rows = [dict(row) for row in connection.execute("SELECT * FROM discussion_turns WHERE room_id=? AND status='queued' ORDER BY id LIMIT ?",
1315
+ (room_id, len(order)))]
1316
+ remaining, moved = list(rows), []
1317
+ for name in order:
1318
+ moved.append(remaining.pop(next(index for index, row in enumerate(remaining) if row["expert"] == name)))
1319
+ # Submission ids are unique, so free them before writing them to their new rows.
1320
+ for slot in rows:
1321
+ connection.execute("UPDATE discussion_turns SET submission_id=submission_id||':moving:'||id WHERE id=?", (slot["id"],))
1322
+ for slot, content in zip(rows, moved):
1323
+ connection.execute("UPDATE discussion_turns SET expert=?,question=?,submission_id=?,created_at=? WHERE id=?",
1324
+ (content["expert"], content["question"], content["submission_id"], content["created_at"], slot["id"]))
1325
+
1326
+
1327
+ def answered_chain(connection, payload, actor):
1328
+ """The chain an answer continues: the newest chain among the requests it completes."""
1329
+ if actor["access"] == "manual":
1330
+ ids = payload.get("request_ids") or [0]
1331
+ marks = ",".join("?" * len(ids))
1332
+ row = connection.execute(f"SELECT MAX(chain_id) FROM member_requests WHERE id IN ({marks})", ids).fetchone()
1333
+ else:
1334
+ row = connection.execute("SELECT MAX(chain_id) FROM member_requests WHERE execution_id=?", (payload["execution_id"],)).fetchone()
1335
+ return row[0] or 0
1336
+
1337
+
1338
+ def after_free_message(connection, room_id, message_id, actor, payload):
1339
+ """Create requests for the owner's message, or close what the member's answer covers."""
1340
+ now = int(time.time())
1341
+ if actor == "用户":
1342
+ from .session_room import create_host_request, current_session
1343
+ session = current_session(connection, room_id, active_only=True)
1344
+ if session and session["status"] == "active" and payload.get("to") is None:
1345
+ create_host_request(connection, session["id"],
1346
+ f"用户留言 #{message_id}:请处理并决定是否安排专家。",
1347
+ {"kind": "user_message", "message_id": message_id, "key": f"message-{message_id}"})
1348
+ connection.execute("UPDATE session_state SET held_since=?,revision=revision+1 WHERE session_id=?",
1349
+ (message_id, session["id"]))
1350
+ return
1351
+ pairs = recipients(connection, room_id, payload)
1352
+ if payload.get("sequential") is True and payload.get("to") is not None:
1353
+ queue_in_turn(connection, room_id, message_id, [member_id for member_id, _ in pairs])
1354
+ return
1355
+ for member_id, purpose in pairs:
1356
+ insert_request(connection, room_id, member_id, message_id, message_id, purpose, "user")
1357
+ return
1358
+ if actor.get("manual_source") == "web":
1359
+ for request_id in payload.get("request_ids", []):
1360
+ connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE id=?", (message_id, request_id))
1361
+ settle_batches(connection, room_id)
1362
+ return
1363
+ chain_id = answered_chain(connection, payload, actor)
1364
+ if actor["access"] == "manual":
1365
+ for request_id in payload.get("request_ids", []):
1366
+ connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE id=?", (message_id, request_id))
1367
+ else:
1368
+ execution_id = payload["execution_id"]
1369
+ connection.execute("UPDATE member_executions SET status='completed',finished_at=?,result=? WHERE id=?",
1370
+ (now, f"message:{message_id}", execution_id))
1371
+ connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE execution_id=? AND status='delivering'",
1372
+ (message_id, execution_id))
1373
+ connection.execute("UPDATE room_members SET read_until=MAX(read_until,?) WHERE id=?", (message_id, actor["id"]))
1374
+ if actor["role"] == "host" and payload.get("to"):
1375
+ dispatch(connection, room_id, actor, message_id, payload["to"], chain_id, payload.get("handoff") is True or bool(payload.get("next_review")))
1376
+ settle_batches(connection, room_id)
1377
+
1378
+
1379
+ def discussion_host_handles(connection, room):
1380
+ """A running discussion already wakes its host for every user message, so a question to the host needs no request of its own."""
1381
+ return room["phase"] not in ("paused", "concluded") and bool(connection.execute(
1382
+ "SELECT 1 FROM discussion_runtime WHERE room_id=? AND status='running'", (room["id"],)).fetchone())
1383
+
1384
+
1385
+ def checked_asks(connection, room, payload):
1386
+ """Validate the user's direct questions to members of a discussion before the message is stored."""
1387
+ names = payload.get("to")
1388
+ if names is None:
1389
+ return []
1390
+ return named_members(active_members(connection, room["id"]), names)
1391
+
1392
+
1393
+ def ask_members(connection, room, message_id, member_ids):
1394
+ """Queue one 'ask' request per named member, outside the discussion's turns, rounds and limits."""
1395
+ host_busy = discussion_host_handles(connection, room)
1396
+ for member_id in member_ids:
1397
+ row = connection.execute("SELECT name FROM room_members WHERE id=?", (member_id,)).fetchone()
1398
+ if host_busy and row["name"] == room["host"]:
1399
+ continue
1400
+ insert_request(connection, room["id"], member_id, message_id, message_id, "ask", "user")
1401
+
1402
+
1403
+ def asks_view(connection, room_id):
1404
+ """Direct questions of a discussion room: recent requests with their member, for status badges beside messages."""
1405
+ names = {row["id"]: row["name"] for row in connection.execute("SELECT id,name FROM room_members WHERE room_id=?", (room_id,))}
1406
+ requests = [{**dict(row), "member": names.get(row["member_id"], "")} for row in connection.execute(
1407
+ """SELECT id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose,created_by,created_at,
1408
+ (SELECT reason FROM request_cancel_reasons c WHERE c.request_id=member_requests.id) AS cancel_reason FROM member_requests
1409
+ WHERE room_id=? ORDER BY id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
1410
+ return {"requests": requests[::-1], "executions": recent_executions(connection, room_id)}
1411
+
1412
+
1413
+ def expire_executions(connection, room_id):
1414
+ """Fail executions whose lease lapsed; their requests stay visible as failed, never silently retried."""
1415
+ now = int(time.time())
1416
+ stale = connection.execute(
1417
+ "SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started') AND lease_until<=?", (room_id, now)).fetchall()
1418
+ for row in stale:
1419
+ finish_execution(connection, row["id"], "failed", "执行租约到期,接入程序未续租", "failed")
1420
+ if stale:
1421
+ settle_batches(connection, room_id)
1422
+
1423
+
1424
+ def record_cancel_reasons(connection, where, params, reason):
1425
+ """Remember why requests are about to be cancelled; call before the status change selects them."""
1426
+ connection.execute(f"INSERT OR REPLACE INTO request_cancel_reasons (request_id,reason) SELECT id,? FROM member_requests WHERE {where}", (reason, *params))
1427
+
1428
+
1429
+ def finish_execution(connection, execution_id, status, result, request_status, cancel_reason=""):
1430
+ """End one execution and move its delivered requests in the same transaction."""
1431
+ if request_status == "cancelled" and cancel_reason:
1432
+ record_cancel_reasons(connection, "execution_id=? AND status='delivering'", (execution_id,), cancel_reason)
1433
+ session_requests = connection.execute("""SELECT r.id FROM member_requests r JOIN session_requests sr
1434
+ ON sr.member_request_id=r.id WHERE r.execution_id=? AND sr.purpose='discuss' AND sr.status='open'""",
1435
+ (execution_id,)).fetchall()
1436
+ connection.execute("UPDATE member_executions SET status=?,finished_at=?,result=? WHERE id=? AND status IN ('dispatched','started')",
1437
+ (status, int(time.time()), result[:500], execution_id))
1438
+ connection.execute("UPDATE member_requests SET status=?,execution_id=CASE WHEN ?='pending' THEN NULL ELSE execution_id END WHERE execution_id=? AND status='delivering'",
1439
+ (request_status, request_status, execution_id))
1440
+ if status == "failed" and request_status == "failed":
1441
+ from .session_room import fail_session_request
1442
+ for row in session_requests:
1443
+ fail_session_request(connection, row["id"], result)
1444
+
1445
+
1446
+ def open_route_messages(connection, member_id, pending_only=False):
1447
+ """(message, purpose) of host requests still open, in order; they need a new host if this one leaves."""
1448
+ states = "'pending'" if pending_only else "'pending','delivering'"
1449
+ return [(row[0], row[1]) for row in connection.execute(
1450
+ f"""SELECT message_id,purpose FROM member_requests WHERE member_id=? AND purpose IN ('route','group')
1451
+ AND status IN ({states}) ORDER BY message_id""", (member_id,))]
1452
+
1453
+
1454
+ def hand_over_routes(connection, room_id, routes, departed_id):
1455
+ """Ask the current host to route messages left behind by the previous host."""
1456
+ host = connection.execute("SELECT id FROM room_members WHERE room_id=? AND role='host' AND status='active' AND id<>?",
1457
+ (room_id, departed_id or 0)).fetchone()
1458
+ for message_id, purpose in routes if host else []:
1459
+ connection.execute("""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1460
+ VALUES (?,?,?,?,?,'user',?)""", (room_id, host["id"], message_id, message_id, purpose, int(time.time())))
1461
+
1462
+
1463
+ def stop_member_work(connection, member_id, reason, cancel_reason):
1464
+ """Void a member's live execution and every open request, so nothing restarts by itself."""
1465
+ for row in connection.execute("SELECT id FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
1466
+ (member_id,)).fetchall():
1467
+ finish_execution(connection, row["id"], "cancelled", reason, "cancelled", cancel_reason)
1468
+ record_cancel_reasons(connection, "member_id=? AND status='pending'", (member_id,), cancel_reason)
1469
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE member_id=? AND status='pending'", (member_id,))
1470
+ from .session_room import advance_session, create_host_request, current_session
1471
+
1472
+ member = connection.execute("SELECT room_id,name FROM room_members WHERE id=?", (member_id,)).fetchone()
1473
+ session = current_session(connection, member["room_id"], active_only=True) if member else None
1474
+ if not session:
1475
+ return
1476
+ plans = connection.execute("""SELECT id,member_request_id FROM session_requests
1477
+ WHERE session_id=? AND member_id=? AND purpose='discuss' AND status='open'""",
1478
+ (session["id"], member_id)).fetchall()
1479
+ for plan in plans:
1480
+ connection.execute("UPDATE session_requests SET status='cancelled' WHERE id=?", (plan["id"],))
1481
+ if not plans:
1482
+ return
1483
+ connection.execute("UPDATE session_state SET revision=revision+1 WHERE session_id=?", (session["id"],))
1484
+ if advance_session(connection, session["id"]):
1485
+ return
1486
+ request_id = plans[0]["member_request_id"]
1487
+ create_host_request(connection, session["id"],
1488
+ f"专家 {member['name']} 的讨论发言已被打断,请检查余下安排并决定如何继续。",
1489
+ {"kind": "request_failed", "request_id": request_id, "key": f"interrupted-{request_id or plans[0]['id']}"})
1490
+
1491
+
1492
+ def stop_room_work(connection, room_id, reason, cancel_reason):
1493
+ """Void every live execution and open request of a room, e.g. when it is archived."""
1494
+ for row in connection.execute("SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')",
1495
+ (room_id,)).fetchall():
1496
+ finish_execution(connection, row["id"], "cancelled", reason, "cancelled", cancel_reason)
1497
+ record_cancel_reasons(connection, "room_id=? AND status='pending'", (room_id,), cancel_reason)
1498
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND status='pending'", (room_id,))
1499
+ settle_batches(connection, room_id)
1500
+
1501
+
1502
+ def inbox(connection, room_id, token):
1503
+ """List what the runner should deliver or reconcile; owner credential only."""
1504
+ require_owner(connection, room_id, token)
1505
+ begin_write(connection)
1506
+ enforce_session_limits(connection, room_id)
1507
+ expire_executions(connection, room_id)
1508
+ release_recommendations(connection, room_id)
1509
+ archived = connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0]
1510
+ members, observers = [], []
1511
+ # Manual and online members are never delivered to; the runner only reads them so smart scheduling can route to them too.
1512
+ for row in connection.execute(f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER} ORDER BY id", (room_id,)):
1513
+ pending = [dict(item) for item in connection.execute("""SELECT r.id,r.message_id,r.purpose,
1514
+ sr.id AS session_request_id,sr.session_id,sr.round,sr.position,sr.read_until,sr.question AS source_question,
1515
+ t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id,
1516
+ (SELECT action FROM group_routes WHERE message_id=r.message_id) AS group_action
1517
+ FROM member_requests r LEFT JOIN session_requests sr ON sr.member_request_id=r.id
1518
+ LEFT JOIN task_message_sources t ON t.session_request_id=sr.id
1519
+ WHERE r.member_id=? AND r.status='pending' ORDER BY r.id""", (row["id"],))]
1520
+ manual_source = connection.execute("SELECT source FROM member_manual_sources WHERE member_id=?", (row["id"],)).fetchone()
1521
+ member_view = {key: row[key] for key in MEMBER_FIELDS}
1522
+ member_view["manual_source"] = manual_source[0] if manual_source else ""
1523
+ member_view["review_capability"] = review_capability(connection, room_id, row["id"], token)
1524
+ pending = [{**request, **review_request_context(connection, request)} for request in pending]
1525
+ (members if row["access"] == "runner" else observers).append({**member_view, "pending": pending})
1526
+ executions = [{**public_execution(row), "member": row["name"], "retry": execution_retry(connection, row["id"])} for row in connection.execute(
1527
+ """SELECT member_executions.*,room_members.name FROM member_executions JOIN room_members ON room_members.id=member_id
1528
+ WHERE member_executions.room_id=? AND member_executions.status IN ('dispatched','started') ORDER BY member_executions.id""", (room_id,))]
1529
+ return {"room_id": room_id, "archived": bool(archived), "members": members, "observers": observers, "executions": executions}
1530
+
1531
+
1532
+ def host_route_request(connection, message_id):
1533
+ """The host's request for one unnamed owner message, if the message was routed."""
1534
+ return connection.execute("SELECT * FROM member_requests WHERE message_id=? AND purpose='route'", (message_id,)).fetchone()
1535
+
1536
+
1537
+ def recommend_member(connection, room_id, token, payload):
1538
+ """Smart scheduling suggests another member for an unnamed message; the host keeps it until the user adopts."""
1539
+ require_owner(connection, room_id, token)
1540
+ begin_write(connection)
1541
+ confidence = payload.get("confidence")
1542
+ if payload.get("provider") not in SCHEDULER_PROVIDERS or type(confidence) not in (int, float) or not 0 <= confidence <= 1:
1543
+ raise ValueError("须提供智能调度供应商 provider 与 0–1 的置信度 confidence")
1544
+ message_id = payload.get("message_id")
1545
+ route = host_route_request(connection, message_id) if type(message_id) is int else None
1546
+ if not route or route["room_id"] != room_id:
1547
+ raise LookupError("只能为交给主持人的未点名消息给出推荐")
1548
+ target = connection.execute(f"""SELECT * FROM room_members WHERE room_id=? AND id=? AND status='active'
1549
+ AND {REGISTERED_MEMBER} AND id<>?""", (room_id, payload.get("member_id"), route["member_id"])).fetchone()
1550
+ if not target:
1551
+ raise LookupError("推荐对象须为在场的其他成员")
1552
+ now = int(time.time())
1553
+ connection.execute("""INSERT OR IGNORE INTO member_recommendations (message_id,room_id,member_id,provider,confidence,created_at,expires_at)
1554
+ VALUES (?,?,?,?,?,?,?)""", (message_id, room_id, target["id"], payload["provider"], float(confidence), now, now + RECOMMEND_SECONDS))
1555
+ return dict(connection.execute("SELECT * FROM member_recommendations WHERE message_id=?", (message_id,)).fetchone())
1556
+
1557
+
1558
+ def release_recommendations(connection, room_id):
1559
+ """Ask each adopted-later member once the host's request for that message has ended in any way."""
1560
+ for row in connection.execute("""SELECT rec.* FROM member_recommendations rec JOIN member_requests r ON r.message_id=rec.message_id AND r.purpose='route'
1561
+ WHERE rec.room_id=? AND rec.status='waiting' AND r.status IN ('completed','cancelled','failed')""", (room_id,)).fetchall():
1562
+ connection.execute("UPDATE member_recommendations SET status='adopted' WHERE message_id=?", (row["message_id"],))
1563
+ if connection.execute("SELECT 1 FROM room_members WHERE id=? AND status='active'", (row["member_id"],)).fetchone():
1564
+ connection.execute("""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1565
+ VALUES (?,?,?,?,'ask','user',?)""", (room_id, row["member_id"], row["message_id"], row["message_id"], int(time.time())))
1566
+
1567
+
1568
+ def group_route_plan(connection, room_id, token, message_id):
1569
+ """Read the current group, eligible members, order and revision before arranging everyone's requests."""
1570
+ require_owner(connection, room_id, token)
1571
+ group = connection.execute("""SELECT id,message_id,status FROM member_requests
1572
+ WHERE room_id=? AND message_id=? AND purpose='group' ORDER BY id DESC LIMIT 1""", (room_id, message_id)).fetchone()
1573
+ previous = connection.execute("SELECT action,request_id,message_id FROM group_routes WHERE room_id=? AND message_id=?",
1574
+ (room_id, message_id)).fetchone()
1575
+ if not group and not previous:
1576
+ raise LookupError("这条消息没有全体待安排请求")
1577
+ state = connection.execute(GROUP_STATE_SQL, (room_id,)).fetchone()["state"]
1578
+ snapshot = json.loads(state)
1579
+ members = [member for member in snapshot["members"] if member["status"] == "active" and member["registered"]]
1580
+ rank = {member_id: index for index, member_id in enumerate(json.loads(snapshot["order"]))}
1581
+ members.sort(key=lambda member: (member["id"] not in rank, rank.get(member["id"], 0), member["role"] != "host", member["id"]))
1582
+ return {"message_id": message_id, "request": dict(group) if group else None, "members": members,
1583
+ "title": snapshot["title"], "goal": snapshot["goal"],
1584
+ "latest_id": snapshot["latest_id"], "revision": hashlib.sha256(state.encode("utf-8")).hexdigest(),
1585
+ "result": dict(previous) if previous else None}
1586
+
1587
+
1588
+ def route_group(connection, room_id, group, payload):
1589
+ """Arrange a pending group atomically; only the single-object handback to its host needs no roster revision."""
1590
+ action = payload["action"]
1591
+ if action not in ("all", "sequential", "host"):
1592
+ raise ValueError("请全体成员回应的消息只能选 action=all、sequential 或 host")
1593
+ if group["status"] != "pending":
1594
+ raise FileExistsError("这条消息已不再等待安排")
1595
+ if action != "host":
1596
+ if not payload.get("revision"):
1597
+ raise ValueError("安排全体前须先读取 message group-plan,并带上其 revision")
1598
+ state = connection.execute(GROUP_STATE_SQL, (room_id,)).fetchone()["state"]
1599
+ if payload["revision"] != hashlib.sha256(state.encode("utf-8")).hexdigest():
1600
+ raise FileExistsError("成员、顺序或消息已变化,请重新读取全体安排状态")
1601
+ if action == "host":
1602
+ connection.execute("UPDATE member_requests SET purpose='route' WHERE id=?", (group["id"],))
1603
+ elif action == "sequential":
1604
+ connection.execute("DELETE FROM member_requests WHERE id=?", (group["id"],))
1605
+ members = connection.execute(f"SELECT id FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER}", (room_id,))
1606
+ queue_in_turn(connection, room_id, group["message_id"], [row["id"] for row in members])
1607
+ else:
1608
+ connection.execute("UPDATE member_requests SET purpose='all' WHERE id=?", (group["id"],))
1609
+ connection.execute(f"""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1610
+ SELECT room_id,id,?,?,'all','user',? FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER} ORDER BY id""",
1611
+ (group["message_id"], group["chain_id"], int(time.time()), room_id))
1612
+ connection.execute("INSERT INTO group_routes (message_id,room_id,request_id,action) VALUES (?,?,?,?)",
1613
+ (group["message_id"], room_id, group["id"], action))
1614
+ return {"action": action, "request_id": group["id"], "message_id": group["message_id"]}
1615
+
1616
+
1617
+ def route_wide(connection, room_id, message_id, payload):
1618
+ """Smart scheduling answers an unnamed message with everyone (each member once, as if the user named them all) or no one.
1619
+
1620
+ A message naming everyone (a group request) is answered by all at once or, with action sequential, one after another.
1621
+ Only a host request that has not started changes; a started host already handles the message its own way.
1622
+ """
1623
+ action = payload["action"]
1624
+ previous = connection.execute("SELECT action,request_id,message_id FROM group_routes WHERE room_id=? AND message_id=?",
1625
+ (room_id, message_id)).fetchone()
1626
+ if previous:
1627
+ if previous["action"] != action:
1628
+ raise FileExistsError("这条全体消息已经安排,不能改用其他动作")
1629
+ return dict(previous)
1630
+ group = connection.execute("""SELECT * FROM member_requests WHERE room_id=? AND message_id=? AND purpose='group'
1631
+ ORDER BY id DESC LIMIT 1""", (room_id, message_id)).fetchone()
1632
+ if group:
1633
+ return route_group(connection, room_id, group, payload)
1634
+ if action in ("sequential", "host"):
1635
+ raise ValueError("只有请全体成员回应的消息可以依次回答或交回主持人")
1636
+ route = host_route_request(connection, message_id)
1637
+ if not route or route["room_id"] != room_id:
1638
+ raise LookupError("只能处理交给主持人的未点名消息")
1639
+ if route["status"] != "pending":
1640
+ raise FileExistsError("主持人已开始处理这条消息,不再改派")
1641
+ if action == "none":
1642
+ record_cancel_reasons(connection, "id=?", (route["id"],), "no_reply")
1643
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE id=?", (route["id"],))
1644
+ else:
1645
+ # The host keeps its row (one request per message and member) and now answers its own share, without dispatching.
1646
+ connection.execute("UPDATE member_requests SET purpose='all' WHERE id=?", (route["id"],))
1647
+ connection.execute(f"""INSERT OR IGNORE INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at)
1648
+ SELECT room_id,id,?,?,'all','user',? FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER} ORDER BY id""",
1649
+ (message_id, message_id, int(time.time()), room_id))
1650
+ requests = connection.execute("SELECT * FROM member_requests WHERE message_id=? ORDER BY id", (message_id,)).fetchall()
1651
+ return {"action": action, "requests": [dict(row) for row in requests]}
1652
+
1653
+
1654
+ def adopt_recommendation(connection, room_id, token, message_id, payload):
1655
+ """The user adopts a recommendation before it expires: interrupt the host now, or ask the member after the host.
1656
+
1657
+ Smart scheduling also sends action all or none here to have everyone or no one answer an unnamed message.
1658
+ """
1659
+ require_owner(connection, room_id, token)
1660
+ begin_write(connection)
1661
+ if payload.get("action") in ("all", "none", "sequential", "host"):
1662
+ return route_wide(connection, room_id, message_id, payload)
1663
+ if payload.get("action") != "adopt" or payload.get("mode") not in ("interrupt", "after"):
1664
+ raise ValueError("采纳须为 action=adopt,mode 为 interrupt 或 after;全体、依次或无需回应为 action=all、sequential 或 none")
1665
+ row = connection.execute("SELECT * FROM member_recommendations WHERE room_id=? AND message_id=?", (room_id, message_id)).fetchone()
1666
+ if not row:
1667
+ raise LookupError("这条消息没有智能调度推荐")
1668
+ if row["status"] != "open":
1669
+ return {"recommendation": dict(row), "duplicate": True}
1670
+ if int(time.time()) > row["expires_at"] + RECOMMEND_GRACE_SECONDS:
1671
+ raise FileExistsError("推荐已过期,可直接 @ 该成员")
1672
+ if not connection.execute("SELECT 1 FROM room_members WHERE id=? AND status='active'", (row["member_id"],)).fetchone():
1673
+ raise FileExistsError("推荐的成员已离开")
1674
+ route = host_route_request(connection, message_id)
1675
+ mode = payload["mode"]
1676
+ if mode == "interrupt" and route["status"] == "delivering":
1677
+ # The host's execution may carry other messages too; stopping it voids that whole execution.
1678
+ finish_execution(connection, route["execution_id"], "cancelled", "智能调度改派,改由其他成员回答", "cancelled", "rerouted")
1679
+ elif mode == "interrupt" and route["status"] == "pending":
1680
+ record_cancel_reasons(connection, "id=?", (route["id"],), "rerouted")
1681
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE id=?", (route["id"],))
1682
+ connection.execute("UPDATE member_recommendations SET status='waiting',mode=? WHERE message_id=?", (mode, message_id))
1683
+ release_recommendations(connection, room_id)
1684
+ settle_batches(connection, room_id)
1685
+ return {"recommendation": dict(connection.execute("SELECT * FROM member_recommendations WHERE message_id=?", (message_id,)).fetchone()),
1686
+ "duplicate": False}
1687
+
1688
+
1689
+ def recent_recommendations(connection, room_id, now):
1690
+ """Recommendations shown beside their messages, with seconds left to adopt an open one."""
1691
+ return [{**dict(row), "expires_in": max(0, row["expires_at"] - now)} for row in connection.execute(
1692
+ """SELECT rec.*,m.name AS member FROM member_recommendations rec JOIN room_members m ON m.id=rec.member_id
1693
+ WHERE rec.room_id=? ORDER BY rec.message_id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
1694
+
1695
+
1696
+ def reserve_execution(connection, room_id, token, payload):
1697
+ """Bundle a member's open requests into one execution; a retried client_id returns the same one."""
1698
+ require_owner(connection, room_id, token)
1699
+ begin_write(connection)
1700
+ if enforce_session_limits(connection, room_id):
1701
+ connection.commit()
1702
+ client_id = str(payload.get("client_id", ""))
1703
+ if not 8 <= len(client_id) <= 100:
1704
+ raise ValueError("client_id 须为 8–100 字符的本地投递编号")
1705
+ previous = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND client_id=?", (room_id, client_id)).fetchone()
1706
+ if previous:
1707
+ return execution_detail(connection, previous)
1708
+ expire_executions(connection, room_id)
1709
+ if connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0]:
1710
+ raise FileExistsError("房间已存档,不再投递")
1711
+ member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND id=? AND status='active' AND access='runner'",
1712
+ (room_id, payload.get("member_id"))).fetchone()
1713
+ if not member:
1714
+ raise LookupError("成员不存在、已离开或为手动接入")
1715
+ if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
1716
+ (member["id"],)).fetchone():
1717
+ raise FileExistsError("该成员已有进行中的执行;同一会话不并发续接")
1718
+ # A group request waits for the runner to choose how everyone answers; it is never delivered itself.
1719
+ pending = connection.execute("""SELECT id,purpose,EXISTS(SELECT 1 FROM review_plans WHERE review_batch_id=member_requests.message_id AND reviewer_id=member_requests.member_id) AS review FROM member_requests
1720
+ WHERE member_id=? AND status='pending' AND purpose<>'group' ORDER BY id""", (member["id"],)).fetchall()
1721
+ session_purpose = next((row["purpose"] for row in pending if row["purpose"] == "discuss"), None)
1722
+ if not pending:
1723
+ raise FileExistsError("该成员没有待投递的请求")
1724
+ if session_purpose:
1725
+ request_filter = "purpose=?"
1726
+ request_values = (session_purpose,)
1727
+ elif pending[0]["review"]:
1728
+ request_filter, request_values = "id=?", (pending[0]["id"],)
1729
+ else:
1730
+ request_filter = "purpose<>'group' AND NOT EXISTS(SELECT 1 FROM review_plans WHERE review_batch_id=member_requests.message_id AND reviewer_id=member_requests.member_id)"
1731
+ request_values = ()
1732
+ now = int(time.time())
1733
+ cursor = connection.execute("""INSERT INTO member_executions (room_id,member_id,client_id,lease_until,created_at,cwd)
1734
+ VALUES (?,?,?,?,?,?)""", (room_id, member["id"], client_id, now + LEASE_SECONDS, now, str(payload.get("cwd") or "")[:MAX_PATH_LENGTH]))
1735
+ connection.execute(f"UPDATE member_requests SET status='delivering',execution_id=? WHERE member_id=? AND status='pending' AND {request_filter}",
1736
+ (cursor.lastrowid, member["id"], *request_values))
1737
+ return execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (cursor.lastrowid,)).fetchone())
1738
+
1739
+
1740
+ def execution_detail(connection, row):
1741
+ """Describe one execution with the requests it carries and the member's read cursor."""
1742
+ member = connection.execute("SELECT * FROM room_members WHERE id=?", (row["member_id"],)).fetchone()
1743
+ requests = [dict(item) for item in connection.execute("""SELECT r.id,r.message_id,r.status,r.purpose,
1744
+ sr.id AS session_request_id,sr.session_id,sr.round,sr.position,sr.read_until,sr.question AS source_question,
1745
+ t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id
1746
+ FROM member_requests r LEFT JOIN session_requests sr ON sr.member_request_id=r.id
1747
+ LEFT JOIN task_message_sources t ON t.session_request_id=sr.id
1748
+ WHERE r.execution_id=? ORDER BY r.id""", (row["id"],))]
1749
+ requests = [{**request, **review_request_context(connection, request)} for request in requests]
1750
+ return {**public_execution(row), "member": member["name"], "read_until": member["read_until"], "requests": requests,
1751
+ "rewound_executions": member_rewinds(connection, member["id"]), "retry": execution_retry(connection, row["id"])}
1752
+
1753
+
1754
+ def view_execution(connection, room_id, execution_id, token):
1755
+ """Let the owner or the executing member read one execution."""
1756
+ row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
1757
+ if not row:
1758
+ raise LookupError("执行不存在")
1759
+ try:
1760
+ require_owner(connection, room_id, token)
1761
+ except PermissionError:
1762
+ member = require_member(connection, room_id, token)
1763
+ if member["id"] != row["member_id"]:
1764
+ raise
1765
+ return execution_detail(connection, row)
1766
+
1767
+
1768
+ def changed_files(payload):
1769
+ """Validate the runner's observed file list; paths are relative to the execution's cwd."""
1770
+ files = payload.get("changes")
1771
+ if (not isinstance(files, list) or len(files) > MAX_CHANGED_FILES
1772
+ or any(not isinstance(item, str) or not item or len(item) > MAX_PATH_LENGTH for item in files)):
1773
+ raise ValueError(f"changes 须为最多 {MAX_CHANGED_FILES} 个相对路径")
1774
+ return sorted(set(files))
1775
+
1776
+
1777
+ def denied_actions(payload):
1778
+ """Validate the operations a member's software refused: the tool, what it tried, and the rule that would allow it."""
1779
+ denials = payload.get("denials")
1780
+ def valid(item):
1781
+ return (isinstance(item, dict) and isinstance(item.get("tool"), str) and 0 < len(item["tool"]) <= 40
1782
+ and all(isinstance(item.get(key, ""), str) and len(item.get(key, "")) <= MAX_DENIAL_FIELD for key in ("detail", "rule")))
1783
+ if not isinstance(denials, list) or not 0 < len(denials) <= MAX_DENIALS or not all(map(valid, denials)):
1784
+ raise ValueError(f"denials 须为 1–{MAX_DENIALS} 条 {{tool, detail, rule}}")
1785
+ return [{key: item.get(key, "") for key in ("tool", "detail", "rule")} for item in denials]
1786
+
1787
+
1788
+ def renewed_activity(payload, row, now):
1789
+ """Validate the runner's reported phase; its output time is kept within the execution, since the runner's clock may differ."""
1790
+ activity, activity_at = payload.get("activity"), payload.get("activity_at")
1791
+ if activity not in ACTIVITY_PHASES:
1792
+ raise ValueError(f"activity 须为 {'、'.join(item for item in ACTIVITY_PHASES if item)} 或空")
1793
+ if type(activity_at) is not int:
1794
+ raise ValueError("activity_at 须为秒级时间戳")
1795
+ return activity, min(max(activity_at, row["created_at"]), now)
1796
+
1797
+
1798
+ def renewed_notes(payload):
1799
+ """Validate progress notes carried by a renewal; a repeated sequence number is the same note resent."""
1800
+ notes = payload.get("notes", [])
1801
+ if (not isinstance(notes, list) or len(notes) > MAX_NOTES_PER_RENEW or any(
1802
+ not isinstance(note, dict) or type(note.get("seq")) is not int or not 1 <= note["seq"] <= MAX_EXECUTION_NOTES
1803
+ or not isinstance(note.get("text"), str) or not 0 < len(note["text"]) <= MAX_NOTE_LENGTH for note in notes)):
1804
+ raise ValueError(f"notes 须为最多 {MAX_NOTES_PER_RENEW} 条 {{seq: 1–{MAX_EXECUTION_NOTES}, text: 1–{MAX_NOTE_LENGTH} 字}}")
1805
+ return notes
1806
+
1807
+
1808
+ def execution_action(connection, room_id, execution_id, token, payload):
1809
+ """Runner-side lifecycle: renew, fail, release undelivered work, or report observed file changes."""
1810
+ begin_write(connection)
1811
+ action = payload.get("action")
1812
+ member = None
1813
+ if action == "fail":
1814
+ try:
1815
+ require_owner(connection, room_id, token)
1816
+ except PermissionError:
1817
+ member = require_member(connection, room_id, token)
1818
+ else:
1819
+ require_owner(connection, room_id, token)
1820
+ if enforce_session_limits(connection, room_id):
1821
+ connection.commit()
1822
+ row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
1823
+ if not row:
1824
+ raise LookupError("执行不存在")
1825
+ if member and member["id"] != row["member_id"]:
1826
+ raise PermissionError("只能报告自己执行的失败")
1827
+ now = int(time.time())
1828
+ if action == "report":
1829
+ # Observed after the process ends, so the execution may already be complete; recorded once.
1830
+ if row["changes"]:
1831
+ raise FileExistsError("本次执行的改动已记录")
1832
+ connection.execute("UPDATE member_executions SET changes=? WHERE id=?", (json.dumps(changed_files(payload), ensure_ascii=False), execution_id))
1833
+ elif action == "denials":
1834
+ # Like file changes, read from the software's output once its process ends; recorded once.
1835
+ saved = connection.execute("INSERT OR IGNORE INTO execution_denials (execution_id,room_id,denials) VALUES (?,?,?)",
1836
+ (execution_id, room_id, json.dumps(denied_actions(payload), ensure_ascii=False)))
1837
+ if not saved.rowcount:
1838
+ raise FileExistsError("本次执行的拒绝记录已记录")
1839
+ elif action == "segments":
1840
+ # The last segments and notes arrive after the member's answer ended the execution; such notes are dated at its end.
1841
+ finished = 0 if row["status"] in ACTIVE else (row["finished_at"] or 1)
1842
+ notes = renewed_notes(payload)
1843
+ save_segments(connection, "free", room_id, execution_id, row["created_at"], finished, payload, optional=bool(notes))
1844
+ connection.executemany("INSERT OR IGNORE INTO execution_notes (execution_id,seq,room_id,text,created_at) VALUES (?,?,?,?,?)",
1845
+ [(execution_id, note["seq"], room_id, note["text"], min(now, finished) if finished else now) for note in notes])
1846
+ elif row["status"] not in ACTIVE:
1847
+ raise FileExistsError("执行已结束")
1848
+ elif action == "renew":
1849
+ # No time limit on one execution: it runs while the runner keeps renewing.
1850
+ if row["lease_until"] <= now:
1851
+ raise FileExistsError("执行租约已到期,不能续租")
1852
+ # Older runners renew without activity; the last reported one is kept.
1853
+ activity, activity_at = renewed_activity(payload, row, now) if "activity" in payload else (row["activity"], row["activity_at"])
1854
+ notes = renewed_notes(payload)
1855
+ connection.execute("UPDATE member_executions SET lease_until=?,activity=?,activity_at=? WHERE id=?",
1856
+ (now + LEASE_SECONDS, activity, activity_at, execution_id))
1857
+ connection.executemany("INSERT OR IGNORE INTO execution_notes (execution_id,seq,room_id,text,created_at) VALUES (?,?,?,?,?)",
1858
+ [(execution_id, note["seq"], room_id, note["text"], now) for note in notes])
1859
+ elif action == "retry_wait":
1860
+ # A manual member's session refused the delivery: the runner keeps the execution and delivers again at retry_at.
1861
+ attempt, retry_at, reason = payload.get("attempt"), payload.get("retry_at"), payload.get("reason")
1862
+ if (type(attempt) is not int or not 1 <= attempt <= MAX_RETRIES or type(retry_at) is not int or retry_at <= 0
1863
+ or not isinstance(reason, str) or not 0 < len(reason) <= MAX_RETRY_REASON):
1864
+ raise ValueError(f"retry_wait 须带 attempt(1–{MAX_RETRIES})、秒级 retry_at 与 reason(最多 {MAX_RETRY_REASON} 字)")
1865
+ connection.execute("""INSERT INTO execution_retries (execution_id,room_id,attempt,retry_at,reason,stopped) VALUES (?,?,?,?,?,0)
1866
+ ON CONFLICT(execution_id) DO UPDATE SET attempt=excluded.attempt,retry_at=excluded.retry_at,reason=excluded.reason,stopped=0""",
1867
+ (execution_id, room_id, attempt, retry_at, reason))
1868
+ elif action == "retry_start":
1869
+ connection.execute("UPDATE execution_retries SET retry_at=0 WHERE execution_id=?", (execution_id,))
1870
+ elif action in ("retry_now", "retry_stop"):
1871
+ # The owner's answer to a waiting retry: deliver now, or stop so the runner fails the execution.
1872
+ change = "retry_at=?" if action == "retry_now" else "stopped=1"
1873
+ updated = connection.execute(f"UPDATE execution_retries SET {change} WHERE execution_id=? AND retry_at>0 AND stopped=0",
1874
+ ((now, execution_id) if action == "retry_now" else (execution_id,)))
1875
+ if not updated.rowcount:
1876
+ raise FileExistsError("本次执行没有在等待自动重试")
1877
+ elif action == "reject_review":
1878
+ request = connection.execute("""SELECT r.id FROM member_requests r JOIN review_plans p ON p.review_batch_id=r.message_id AND p.reviewer_id=r.member_id
1879
+ WHERE r.execution_id=? AND r.status='delivering' AND r.purpose='ask'""", (execution_id,)).fetchall()
1880
+ count = connection.execute("SELECT COUNT(*) FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,)).fetchone()[0]
1881
+ if len(request) != 1 or count != 1 or not isinstance(payload.get("reason"), str) or not payload["reason"].strip():
1882
+ raise ValueError("reject_review 只用于单个评审执行,须说明拒绝原因")
1883
+ finish_execution(connection, execution_id, "cancelled", "评审未投递:" + payload["reason"][:400], "cancelled")
1884
+ settle_batches(connection, room_id)
1885
+ elif action == "fail":
1886
+ finish_execution(connection, execution_id, "failed", str(payload.get("reason") or "执行失败"), "failed")
1887
+ settle_batches(connection, room_id)
1888
+ elif action == "release":
1889
+ # Only for proven non-delivery: the requests return to the queue unchanged.
1890
+ finish_execution(connection, execution_id, "cancelled", str(payload.get("reason") or "未送达"), "pending")
1891
+ else:
1892
+ raise ValueError("action 须为 renew、fail、release、report、segments、retry_wait、retry_start、retry_now 或 retry_stop")
1893
+ return execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (execution_id,)).fetchone())
1894
+
1895
+
1896
+ def owned_member(connection, room_id, member_id, token):
1897
+ """Read one member after proving the owner's credential."""
1898
+ require_owner(connection, room_id, token)
1899
+ begin_write(connection)
1900
+ member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND id=?", (room_id, member_id)).fetchone()
1901
+ if not member or member["status"] == "removed":
1902
+ raise LookupError("成员不存在")
1903
+ return member
1904
+
1905
+
1906
+ def interrupt_member(connection, room_id, member_id, token):
1907
+ """Owner stop: void the live execution and every open request."""
1908
+ owned_member(connection, room_id, member_id, token)
1909
+ stop_member_work(connection, member_id, "用户打断", "user_stop")
1910
+ settle_batches(connection, room_id)
1911
+ return free_view(connection, room_id)
1912
+
1913
+
1914
+ def withdrawals(connection, room_id):
1915
+ """The room's taken-back messages by id, so the page keeps them in place while AI readers skip them."""
1916
+ return [dict(row) for row in connection.execute("""SELECT w.message_id,w.kind FROM message_withdrawals w
1917
+ JOIN messages m ON m.id=w.message_id WHERE m.room_id=? ORDER BY w.message_id""", (room_id,))]
1918
+
1919
+
1920
+ def owner_message(connection, room_id, message_id):
1921
+ """One visible message of the user in a free room without an open discussion, which a retract or rewind may take back."""
1922
+ row = connection.execute("SELECT * FROM messages WHERE room_id=? AND id=?", (room_id, message_id)).fetchone()
1923
+ if not row:
1924
+ raise LookupError("消息不存在")
1925
+ if row["author"] != "用户":
1926
+ raise ValueError("只能撤回或编辑用户自己的消息")
1927
+ if room_mode(connection, room_id) != "free":
1928
+ raise ValueError("只有协作房间的消息可以撤回或编辑")
1929
+ if connection.execute("SELECT 1 FROM room_directory WHERE room_id=? AND archived=1", (room_id,)).fetchone():
1930
+ raise ValueError("房间已存档;恢复后才能撤回或编辑")
1931
+ # A discussion's host reads the user's messages itself, with no request that shows whether it began.
1932
+ if connection.execute("SELECT 1 FROM discussion_sessions WHERE room_id=? AND (status IN ('active','paused') OR started_message_id>=?)",
1933
+ (room_id, message_id)).fetchone():
1934
+ raise FileExistsError("讨论进行中,或这条消息之后开启过讨论,不能撤回或编辑")
1935
+ return row
1936
+
1937
+
1938
+ def retract_message(connection, room_id, message_id, token):
1939
+ """Owner takes back a message no member began to handle: its queued requests end and AI readers no longer see it.
1940
+
1941
+ Bound to one known message, so it takes no revision; a message any member started, answered or failed is refused.
1942
+ A member working on an earlier message may still have read it, which the room cannot know.
1943
+
1944
+ Returns:
1945
+ `{"message_id", "text", "duplicate"}`; the text lets the page put it back in the input for editing.
1946
+ """
1947
+ require_owner(connection, room_id, token)
1948
+ begin_write(connection)
1949
+ message = owner_message(connection, room_id, message_id)
1950
+ if connection.execute("SELECT 1 FROM message_withdrawals WHERE message_id=?", (message_id,)).fetchone():
1951
+ return {"message_id": message_id, "text": message["text"], "duplicate": True}
1952
+ if connection.execute("SELECT 1 FROM member_requests WHERE message_id=? AND status IN ('delivering','completed','failed')", (message_id,)).fetchone():
1953
+ raise FileExistsError("已有成员开始处理这条消息,不能撤回;可以编辑这条消息回退到它之前")
1954
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE message_id=? AND status='pending'", (message_id,))
1955
+ connection.execute("DELETE FROM free_queue WHERE message_id=?", (message_id,))
1956
+ connection.execute("INSERT INTO message_withdrawals (message_id,kind,created_at) VALUES (?,'retracted',?)", (message_id, int(time.time())))
1957
+ settle_batches(connection, room_id)
1958
+ return {"message_id": message_id, "text": message["text"], "duplicate": False}
1959
+
1960
+
1961
+ # Software whose session the runner can cut before a taken-back execution; an API member rebuilds its context each time.
1962
+ CUTTABLE_ADAPTERS = ("claude", "codex", "codex_cli", "antigravity_cli")
1963
+ # Executions a rewind takes back: any touching a message from the rewind point on, and any still running.
1964
+ REWOUND_EXECUTIONS = """SELECT e.id,e.member_id FROM member_executions e WHERE e.room_id=? AND (e.status IN ('dispatched','started')
1965
+ OR EXISTS(SELECT 1 FROM member_requests r WHERE r.execution_id=e.id AND (r.message_id>=? OR r.answer_id>=?))) ORDER BY e.id"""
1966
+
1967
+
1968
+ def rewind_plan(connection, room_id, message_id):
1969
+ """What rewinding to just before a message takes back, and a revision of the state it was read from.
1970
+
1971
+ Each member reports what happens to its session: `cut` (the runner cuts it before the first taken-back execution),
1972
+ `fresh` (an API member, which rebuilds its context), `unchanged` (no taken-back execution) or `kept` (manual, online or
1973
+ App software whose own window keeps what it saw).
1974
+ """
1975
+ owner_message(connection, room_id, message_id)
1976
+ if connection.execute("SELECT 1 FROM message_withdrawals WHERE message_id=?", (message_id,)).fetchone():
1977
+ raise FileExistsError("这条消息已被撤回或回退")
1978
+ executions = {}
1979
+ for row in connection.execute(REWOUND_EXECUTIONS, (room_id, message_id, message_id)):
1980
+ executions.setdefault(row["member_id"], []).append(row["id"])
1981
+ members = []
1982
+ for row in connection.execute("SELECT id,name,access,adapter FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id", (room_id,)):
1983
+ taken = executions.get(row["id"], [])
1984
+ session = ("kept" if row["access"] != "runner" or row["adapter"] not in (*CUTTABLE_ADAPTERS, "api")
1985
+ else "unchanged" if not taken else "fresh" if row["adapter"] == "api" else "cut")
1986
+ members.append({"id": row["id"], "name": row["name"], "executions": taken, "session": session})
1987
+ count = connection.execute("""SELECT COUNT(*) FROM messages m WHERE m.room_id=? AND m.id>=?
1988
+ AND NOT EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id=m.id)""", (room_id, message_id)).fetchone()[0]
1989
+ latest = connection.execute("SELECT COALESCE(MAX(id),0) FROM messages WHERE room_id=?", (room_id,)).fetchone()[0]
1990
+ state = json.dumps([message_id, latest, count, members])
1991
+ return {"message_id": message_id, "messages": count, "members": members,
1992
+ "revision": hashlib.sha256(state.encode("utf-8")).hexdigest()[:12]}
1993
+
1994
+
1995
+ def rewind_room(connection, room_id, token, payload):
1996
+ """Owner returns the room to just before one of its messages, as editing that message does.
1997
+
1998
+ Read the plan first (`GET rewind?message_id=`) and send its revision: a missing revision is refused and a changed
1999
+ one conflicts. The message and everything after it stay on the page but leave AI reads; running work stops, open
2000
+ requests on them end, members read again from before the message, and each runner member's session is cut before
2001
+ its first taken-back execution when it next works. Files the members changed are not restored.
2002
+ """
2003
+ require_owner(connection, room_id, token)
2004
+ begin_write(connection)
2005
+ message_id = payload.get("message_id")
2006
+ if type(message_id) is not int:
2007
+ raise ValueError("须提供要回退到其之前的消息编号 message_id")
2008
+ if payload.get("revision") is None:
2009
+ raise ValueError("回退前须先读取回退计划(GET rewind?message_id=),并带上其 revision")
2010
+ plan = rewind_plan(connection, room_id, message_id)
2011
+ if payload["revision"] != plan["revision"]:
2012
+ raise FileExistsError("房间已有新的消息或执行,请重新读取回退计划后再确认")
2013
+ now = int(time.time())
2014
+ for row in connection.execute("SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')", (room_id,)).fetchall():
2015
+ finish_execution(connection, row["id"], "cancelled", "用户回退了对话", "cancelled", "user_stop")
2016
+ record_cancel_reasons(connection, "room_id=? AND message_id>=? AND status='pending'", (room_id, message_id), "user_stop")
2017
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND message_id>=? AND status='pending'", (room_id, message_id))
2018
+ connection.execute("DELETE FROM free_queue WHERE room_id=? AND message_id>=?", (room_id, message_id))
2019
+ # Batches of taken-back dispatches never hand back, and a dispatch the round limit held from them is never sent.
2020
+ connection.execute("UPDATE free_batches SET settled=1 WHERE room_id=? AND batch_id>=?", (room_id, message_id))
2021
+ connection.execute("UPDATE free_chain_holds SET message_id=0,host_id=0,names='[]',handoff=0 WHERE room_id=? AND message_id>=?", (room_id, message_id))
2022
+ connection.execute("""INSERT INTO message_withdrawals (message_id,kind,created_at) SELECT id,'rewound',? FROM messages m
2023
+ WHERE m.room_id=? AND m.id>=? AND NOT EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id=m.id)""", (now, room_id, message_id))
2024
+ connection.execute("UPDATE room_members SET read_until=MIN(read_until,?) WHERE room_id=?", (message_id - 1, room_id))
2025
+ cuts = {str(member["id"]): member["executions"] for member in plan["members"] if member["session"] == "cut"}
2026
+ cursor = connection.execute("INSERT INTO room_rewinds (room_id,message_id,cuts,created_at) VALUES (?,?,?,?)",
2027
+ (room_id, message_id, json.dumps(cuts), now))
2028
+ settle_batches(connection, room_id)
2029
+ return {"rewind_id": cursor.lastrowid, **plan}
2030
+
2031
+
2032
+ # The runner checks this many of a member's latest rewinds before each execution.
2033
+ RECENT_REWINDS = 50
2034
+
2035
+
2036
+ def member_rewinds(connection, member_id):
2037
+ """Executions taken back from one member by recent rewinds, oldest first; the runner cuts before the earliest it finds."""
2038
+ taken = set()
2039
+ for row in connection.execute("SELECT cuts FROM room_rewinds WHERE room_id=(SELECT room_id FROM room_members WHERE id=?) ORDER BY id DESC LIMIT ?",
2040
+ (member_id, RECENT_REWINDS)):
2041
+ taken.update(json.loads(row["cuts"]).get(str(member_id), []))
2042
+ return sorted(taken)
2043
+
2044
+
2045
+ def add_member(connection, room_id, token, payload, now):
2046
+ """Owner adds a member while the room keeps running; other members are not interrupted."""
2047
+ require_owner(connection, room_id, token)
2048
+ begin_write(connection)
2049
+ member = member_value(payload)
2050
+ existing = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, member["name"])).fetchone()
2051
+ if existing and existing["status"] == "active" and existing["token_hash"] == token_hash(member["token"]) and all(
2052
+ existing[key] == member[key] for key in ("adapter", "access", "session_mode")):
2053
+ return free_view(connection, room_id)
2054
+ if existing:
2055
+ raise FileExistsError(f"{member['name']} 已是本房间成员;离开的成员请用请回")
2056
+ require_fresh_member_token(connection, room_id, member["token"])
2057
+ insert_member(connection, room_id, member, now)
2058
+ queue_invited_expert(connection, room_id, member["name"], now)
2059
+ sync_participants(connection, room_id)
2060
+ return free_view(connection, room_id)
2061
+
2062
+
2063
+ def discussion_roster(connection, room_id):
2064
+ """Return a discussion's host, active experts and phase; away experts keep only their member row."""
2065
+ row = connection.execute("SELECT host,experts,phase FROM topic_settings WHERE room_id=?", (room_id,)).fetchone()
2066
+ return row["host"], json.loads(row["experts"]), row["phase"]
2067
+
2068
+
2069
+ def save_discussion_experts(connection, room_id, experts):
2070
+ """Write the active roster; additions preserve its plan, other changes ask the host to re-plan."""
2071
+ connection.execute("UPDATE topic_settings SET experts=? WHERE room_id=?", (json.dumps(experts, ensure_ascii=False), room_id))
2072
+
2073
+
2074
+ def queue_invited_expert(connection, room_id, name, now):
2075
+ """Queue a new expert at the tail of an existing live plan, without changing the current speaker or hold.
2076
+
2077
+ A manual expert is queued only once it has registered (the invite alone does not), and only once per invitation.
2078
+ """
2079
+ member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status='active'", (room_id, name)).fetchone()
2080
+ if not member or (member["adapter"] == "manual" and not registered_at(connection, member)):
2081
+ return
2082
+ from .session_room import current_session
2083
+ session = current_session(connection, room_id)
2084
+ if session and session["status"] != "concluded":
2085
+ planned = connection.execute("SELECT 1 FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued') LIMIT 1",
2086
+ (session["id"],)).fetchone()
2087
+ if not planned:
2088
+ return
2089
+ round_number = connection.execute("SELECT MIN(round) FROM session_requests WHERE session_id=? AND purpose='discuss' AND status IN ('open','queued')",
2090
+ (session["id"],)).fetchone()[0]
2091
+ if round_number is None:
2092
+ round_number = 1
2093
+ position = connection.execute("SELECT COALESCE(MAX(position),0)+1 FROM session_requests WHERE session_id=? AND purpose='discuss' AND round=?",
2094
+ (session["id"], round_number)).fetchone()[0]
2095
+ invitation = connection.execute("SELECT COUNT(*) FROM session_requests WHERE session_id=? AND member_id=? AND submission_id LIKE 'invite:%'",
2096
+ (session["id"], member["id"])).fetchone()[0] + 1
2097
+ state = connection.execute("SELECT phase,read_until FROM session_state WHERE session_id=?", (session["id"],)).fetchone()
2098
+ question = ("欢迎加入:请先读取议题,独立给出你的开场观点。" if state and state["phase"] == "initial"
2099
+ else "欢迎加入:请先读取议题和已有回答,给出你的观点。")
2100
+ read_until = state["read_until"] if state and state["phase"] == "initial" and round_number == 1 else None
2101
+ connection.execute("""INSERT OR IGNORE INTO session_requests
2102
+ (session_id,round,position,member_id,purpose,question,status,submission_id,read_until,created_at)
2103
+ VALUES(?,?,?,?,'discuss',?,'queued',?,?,?)""",
2104
+ (session["id"], round_number, position, member["id"], question,
2105
+ f"invite:{member['id']}:{invitation}", read_until,
2106
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())))
2107
+ return
2108
+ connection.execute("""INSERT OR IGNORE INTO discussion_turns (room_id,expert,question,status,submission_id,created_at)
2109
+ SELECT settings.room_id,member.name,
2110
+ CASE WHEN settings.phase='initial' THEN '欢迎加入:请先读取议题,独立给出你的开场观点。'
2111
+ ELSE '欢迎加入:请先读取议题和已有回答,给出你的观点。' END,
2112
+ 'queued','invite:'||member.id,?
2113
+ FROM topic_settings AS settings JOIN room_members AS member ON member.room_id=settings.room_id
2114
+ WHERE settings.room_id=? AND member.name=? AND member.status='active'
2115
+ AND settings.phase NOT IN ('paused','concluded')
2116
+ AND EXISTS (SELECT 1 FROM discussion_turns WHERE room_id=settings.room_id AND status IN ('pending','notified','queued'))""",
2117
+ (now, room_id, name))
2118
+
2119
+
2120
+ def add_discussion_member(connection, room_id, token, payload, now):
2121
+ """Owner invites one expert into a discussion using the room's delivery method."""
2122
+ require_owner(connection, room_id, token)
2123
+ begin_write(connection)
2124
+ member = member_value(payload)
2125
+ _, experts, phase = discussion_roster(connection, room_id)
2126
+ run = connection.execute("SELECT mode FROM discussion_runtime WHERE room_id=?", (room_id,)).fetchone()
2127
+ if not discussion_access_ok(member["access"], "cli", bool(run and run["mode"] == "automatic"), False):
2128
+ raise ValueError("新专家的接入方式须与讨论的推进方式一致")
2129
+ existing = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, member["name"])).fetchone()
2130
+ if existing and existing["status"] == "active" and existing["token_hash"] == token_hash(member["token"]):
2131
+ return
2132
+ if existing:
2133
+ raise FileExistsError(f"{member['name']} 已是本房间成员;离开的成员请用请回")
2134
+ if phase == "concluded":
2135
+ raise ValueError("讨论已收束,不能再邀请专家")
2136
+ if len(experts) >= MAX_ROOM_AGENTS:
2137
+ raise ValueError("房间成员已达上限")
2138
+ require_fresh_member_token(connection, room_id, member["token"])
2139
+ insert_member(connection, room_id, mark_manual(member, bool(run and run["mode"] == "automatic")), now)
2140
+ save_discussion_experts(connection, room_id, {**experts, member["name"]: "cli"})
2141
+ queue_invited_expert(connection, room_id, member["name"], now)
2142
+
2143
+
2144
+ def discussion_member_action(connection, room_id, member_id, token, payload):
2145
+ """Owner sends an expert away (keeping its seat), brings it back with a new credential, or removes it.
2146
+
2147
+ Leaving cancels the expert's open assignments; the host keeps its role and cannot leave, and an
2148
+ leaving cancels its active plan and asks the host to re-plan without pausing the discussion.
2149
+ """
2150
+ member = owned_member(connection, room_id, member_id, token)
2151
+ host, experts, phase = discussion_roster(connection, room_id)
2152
+ action = payload.get("action")
2153
+ if action in ("away", "remove"):
2154
+ if member["name"] == host:
2155
+ raise ValueError("主持人不能离开或移除;请先更换主持人")
2156
+ from .session_room import session_member_change
2157
+ session_member_change(connection, room_id, member, action)
2158
+ connection.execute("UPDATE discussion_turns SET status='cancelled' WHERE room_id=? AND expert=? AND status IN ('pending','notified')",
2159
+ (room_id, member["name"]))
2160
+ connection.execute("UPDATE discussion_turns SET status='skipped' WHERE room_id=? AND expert=? AND status='queued'", (room_id, member["name"]))
2161
+ connection.execute("UPDATE room_members SET status=? WHERE id=?", ("away" if action == "away" else "removed", member_id))
2162
+ experts.pop(member["name"], None)
2163
+ elif action == "active":
2164
+ hashed = token_hash(payload.get("token"))
2165
+ if member["status"] == "active" and hashed and hmac.compare_digest(hashed, member["token_hash"]):
2166
+ return
2167
+ if member["status"] != "away" or not hashed or hmac.compare_digest(hashed, member["token_hash"]):
2168
+ raise ValueError("只有离开的成员可以请回,且须提供新的成员凭证")
2169
+ require_fresh_member_token(connection, room_id, payload.get("token"))
2170
+ connection.execute("UPDATE room_members SET status='active',token_hash=? WHERE id=?", (hashed, member_id))
2171
+ experts[member["name"]] = "online" if member["access"] == "online" else "cli"
2172
+ from .session_room import current_session, session_member_change
2173
+ if current_session(connection, room_id, active_only=True):
2174
+ session_member_change(connection, room_id, member, action)
2175
+ else:
2176
+ queue_invited_expert(connection, room_id, member["name"], int(time.time()))
2177
+ elif action == "adopt":
2178
+ adopt_manual_member(connection, room_id, member, payload)
2179
+ return
2180
+ else:
2181
+ raise ValueError("action 须为 away、active、remove 或 adopt")
2182
+ save_discussion_experts(connection, room_id, experts)
2183
+
2184
+
2185
+ ADOPTABLE_ADAPTERS = ("claude", "codex", "codex_cli", "antigravity", "antigravity_cli")
2186
+
2187
+
2188
+ def adopt_manual_member(connection, room_id, member, payload):
2189
+ """Hand a manual expert to the local service once its CLI reported the session it runs in; the owner's service resumes that session."""
2190
+ reported = connection.execute("SELECT session_id FROM member_sessions WHERE member_id=?", (member["id"],)).fetchone()
2191
+ run = connection.execute("SELECT mode FROM discussion_runtime WHERE room_id=?", (room_id,)).fetchone()
2192
+ if not registered_at(connection, member):
2193
+ raise ValueError("成员尚未注册,不能转为托管")
2194
+ if not reported or reported["session_id"] != payload.get("session_id") or payload.get("adapter") not in ADOPTABLE_ADAPTERS:
2195
+ raise ValueError("成员尚未上报与之相符的会话,不能转为托管")
2196
+ if member["access"] != "manual" or member["status"] != "active" or not (room_mode(connection, room_id) == "free" or (run and run["mode"] == "automatic")):
2197
+ raise ValueError("只有自由协作或全自动讨论中在场的手动专家可以转为托管")
2198
+ connection.execute("UPDATE room_members SET access='runner',adapter=?,session_mode='borrowed' WHERE id=?", (payload["adapter"], member["id"]))
2199
+ connection.execute("DELETE FROM member_sessions WHERE member_id=?", (member["id"],))
2200
+ # A free room's service answers as the member, so it takes over with a credential the owner's side generated.
2201
+ if payload.get("token") is not None:
2202
+ require_fresh_member_token(connection, room_id, payload["token"])
2203
+ connection.execute("UPDATE room_members SET token_hash=? WHERE id=?", (token_hash(payload["token"]), member["id"]))
2204
+
2205
+
2206
+ def require_fresh_member_token(connection, room_id, token):
2207
+ """Prevent owner or another member's credential from being reused for a new identity."""
2208
+ hashed = token_hash(token)
2209
+ if not hashed or connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND token_hash=? UNION ALL SELECT 1 FROM room_modes WHERE room_id=? AND control_hash=?",
2210
+ (room_id, hashed, room_id, hashed)).fetchone():
2211
+ raise ValueError("须提供独立的新成员凭证")
2212
+
2213
+
2214
+ def member_action(connection, room_id, member_id, token, payload):
2215
+ """Owner sends a member away, brings it back with a new credential, or removes it.
2216
+
2217
+ Leaving voids live work at once. Coming back requires a fresh credential, so copies of the
2218
+ old one never revive; the software session is kept by the local runner, not here. The
2219
+ `role` action makes one runner or manual member the AI host, replacing any previous host.
2220
+ """
2221
+ member = owned_member(connection, room_id, member_id, token)
2222
+ manual_source = connection.execute("SELECT source FROM member_manual_sources WHERE member_id=?", (member_id,)).fetchone()
2223
+ is_web_member = bool(manual_source and manual_source["source"] == "web")
2224
+ action = payload.get("action")
2225
+ routed = []
2226
+ if action in ("away", "remove"):
2227
+ from .session_room import pause_session_for_host_change, session_member_change
2228
+ if member["role"] == "host":
2229
+ pause_session_for_host_change(connection, room_id)
2230
+ else:
2231
+ session_member_change(connection, room_id, member, action)
2232
+ # Unnamed messages still waiting on a departing host move to its successor instead of being dropped.
2233
+ routed = open_route_messages(connection, member_id)
2234
+ stop_member_work(connection, member_id, "成员已离开" if action == "away" else "成员已移除",
2235
+ "member_away" if action == "away" else "member_removed")
2236
+ connection.execute("UPDATE room_members SET status=? WHERE id=?", ("away" if action == "away" else "removed", member_id))
2237
+ elif action == "active":
2238
+ hashed = token_hash(payload.get("token"))
2239
+ if member["status"] == "active" and hashed and hmac.compare_digest(hashed, member["token_hash"]):
2240
+ return free_view(connection, room_id)
2241
+ if member["status"] != "away" or not hashed or hmac.compare_digest(hashed, member["token_hash"]):
2242
+ raise ValueError("只有离开的成员可以请回,且须提供新的成员凭证")
2243
+ require_fresh_member_token(connection, room_id, payload.get("token"))
2244
+ connection.execute("UPDATE room_members SET status='active',token_hash=? WHERE id=?", (hashed, member_id))
2245
+ from .session_room import current_session, session_member_change
2246
+ if current_session(connection, room_id, active_only=True):
2247
+ session_member_change(connection, room_id, member, action)
2248
+ else:
2249
+ queue_invited_expert(connection, room_id, member["name"], int(time.time()))
2250
+ elif action == "adopt":
2251
+ adopt_manual_member(connection, room_id, member, payload)
2252
+ elif action == "role":
2253
+ role = payload.get("role")
2254
+ if role not in ("host", "member") or (role == "host" and (member["access"] == "online" or is_web_member)):
2255
+ raise ValueError("role 须为 host 或 member;在线成员不能担任主持人")
2256
+ if role == "member" and member["role"] == "host":
2257
+ raise ValueError("自由房间须由一位 AI 主持;请指定另一位成员担任主持人")
2258
+ if role == "host":
2259
+ from .session_room import pause_session_for_host_change
2260
+ pause_session_for_host_change(connection, room_id)
2261
+ # Unnamed messages the old host has not started move to the new host, which carries the host rules.
2262
+ old_host = connection.execute("SELECT id FROM room_members WHERE room_id=? AND role='host' AND id<>?", (room_id, member_id)).fetchone()
2263
+ if old_host:
2264
+ routed = open_route_messages(connection, old_host["id"], pending_only=True)
2265
+ record_cancel_reasons(connection, "member_id=? AND purpose IN ('route','group') AND status='pending'", (old_host["id"],), "rerouted")
2266
+ connection.execute("UPDATE member_requests SET status='cancelled' WHERE member_id=? AND purpose IN ('route','group') AND status='pending'", (old_host["id"],))
2267
+ connection.execute("UPDATE room_members SET role='member' WHERE room_id=? AND role='host'", (room_id,))
2268
+ connection.execute("UPDATE room_members SET role=? WHERE id=?", (role, member_id))
2269
+ else:
2270
+ raise ValueError("action 须为 away、active、remove、role 或 adopt")
2271
+ settle_batches(connection, room_id)
2272
+ sync_participants(connection, room_id)
2273
+ hand_over_routes(connection, room_id, routed, member_id if action in ("away", "remove") else None)
2274
+ return free_view(connection, room_id)