ai_co_discuss 0.4.66 → 0.4.67

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.
@@ -26,6 +26,7 @@ QUOTA_KEYS = ("hourly_bytes", "total_bytes", "hourly_reads")
26
26
  DEFAULT_QUOTA = {"hourly_bytes": 4 * 1024 * 1024, "total_bytes": 64 * 1024 * 1024, "hourly_reads": 600}
27
27
  MAX_QUOTA = {"hourly_bytes": 1024 ** 3, "total_bytes": 100 * 1024 ** 3, "hourly_reads": 100000}
28
28
  MAX_EXTERNAL_SECONDS = 365 * 86400
29
+ PENDING_SEAT_SECONDS = 7 * 86400
29
30
  MAX_DIRECTORIES = 20
30
31
  MAX_DIRECTORY_LENGTH = 500
31
32
  MAX_MACHINE = 200
@@ -48,7 +49,7 @@ ANSWER_FIELDS = ("text", "text_text", "execution_id", "submission_id", "reply_to
48
49
  ENDED_TEXTS = {"revoked": Text("外部成员已被撤销"), "expired": Text("外部成员已到期"), "left": Text("外部成员已退出")}
49
50
  EXTERNAL_SQL = """SELECT m.id,m.room_id,m.name,m.adapter,m.role,m.status,m.access,m.session_mode,m.read_until,m.token_hash,
50
51
  x.machine,x.machine_label,x.scope,x.directories,x.expires_at,x.hourly_bytes,x.total_bytes,x.hourly_reads,
51
- x.created_at,x.updated_at,x.ended_at,x.end_reason
52
+ x.created_at,x.updated_at,x.ended_at,x.end_reason,x.claimed_at,x.invite_version,x.invite_duration,x.token_hash AS binding_hash
52
53
  FROM external_members x JOIN room_members m ON m.id=x.member_id"""
53
54
 
54
55
 
@@ -113,17 +114,19 @@ def owner_view(connection, row):
113
114
  "status": row["status"], "machine": row["machine"], "machine_label": row["machine_label"], "scope": row["scope"],
114
115
  "directories": json.loads(row["directories"]), "expires_at": row["expires_at"], "quota": quota_of(row),
115
116
  "usage": usage_of(connection, row["id"]), "created_at": row["created_at"], "updated_at": row["updated_at"],
116
- "ended_at": row["ended_at"], "end_reason": row["end_reason"]}
117
+ "ended_at": row["ended_at"], "end_reason": row["end_reason"],
118
+ "claimed_at": row["claimed_at"], "invite_version": row["invite_version"], "duration": row["invite_duration"]}
117
119
 
118
120
 
119
121
  def room_view_field(connection, member_id):
120
122
  """The `external` field of a member in the room view, or None for a local member; no local paths."""
121
- row = connection.execute("SELECT scope,expires_at,machine_label,directories FROM external_members WHERE member_id=?",
123
+ row = connection.execute("SELECT scope,expires_at,machine_label,directories,claimed_at,invite_version FROM external_members WHERE member_id=?",
122
124
  (member_id,)).fetchone()
123
125
  if not row:
124
126
  return None
125
127
  return {"scope": row["scope"], "expires_at": row["expires_at"], "machine_label": row["machine_label"],
126
- "directories": directory_names(json.loads(row["directories"]))}
128
+ "directories": directory_names(json.loads(row["directories"])), "claimed_at": row["claimed_at"],
129
+ "invite_version": row["invite_version"]}
127
130
 
128
131
 
129
132
  def external_row(connection, room_id, member_id):
@@ -148,7 +151,7 @@ def end_member(connection, row, reason):
148
151
 
149
152
  def expire_room(connection, room_id):
150
153
  """End every external member of the room whose time is up; returns whether any ended."""
151
- rows = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.status='active' AND x.ended_at=0 AND x.expires_at<=?",
154
+ rows = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.status='active' AND x.ended_at=0 AND (CASE WHEN x.claimed_at=0 THEN x.created_at+{PENDING_SEAT_SECONDS} ELSE x.expires_at END)<=?",
152
155
  (room_id, int(time.time()))).fetchall()
153
156
  for row in rows:
154
157
  end_member(connection, row, "expired")
@@ -158,7 +161,7 @@ def expire_room(connection, room_id):
158
161
  def roster_revision(connection, room_id):
159
162
  """Version of the room's roster and external settings that a new external member is checked against (red line 1)."""
160
163
  members = connection.execute("SELECT id,name,status,access FROM room_members WHERE room_id=? ORDER BY id", (room_id,)).fetchall()
161
- externals = connection.execute("""SELECT member_id,scope,directories,expires_at,hourly_bytes,total_bytes,hourly_reads,ended_at
164
+ externals = connection.execute("""SELECT member_id,scope,directories,expires_at,hourly_bytes,total_bytes,hourly_reads,ended_at,claimed_at
162
165
  FROM external_members WHERE room_id=? ORDER BY member_id""", (room_id,)).fetchall()
163
166
  state = json.dumps([[list(row) for row in members], [list(row) for row in externals]], ensure_ascii=False)
164
167
  return hashlib.sha256(state.encode()).hexdigest()
@@ -236,8 +239,9 @@ def create_external(connection, room_id, token, payload, now):
236
239
  require_owner(connection, room_id, token)
237
240
  begin_write(connection)
238
241
  expire_room(connection, room_id)
242
+ pending = payload.get("pending") is True
239
243
  name, member_token = payload.get("name"), payload.get("token")
240
- machine = checked_text(payload.get("machine"), MAX_MACHINE, "machine", required=True)
244
+ machine = checked_text(payload.get("machine"), MAX_MACHINE, "machine", required=not pending)
241
245
  hashed = token_hash(member_token)
242
246
  repeated = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.name=? AND x.token_hash=? AND x.machine=? AND m.status='active'",
243
247
  (room_id, name, hashed, machine)).fetchone() if hashed else None
@@ -249,24 +253,36 @@ def create_external(connection, room_id, token, payload, now):
249
253
  raise classified(FileExistsError, Text("房间成员已变化,请重新读取外部成员名单后再提交"), "stale_revision")
250
254
  if not is_ai(name):
251
255
  raise ValueError(Text("成员须为有效 AI 身份"))
252
- if not hashed:
256
+ if not hashed and not pending:
253
257
  raise ValueError(Text("每位成员须提供 32–256 字符的成员凭证"))
258
+ if pending:
259
+ hashed, machine = "", ""
254
260
  adapter = checked_text(payload.get("adapter", ""), MAX_ADAPTER, "adapter")
255
261
  label = checked_text(payload.get("machine_label"), MAX_MACHINE_LABEL, "machine_label")
256
262
  directories = checked_scope(payload.get("scope"), payload.get("directories", []))
257
- expires_at = checked_expiry(payload.get("expires_at"), now)
263
+ expires_at = now + PENDING_SEAT_SECONDS if pending else checked_expiry(payload.get("expires_at"), now)
258
264
  quota = checked_quota(payload.get("quota"), DEFAULT_QUOTA)
259
265
  if connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, name)).fetchone():
260
266
  raise FileExistsError(Text("{name} 已是本房间成员", name=name))
261
267
  if connection.execute("SELECT COUNT(*) FROM room_members WHERE room_id=? AND status<>'removed'", (room_id,)).fetchone()[0] >= MAX_ROOM_AGENTS:
262
268
  raise FileExistsError(Text("房间成员已满"))
263
- free_room.require_fresh_member_token(connection, room_id, member_token)
269
+ if not pending:
270
+ free_room.require_fresh_member_token(connection, room_id, member_token)
264
271
  cursor = connection.execute("""INSERT INTO room_members (room_id,name,adapter,token_hash,access,session_mode,created_at)
265
272
  VALUES (?,?,?,?,'external','new',?)""", (room_id, name, adapter, hashed, free_room_now()))
266
273
  connection.execute("""INSERT INTO external_members (member_id,room_id,token_hash,machine,machine_label,scope,directories,expires_at,
267
- hourly_bytes,total_bytes,hourly_reads,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
274
+ hourly_bytes,total_bytes,hourly_reads,created_at,updated_at,claimed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
268
275
  (cursor.lastrowid, room_id, hashed, machine, label, payload["scope"], json.dumps(directories, ensure_ascii=False),
269
- expires_at, quota["hourly_bytes"], quota["total_bytes"], quota["hourly_reads"], now, now))
276
+ expires_at, quota["hourly_bytes"], quota["total_bytes"], quota["hourly_reads"], now, now, 0 if pending else now))
277
+ if pending:
278
+ duration = payload.get("duration", "1h")
279
+ if duration not in ("1h", "today", "3d"):
280
+ raise ValueError(Text("外部成员不存在"))
281
+ connection.execute("UPDATE external_members SET claimed_at=0,invite_duration=? WHERE member_id=?", (duration, cursor.lastrowid))
282
+ suffix = name.removeprefix("Custom-ext") if name.startswith("Custom-ext") else f"-{cursor.lastrowid}"
283
+ connection.execute("""INSERT INTO member_labels(room_id,name,label,updated_at) VALUES(?,?,?,?)
284
+ ON CONFLICT(room_id,name) DO UPDATE SET label=excluded.label,updated_at=excluded.updated_at""",
285
+ (room_id, name, str(Text("另一台电脑{suffix}", suffix=suffix)), now))
270
286
  free_room.queue_invited_expert(connection, room_id, name, now)
271
287
  free_room.sync_participants(connection, room_id)
272
288
  row = external_row(connection, room_id, cursor.lastrowid)
@@ -285,6 +301,8 @@ def update_external(connection, room_id, member_id, token, payload, now):
285
301
  expire_room(connection, room_id)
286
302
  row = external_row(connection, room_id, member_id)
287
303
  action = payload.get("action")
304
+ if action in ("invite", "bind", "activate"):
305
+ return seat_action(connection, row, payload, now)
288
306
  if action == "revoke":
289
307
  if row["status"] == "active":
290
308
  end_member(connection, row, "revoked")
@@ -305,6 +323,42 @@ def update_external(connection, room_id, member_id, token, payload, now):
305
323
  return owner_view(connection, external_row(connection, room_id, member_id))
306
324
 
307
325
 
326
+ def seat_action(connection, row, payload, now):
327
+ """Version an invitation or bind and activate its fixed seat under the owner transaction."""
328
+ if row["status"] != "active":
329
+ raise FileExistsError(Text("外部成员已结束,不能再调整;需要时重新邀请"))
330
+ action = payload["action"]
331
+ if action == "invite":
332
+ if row["claimed_at"] or row["machine"]:
333
+ raise FileExistsError(Text("房间成员已变化,请重新读取外部成员名单后再提交"))
334
+ connection.execute("UPDATE external_members SET invite_version=invite_version+1 WHERE member_id=?", (row["id"],))
335
+ else:
336
+ if payload.get("invite_version") != row["invite_version"]:
337
+ raise FileExistsError(Text("房间成员已变化,请重新读取外部成员名单后再提交"))
338
+ machine = checked_text(payload.get("machine"), MAX_MACHINE, "machine", required=True)
339
+ hashed = token_hash(payload.get("token"))
340
+ if not hashed:
341
+ raise ValueError(Text("每位成员须提供 32–256 字符的成员凭证"))
342
+ if row["machine"] and (row["machine"] != machine or row["binding_hash"] != hashed):
343
+ raise FileExistsError(Text("房间成员已变化,请重新读取外部成员名单后再提交"))
344
+ if action == "bind" and not row["machine"]:
345
+ expiry = checked_expiry(payload.get("expires_at"), now)
346
+ label = checked_text(payload.get("machine_label"), MAX_MACHINE_LABEL, "machine_label")
347
+ adapter = checked_text(payload.get("adapter", ""), MAX_ADAPTER, "adapter")
348
+ connection.execute("UPDATE room_members SET adapter=? WHERE id=?", (adapter, row["id"]))
349
+ connection.execute("UPDATE external_members SET machine=?,machine_label=?,token_hash=?,expires_at=? WHERE member_id=?",
350
+ (machine, label, hashed, expiry, row["id"]))
351
+ elif action == "activate":
352
+ if not row["machine"]:
353
+ raise FileExistsError(Text("外部成员不存在"))
354
+ if not row["claimed_at"]:
355
+ connection.execute("UPDATE external_members SET claimed_at=?,updated_at=? WHERE member_id=?", (now, now, row["id"]))
356
+ connection.execute("UPDATE room_members SET token_hash=? WHERE id=?", (hashed, row["id"]))
357
+ free_room.queue_invited_expert(connection, row["room_id"], row["name"], now)
358
+ free_room.sync_participants(connection, row["room_id"])
359
+ return owner_view(connection, external_row(connection, row["room_id"], row["id"]))
360
+
361
+
308
362
  def list_reads(connection, room_id, member_id, token, params):
309
363
  """The owner reads one external member's read records in order."""
310
364
  require_owner(connection, room_id, token)
@@ -385,7 +439,7 @@ def require_external(connection, room_id, token):
385
439
  begin_write(connection)
386
440
  hashed = token_hash(token)
387
441
  row = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND x.token_hash=?", (room_id, hashed)).fetchone() if hashed else None
388
- if not row:
442
+ if not row or not row["claimed_at"]:
389
443
  raise classified(PermissionError, Text("需要本房间外部成员的凭证"), "external_credential_required")
390
444
  if row["status"] == "active" and row["expires_at"] <= int(time.time()):
391
445
  end_member(connection, row, "expired")
@@ -406,7 +460,7 @@ def member_room_view(connection, room_id, member):
406
460
  labels = free_room.member_display_names(connection, room_id)
407
461
  members = [{"name": row["name"], "label": labels.get(row["name"], row["name"]), "role": row["role"], "status": row["status"],
408
462
  "external": row["access"] == "external"}
409
- for row in connection.execute("SELECT name,role,status,access FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id",
463
+ for row in connection.execute(f"SELECT name,role,status,access FROM room_members WHERE room_id=? AND status<>'removed' AND {free_room.REGISTERED_MEMBER} ORDER BY id",
410
464
  (room_id,))]
411
465
  latest = connection.execute("""SELECT COALESCE(MAX(id),0) FROM messages m WHERE room_id=?
412
466
  AND NOT EXISTS (SELECT 1 FROM internal_task_messages t WHERE t.message_id=m.id)""", (room_id,)).fetchone()[0]
@@ -189,6 +189,7 @@ def reported_capabilities(row):
189
189
  # Columns added after the first free-room tables; Python databases created by that build gain them here.
190
190
  LATER_COLUMNS = {"room_members": {"access": "TEXT NOT NULL DEFAULT 'runner'", "session_mode": "TEXT NOT NULL DEFAULT 'new'"},
191
191
  "member_executions": {"changes": "TEXT NOT NULL DEFAULT ''", "edited": "TEXT NOT NULL DEFAULT ''", "cwd": "TEXT NOT NULL DEFAULT ''",
192
+ "diffs": "TEXT NOT NULL DEFAULT ''",
192
193
  "activity": "TEXT NOT NULL DEFAULT ''", "activity_at": "INTEGER NOT NULL DEFAULT 0",
193
194
  "paused_at": "INTEGER NOT NULL DEFAULT 0"},
194
195
  "member_requests": {"chain_id": "INTEGER NOT NULL DEFAULT 0", "batch_id": "INTEGER NOT NULL DEFAULT 0",
@@ -208,6 +209,24 @@ def migrate_free_tables(connection):
208
209
  for name, definition in columns.items():
209
210
  if name not in present:
210
211
  connection.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")
212
+ present = {row[1] for row in connection.execute("PRAGMA table_info(external_members)")}
213
+ claimed = next((row for row in connection.execute("PRAGMA table_info(external_members)") if row[1] == "claimed_at"), None)
214
+ if claimed and str(claimed[4]) == "1":
215
+ values = list(connection.execute("SELECT claimed_at,member_id FROM external_members"))
216
+ connection.execute("ALTER TABLE external_members DROP COLUMN claimed_at")
217
+ connection.execute("ALTER TABLE external_members ADD COLUMN claimed_at INTEGER NOT NULL DEFAULT 0")
218
+ connection.executemany("UPDATE external_members SET claimed_at=? WHERE member_id=?", values)
219
+ for name, default in (("claimed_at", 0), ("invite_version", 0)):
220
+ if name not in present:
221
+ connection.execute(f"ALTER TABLE external_members ADD COLUMN {name} INTEGER NOT NULL DEFAULT {default}")
222
+ if name == "claimed_at":
223
+ connection.execute("UPDATE external_members SET claimed_at=1")
224
+ if "invite_duration" not in present:
225
+ connection.execute("ALTER TABLE external_members ADD COLUMN invite_duration TEXT NOT NULL DEFAULT '1h'")
226
+ index = connection.execute("SELECT sql FROM sqlite_master WHERE name='member_credential'").fetchone()
227
+ if index and "WHERE" not in index[0].upper():
228
+ connection.execute("DROP INDEX member_credential")
229
+ connection.execute("CREATE UNIQUE INDEX member_credential ON room_members(room_id,token_hash) WHERE token_hash<>''")
211
230
  migrate_stop_results(connection)
212
231
  migrate_failure_classes(connection)
213
232
 
@@ -964,6 +983,7 @@ def recent_executions(connection, room_id, span=None):
964
983
  requests.append(request_data)
965
984
  executions.append({**public_execution(row), "texts": execution_texts(connection, row["id"]), "member": row["member"], "cwd": row["cwd"], "changes": json.loads(row["changes"] or "[]"),
966
985
  "changes_recorded": bool(row["changes"]), "request_ids": json.loads(row["request_ids"]),
986
+ "edited": json.loads(row["edited"]) if row["edited"] else None, "diff_stats": diff_stats(row["diffs"]),
967
987
  "answer_id": row["answer_id"], "request_message_id": row["request_message_id"],
968
988
  "layout_after": row["layout_after"], "layout_at": row["layout_at"] or row["created_at"], "requests": requests,
969
989
  "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"),
@@ -1034,7 +1054,9 @@ def possible_conflicts(connection, room_id, names):
1034
1054
 
1035
1055
  # An invited manual member that has not registered counts as absent: it receives no request and is never a target.
1036
1056
  REGISTERED_MEMBER = """(room_members.access<>'manual' OR EXISTS(SELECT 1 FROM member_registrations r
1037
- WHERE r.member_id=room_members.id AND r.token_hash=room_members.token_hash))"""
1057
+ WHERE r.member_id=room_members.id AND r.token_hash=room_members.token_hash))
1058
+ AND (room_members.access<>'external' OR EXISTS(SELECT 1 FROM external_members x
1059
+ WHERE x.member_id=room_members.id AND x.claimed_at>0 AND x.ended_at=0 AND room_members.token_hash<>''))"""
1038
1060
 
1039
1061
  # One snapshot for group routing; the Worker uses the same SQL inside its atomic write assertion.
1040
1062
  GROUP_STATE_SQL = f"""SELECT json_object(
@@ -1203,7 +1225,7 @@ def authorize_free_write(connection, room_id, token, operation, payload):
1203
1225
  def active_members(connection, room_id, registered_only=True):
1204
1226
  """Map active member names to their rows; unregistered manual members are left out unless a discussion start needs them pending."""
1205
1227
  return {row["name"]: row for row in connection.execute(
1206
- f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND ({REGISTERED_MEMBER} OR ?=0)", (room_id, int(registered_only)))}
1228
+ f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND ({REGISTERED_MEMBER} OR (?=0 AND access<>'external'))", (room_id, int(registered_only)))}
1207
1229
 
1208
1230
 
1209
1231
  def named_members(active, names, exclude=None):
@@ -2390,6 +2412,7 @@ def speaking_order(connection, room):
2390
2412
  speakers; a plan reaching into later rounds lists them apart in `later` (one name list per round), read-only. The
2391
2413
  revision changes with any of it.
2392
2414
  """
2415
+ # The display includes reserved seats; dispatch uses active_members separately.
2393
2416
  active = [member for member in room["members"] if member["status"] == "active"]
2394
2417
  by_id = {member["id"]: member for member in active}
2395
2418
  ordered = [member["name"] for member in default_order(connection, room["id"], active)]
@@ -3220,6 +3243,53 @@ def changed_files(payload):
3220
3243
  return sorted(set(files))
3221
3244
 
3222
3245
 
3246
+ MAX_DIFF_PATCH_CHARS = 64 * 1024
3247
+ MAX_DIFFS_CHARS = 512 * 1024
3248
+
3249
+
3250
+ def file_diffs(payload, changes):
3251
+ """The runner's line counts and patches of the changed files, kept within `changes`; '' when none were sent.
3252
+
3253
+ Each item is `{path, added, removed, patch, truncated, created?, deleted?}`, or `{path, skipped}` for a large or binary
3254
+ file. Oversized patches are dropped (the counts stay) rather than refusing the whole report."""
3255
+ items = payload.get("diffs")
3256
+ if items is None:
3257
+ return ""
3258
+ if not isinstance(items, list) or len(items) > MAX_CHANGED_FILES:
3259
+ raise ValueError(Text("diffs 须为最多 {max_changed_files} 项的列表", max_changed_files=MAX_CHANGED_FILES))
3260
+ known, kept, total = set(changes), [], 0
3261
+ for item in items:
3262
+ if not isinstance(item, dict) or item.get("path") not in known:
3263
+ continue
3264
+ if item.get("skipped") in ("large", "binary"):
3265
+ kept.append({"path": item["path"], "skipped": item["skipped"]})
3266
+ continue
3267
+ added, removed, patch = item.get("added"), item.get("removed"), item.get("patch", "")
3268
+ if not all(isinstance(value, int) and not isinstance(value, bool) and value >= 0 for value in (added, removed)) or not isinstance(patch, str):
3269
+ continue
3270
+ truncated = bool(item.get("truncated"))
3271
+ if len(patch) > MAX_DIFF_PATCH_CHARS or total + len(patch) > MAX_DIFFS_CHARS:
3272
+ patch, truncated = "", True
3273
+ total += len(patch)
3274
+ kept.append({"path": item["path"], "added": added, "removed": removed, "patch": patch, "truncated": truncated,
3275
+ **{flag: True for flag in ("created", "deleted") if item.get(flag) is True}})
3276
+ return json.dumps(kept, ensure_ascii=False)
3277
+
3278
+
3279
+ def diff_stats(stored):
3280
+ """The stored diffs without their patches: what every room read carries; the patches are read on demand."""
3281
+ return [{key: value for key, value in item.items() if key != "patch"} for item in json.loads(stored)] if stored else []
3282
+
3283
+
3284
+ def execution_diffs(connection, room_id, execution_id, token):
3285
+ """One execution's file patches for its card, for the room owner (they hold project file content)."""
3286
+ require_owner(connection, room_id, token)
3287
+ row = connection.execute("SELECT diffs FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
3288
+ if not row:
3289
+ raise LookupError(Text("执行不存在"))
3290
+ return {"execution_id": execution_id, "diffs": json.loads(row["diffs"]) if row["diffs"] else []}
3291
+
3292
+
3223
3293
  def edited_files(payload, changes):
3224
3294
  """The reported files the member's own edit tools wrote, kept within `changes`; '' when the runner could not tell."""
3225
3295
  if "edited" not in payload:
@@ -3383,8 +3453,8 @@ def execution_action(connection, room_id, execution_id, token, payload, member=N
3383
3453
  if row["changes"]:
3384
3454
  raise FileExistsError(Text("本次执行的改动已记录"))
3385
3455
  changes = changed_files(payload)
3386
- connection.execute("UPDATE member_executions SET changes=?,edited=? WHERE id=?",
3387
- (json.dumps(changes, ensure_ascii=False), edited_files(payload, changes), execution_id))
3456
+ connection.execute("UPDATE member_executions SET changes=?,edited=?,diffs=? WHERE id=?",
3457
+ (json.dumps(changes, ensure_ascii=False), edited_files(payload, changes), file_diffs(payload, changes), execution_id))
3388
3458
  elif action == "denials":
3389
3459
  # Like file changes, read from the software's output once its process ends; recorded once.
3390
3460
  saved = connection.execute("INSERT OR IGNORE INTO execution_denials (execution_id,room_id,denials) VALUES (?,?,?)",
@@ -3837,7 +3907,7 @@ def queue_invited_expert(connection, room_id, name, now):
3837
3907
  A manual expert is queued only once it has registered (the invite alone does not), and only once per invitation.
3838
3908
  """
3839
3909
  member = connection.execute("SELECT * FROM room_members WHERE room_id=? AND name=? AND status='active'", (room_id, name)).fetchone()
3840
- if not member or (member["adapter"] == "manual" and not registered_at(connection, member)):
3910
+ if not member or name not in active_members(connection, room_id):
3841
3911
  return
3842
3912
  session = discussion.current_session(connection, room_id)
3843
3913
  if session and session["status"] != "concluded":
@@ -44,6 +44,8 @@ def default_label(name):
44
44
 
45
45
  def default_label_text(name, label):
46
46
  """Return display metadata only for the unchanged Custom platform nickname."""
47
+ if name.startswith("Custom-ext") and label == "另一台电脑" + name.removeprefix("Custom-ext"):
48
+ return text_payload(Text("另一台电脑{suffix}", suffix=name.removeprefix("Custom-ext")))
47
49
  if platform_of(name) == "Custom" and label == default_label(name):
48
50
  return text_payload(Text("自定义 API{suffix}", suffix=name[len("Custom"):]))
49
51
  return None
@@ -235,7 +235,7 @@ CREATE TABLE IF NOT EXISTS room_members (
235
235
  session_mode TEXT NOT NULL DEFAULT 'new'
236
236
  );
237
237
  CREATE UNIQUE INDEX IF NOT EXISTS member_name ON room_members(room_id,name) WHERE status<>'removed';
238
- CREATE UNIQUE INDEX IF NOT EXISTS member_credential ON room_members(room_id,token_hash);
238
+ CREATE UNIQUE INDEX IF NOT EXISTS member_credential ON room_members(room_id,token_hash) WHERE token_hash<>'';
239
239
 
240
240
  -- Local service attestation, never a permission grant. Re-imported rooms require a fresh attestation.
241
241
  CREATE TABLE IF NOT EXISTS member_review_capabilities (
@@ -556,6 +556,9 @@ CREATE TABLE IF NOT EXISTS external_members (
556
556
  room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
557
557
  token_hash TEXT NOT NULL,
558
558
  machine TEXT NOT NULL,
559
+ claimed_at INTEGER NOT NULL DEFAULT 0,
560
+ invite_version INTEGER NOT NULL DEFAULT 0,
561
+ invite_duration TEXT NOT NULL DEFAULT '1h',
559
562
  machine_label TEXT NOT NULL DEFAULT '',
560
563
  scope TEXT NOT NULL CHECK(scope IN ('discuss','read')),
561
564
  directories TEXT NOT NULL DEFAULT '[]',
package/backend/server.py CHANGED
@@ -43,7 +43,7 @@ from .free_room import describe_members, execution_notes, label_members, set_hos
43
43
  from .free_room import (ADAPTER_VALUE, LAYOUT_AFTER_SQL, LAYOUT_AT_SQL, continue_chain, execution_timeline, group_route_plan, retract_message, rewind_plan, rewind_room,
44
44
  room_event_log, withdrawals)
45
45
  from .free_room import review_capability, review_roster, checked_review_plan, save_review_plan, check_review_retry
46
- from .free_room import review_ready, advance_review, late_answer
46
+ from .free_room import review_ready, advance_review, late_answer, execution_diffs
47
47
  from .free_room import checked_sequence, continue_sequence, sequence_view
48
48
  from . import questions
49
49
  from .identity import MAX_ROOM_AGENTS, PARTICIPANTS, default_label_text, is_ai, is_participant
@@ -548,6 +548,10 @@ def require_room(connection, room_id):
548
548
  room["host_arrangements"] = host_arrangements(connection, room_id, room["scheduler_decisions"])
549
549
  room["cancelled_turns"] = cancelled_turns(connection, room_id)
550
550
  room["free"] = free_view(connection, room_id)
551
+ external_fields = {member["id"]: member.get("external") for member in room["free"]["members"] if member["access"] == "external"}
552
+ for member in room["members"]:
553
+ if member["id"] in external_fields:
554
+ member["external"] = external_fields[member["id"]]
551
555
  room["goal_state"] = goal_view(connection, room_id)
552
556
  # Where the room's own task starts when no goal was set: the owner's first message (COVERAGE 3③).
553
557
  first = connection.execute("SELECT MIN(id) FROM messages WHERE room_id=? AND author='用户'", (room_id,)).fetchone()[0]
@@ -739,10 +743,9 @@ def merge_round_groups(connection, room_id):
739
743
  group["host_scheduled"] = group["host_scheduled"] or row["role"] == "host"
740
744
  if not by_round:
741
745
  return []
742
- active_experts = connection.execute("""SELECT COUNT(*) FROM room_members m
743
- WHERE m.room_id=? AND m.status='active' AND m.role<>'host'
744
- AND (m.access<>'manual' OR EXISTS(SELECT 1 FROM member_registrations reg
745
- WHERE reg.member_id=m.id AND reg.token_hash=m.token_hash))""", (room_id,)).fetchone()[0]
746
+ from .free_room import REGISTERED_MEMBER
747
+ active_experts = connection.execute(f"""SELECT COUNT(*) FROM room_members
748
+ WHERE room_id=? AND status='active' AND role<>'host' AND {REGISTERED_MEMBER}""", (room_id,)).fetchone()[0]
746
749
  previous_answers = {}
747
750
  result = []
748
751
  for (session_id, number), group in sorted(by_round.items()):
@@ -3421,6 +3424,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3421
3424
  result = adopt_recommendation(connection, room_id, token, int(parts[4]), self.read_payload())
3422
3425
  elif len(parts) == 6 and parts[3] == "executions" and parts[5] == "notes" and method == "GET":
3423
3426
  result = execution_notes(connection, room_id, int(parts[4]), token)
3427
+ elif len(parts) == 6 and parts[3] == "executions" and parts[5] == "diff" and method == "GET":
3428
+ result = execution_diffs(connection, room_id, int(parts[4]), token)
3424
3429
  elif len(parts) == 6 and parts[3] == "executions" and parts[5] == "late-answer" and method == "GET":
3425
3430
  result = late_answer(connection, room_id, int(parts[4]), token)
3426
3431
  elif len(parts) == 5 and parts[3] == "executions":
@@ -534,6 +534,8 @@ def _session_roster(connection, session_id):
534
534
  experts = []
535
535
  shown = member_display_names(connection, session["room_id"])
536
536
  for member in members:
537
+ if member["access"] == "external" and member["name"] not in active_members(connection, session["room_id"]):
538
+ continue
537
539
  registered = member["access"] != "manual" or member["registration_hash"] == member["token_hash"]
538
540
  experts.append({"id": member["id"],"name":member["name"],"label":shown.get(member["name"], member["name"]),
539
541
  "host":member["role"] == "host", "mode":member["access"],
@@ -672,7 +674,7 @@ def _validate_plan_members(connection, room_id, plan):
672
674
  member = connection.execute("""SELECT * FROM room_members m
673
675
  WHERE m.room_id=? AND m.name=? AND m.status='active'""",
674
676
  (room_id, name)).fetchone()
675
- if not member:
677
+ if not member or (member["access"] == "external" and name not in active_members(connection, room_id)):
676
678
  raise ValueError(Text("安排对象 {name} 不是在场专家", name=name))
677
679
  if member["access"] == "manual" and not connection.execute(
678
680
  "SELECT 1 FROM member_registrations WHERE member_id=? AND token_hash=?",
@@ -827,9 +829,9 @@ def _advance_initial_phase(connection, session_id):
827
829
  def _expert_denominator(connection, session_id, round_number=None):
828
830
  """Count registered active experts, plus the host only if that round explicitly schedules them."""
829
831
  room_id = connection.execute("SELECT room_id FROM discussion_sessions WHERE id=?", (session_id,)).fetchone()[0]
830
- count = connection.execute("""SELECT COUNT(*) FROM room_members m LEFT JOIN member_registrations r ON r.member_id=m.id
831
- WHERE m.room_id=? AND m.status='active' AND m.role<>'host'
832
- AND (m.access<>'manual' OR r.token_hash=m.token_hash)""", (room_id,)).fetchone()[0]
832
+ from .free_room import REGISTERED_MEMBER
833
+ count = connection.execute(f"""SELECT COUNT(*) FROM room_members
834
+ WHERE room_id=? AND status='active' AND role<>'host' AND {REGISTERED_MEMBER}""", (room_id,)).fetchone()[0]
833
835
  host_sql = "SELECT 1 FROM session_requests WHERE session_id=? AND purpose='discuss' AND member_id IN (SELECT id FROM room_members WHERE room_id=? AND role='host')"
834
836
  values = [session_id, room_id]
835
837
  if round_number is not None:
package/docs/en/runner.md CHANGED
@@ -87,9 +87,9 @@ Invite an AI on another computer into your room: it reads only the project files
87
87
  **Before you start**: both computers install CoDiscuss and run the local service; your computer is [connected to a hosted site](#from-a-hosted-site) with the relay deployed, and the other side reaches your room through that site's encrypted relay. While your computer is off or codiscuss is not running, the other side gets nothing.
88
88
 
89
89
  **Invite (your computer)**:
90
- 1. In the right panel's "Invite members" dialog, choose "Another computer" on the "External" row, then pick what it may do (discussion only, or can read project), which project folders to open (only folders this room already has), and how long it stays (1 hour, today or 3 days).
91
- 2. Choose "Create invitation" and send the link, QR code or pairing code. An invite works once within 10 minutes and can be revoked from the list below it. Paired phones and tablets can issue invites too.
92
- 3. Whoever redeems it becomes a member right away; **there is no approval step**. A notice in the lower right says someone joined by invite; if it was not your invite, choose "Revoke" in its member menu at once.
90
+ 1. In the new-room panel or Invite members, choose External → Another computer and select the access, folders and membership duration after check-in.
91
+ 2. Choose Add a seat awaiting check-in (automatic when creating the room). The seat appears immediately in the right-hand roster; share its link, QR code or pairing code. The link lasts 10 minutes and binds one member; regenerating it invalidates the previous link. Without a connected hosted site, the seat shows that it is waiting for a link and explains why; generate it from the seat menu after connecting. Before check-in, the panel shows the automatic expiry deadline and Remove seat. Usage, read logs and access adjustments appear after check-in.
92
+ 3. Redemption completes check-in and starts the membership duration, with **no extra approval step**. Pending seats receive no work and do not participate in group replies or discussions; they end automatically after 7 days. An expired link leaves the seat intact.
93
93
  4. `@` it in the room; its answers appear in the conversation as usual. "Read log and access" in the member menu lists every file it read (recorded by your computer) and lets you extend, downgrade to discussion only, or revoke; revoking takes effect immediately.
94
94
 
95
95
  **Join (the other computer)**:
package/docs/runner.md CHANGED
@@ -118,9 +118,9 @@ codiscuss local connect https://你的站点
118
118
  **前提**:两台电脑都安装共议并运行本机服务;你的电脑已[连接线上网站](#线上网页连接本机)并部署了中转,对方经这个网站的加密中转访问你的房间。你的电脑关机或 codiscuss 未运行时,对方什么也拿不到。
119
119
 
120
120
  **邀请(你的电脑)**:
121
- 1. 右栏“邀请成员”弹窗的“外部”一行点“另一台电脑”,选择能做什么(只讨论,或可读项目)、开放哪些项目目录(只能选本房间已有的)、有效期(1 小时、今天或 3 天)。
122
- 2. 点“生成邀请”,把链接、二维码或配对码发给对方。邀请 10 分钟内有效、只能用一次,可在下方列表撤销。已配对的手机或平板也能签发邀请。
123
- 3. 对方加入后直接成为成员,**没有批准步骤**:右下角会提示有人经邀请加入,不是你邀请的就立即在成员菜单里撤销授权。
121
+ 1. 建房面板或右栏“邀请成员”里选择“外部 · 另一台电脑”,设置开放内容、目录和签到后的有效期。
122
+ 2. 点“添加待签到席位”(建房时自动添加),右栏名单立即显示待签到成员;把席位的链接、二维码或配对码发给对方。链接 10 分钟有效,只能绑定一位成员;重新生成会立即作废旧链接。未绑定线上站点时显示“待生成链接”及原因,绑定站点后从席位菜单生成。待签到面板显示自动结束期限,可“移除席位”;签到后才显示用量、读取记录和授权调整。
123
+ 3. 对方兑换即完成签到,成员有效期从兑换时开始,**没有额外批准步骤**。未签到不收任务、不参与全体回应或讨论,7 天后自动结束;链接过期不会删除席位。
124
124
  4. 在房间里 `@` 它,回答照常出现在对话中。成员菜单的“读取记录与权限”列出它读过的每个文件(由你的电脑记录),可延长、降为只讨论或撤销授权,撤销立即生效。
125
125
 
126
126
  **加入(对方电脑)**:
@@ -809,5 +809,6 @@
809
809
  "该目录未对外部成员开放": "This directory is not open to the external member",
810
810
  "读取总量已达上限": "The total read volume limit has been reached",
811
811
  "配额 {key} 须为 1–{limit} 的整数": "Quota {key} must be an integer from 1 to {limit}",
812
- "需要本房间外部成员的凭证": "This room's external member credential is required"
812
+ "需要本房间外部成员的凭证": "This room's external member credential is required",
813
+ "diffs 须为最多 {max_changed_files} 项的列表": "diffs must be a list of at most {max_changed_files} items"
813
814
  }
@@ -28,7 +28,6 @@
28
28
  "已拒绝,对方会看到“对方未同意”": "Declined; the other side will see \"Not accepted\"",
29
29
  "已在这台电脑上退出;对方电脑不在线,它那边要等撤销或到期才会移除": "Left on this computer; the other computer is offline, so it removes you only when it revokes or the membership expires",
30
30
  "已退出该房间": "Left the room",
31
- "邀请已撤销": "Invitation revoked",
32
31
  "邀请另一台电脑上的 AI": "Invite an AI on another computer",
33
32
  "另一台电脑": "Another computer",
34
33
  "移除这张卡片": "Remove this card",
@@ -39,16 +38,11 @@
39
38
  "有效期": "Valid for",
40
39
  "项目内容会经对方的 AI 发送给其模型服务商;读出去的内容收不回,撤销只阻止以后的读取。": "Project content reaches the other side's model provider through their AI; what was read cannot be taken back, and revoking only stops later reads.",
41
40
  "房间里发给它的内容会经对方的 AI 发送给其模型服务商。": "What the room sends it reaches the other side's model provider through their AI.",
42
- "生成邀请": "Create invitation",
43
41
  "生成邀请需要本机服务,请在这台电脑打开本机网站。": "Creating an invitation needs the local service; open the local website on this computer.",
44
42
  "邀请二维码": "Invitation QR code",
45
43
  "把链接或二维码发给对方;对方也可以在自己的共议里输入配对码:": "Send the link or QR code to the other person; they can also enter the pairing code in their own CoDiscuss:",
46
44
  "复制配对码": "Copy pairing code",
47
- "{time} 前兑换有效,只能用一次。对方兑换后直接成为成员,你会收到提示,可随时撤销。": "Redeem before {time}, once only. Whoever redeems it becomes a member at once; you get a notice and can revoke at any time.",
48
45
  "配对码不含这台电脑的公钥指纹,优先发链接或二维码。": "The pairing code does not carry this computer's key fingerprint; prefer sending the link or QR code.",
49
- "再生成一个": "Create another",
50
- "待兑换的邀请": "Pending invitations",
51
- "{level} · 成员 {duration} · {left}内兑换": "{level} · member for {duration} · redeem within {left}",
52
46
  "立即生效:之后的请求与读取一律被拒,未完成的执行作废。": "Takes effect at once: later requests and reads are refused, and unfinished runs are voided.",
53
47
  "已经读出去的内容收不回,会留在对方 AI 的会话里。": "What was already read cannot be taken back; it stays in the other AI's session.",
54
48
  "外部成员 · {name}": "External member · {name}",
@@ -159,7 +153,6 @@
159
153
  "被对方撤销": "revoked by the other side",
160
154
  "你已退出": "you left",
161
155
  "已结束:{reason}": "Ended: {reason}",
162
- "撤销邀请": "Revoke",
163
156
  "撤销授权": "Revoke",
164
157
  "已结束,未回答": "Ended without an answer",
165
158
  "这台电脑没有可用的 AI 程序,未启动": "No usable AI program on this computer; not started",
@@ -185,5 +178,21 @@
185
178
  "剩 {count} 天": "{count}d",
186
179
  "剩 {count} 小时": "{count}h",
187
180
  "剩 {count} 分": "{count}m",
188
- "{used} / {limit} · 本小时 {hour} / {hour_limit} · 被拒 {denied} 次": "{used} / {limit} · this hour {hour} / {hour_limit} · {denied} refused"
181
+ "{used} / {limit} · 本小时 {hour} / {hour_limit} · 被拒 {denied} 次": "{used} / {limit} · this hour {hour} / {hour_limit} · {denied} refused",
182
+ "还没有选项目目录,只能选“只讨论”。": "No project directory chosen yet, so only \"Discuss only\" is available.",
183
+ "另一台电脑 · 待签到": "Another computer · Awaiting check-in",
184
+ "待签到": "Awaiting check-in",
185
+ "重新生成链接": "Regenerate link",
186
+ "添加待签到席位": "Add a seat awaiting check-in",
187
+ "待生成链接": "Waiting for a link",
188
+ "邀请链接": "Invitation link",
189
+ "创建房间后添加待签到席位并生成邀请链接,再发给对方。": "After creating the room, reserve a seat and generate its invitation link to send to the other person.",
190
+ "{time} 前兑换有效,只能用一次。对方兑换后完成签到,你会收到提示,可随时撤销。": "Redeem before {time}, for one member only. Check-in completes on redemption; you will be notified and can revoke access anytime.",
191
+ "另一台电脑{suffix}": "Another computer{suffix}",
192
+ "链接只在生成时显示;请重新生成。未绑定线上网站时,需先在设置中绑定。": "Links are shown only when generated. Generate a new one; if no online site is bound, bind one in Settings first.",
193
+ "{count} 台另一台电脑待签到": "{count} other computer(s) awaiting check-in",
194
+ "{count} 天内未签到自动结束": "Ends automatically if not checked in within {count} days",
195
+ "移除席位": "Remove seat",
196
+ "席位已移除": "Seat removed",
197
+ "生成链接": "Generate link"
189
198
  }
@@ -751,5 +751,13 @@
751
751
  "接入此会话": "Resume this session",
752
752
  "额度已用尽,预计 {value1} 恢复;给它发新消息会立即再试": "Out of quota, expected back at {value1}; a new message to it is tried at once",
753
753
  "保存(Enter)": "Save (Enter)",
754
- "已重试,新的执行接在下方": "Retried; the new run follows below"
754
+ "已重试,新的执行接在下方": "Retried; the new run follows below",
755
+ "已修改 {count} 个文件": "Edited {count} files",
756
+ "二进制文件": "Binary file",
757
+ "文件过大": "File too large",
758
+ "正在读取改动…": "Reading changes…",
759
+ "读取改动失败:{value1}": "Could not read changes: {value1}",
760
+ "改动较长,只显示前面一部分": "Long change; only the first part is shown",
761
+ "这些文件在同一时间被改动,但不是这位成员的编辑工具写的,可能来自其他窗口或成员": "These files changed meanwhile but not through this member's edit tools; another window or member may have changed them",
762
+ "同期其他改动:{value1}": "Other changes meanwhile: {value1}"
755
763
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.66",
3
+ "version": "0.4.67",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -32,6 +32,7 @@ import { FreeRoomRunner, free_task_files } from './free_runner.mjs';
32
32
  import { assert_workflow_enabled, bind_room_workflow, delete_workflow, get_workflow, list_workflows, load_room_workflow, parse_workflow_draft, preview_workflow, rename_workflow, save_workflow, set_workflow_disabled, workflow_cards, workflow_directory, WORKFLOW_ID_PATTERN } from './workflows.mjs';
33
33
  import { assert_shared_home, CONNECTION_FIELDS, configuration_snapshot, read_registry, registered_identity, register_room, service_home, service_pid, start_service } from './discussion_service.mjs';
34
34
  import { site_fetch } from './entry_client.mjs';
35
+ import { t } from './i18n.mjs';
35
36
 
36
37
  // A platform is a type; `Claude-review` is another Claude instance with its own session, model and effort. An ID is
37
38
  // English letters, digits and underscores only; a Chinese name is a display label.
@@ -133,7 +134,7 @@ pick-directory 在本机弹出系统目录选择窗口,返回所选路径;
133
134
  browse-directory 列出常用项目及其中的子文件夹(只含文件夹名,分页),供其他设备选择目录;path 为空时列出常用项目。
134
135
  device-pairing 在本机生成 12 位设备配对码(2 分钟有效,可选 temporary 临时设备、without_passkey 允许这次配对不用通行密钥、site 指定已绑定的网站),扫码链接带本机密钥指纹;只能在这台电脑上执行,新设备只能在电脑前添加。
135
136
  devices 列出已配对设备;提供 revoke(设备 id)撤销设备。
136
- room-invite 为本机房间签发一次性外部成员邀请(10 分钟内兑换一次);须提供 room_id、token,可选 level(discuss/read)、folders(项目目录序号)、duration(1h/today/3d)、site_url;返回配对码与链接,只显示这一次。
137
+ ${t("room-invite 创建待签到席位并签发邀请;提供 member_id 时重发该席位链接,旧链接失效。须提供 room_id、token,可选 level(discuss/read)、folders、duration(1h/today/3d)、site_url;程序先读名单 revision 再建席位。链接有效 10 分钟,未签到席位 7 天结束;未绑定线上站点时只建立席位。")}
137
138
  room-invites 列出房间未兑换的邀请(不含配对码);须提供 room_id、token。
138
139
  room-invite-revoke 撤销一条未兑换的邀请;须提供 room_id、token、invite_id。
139
140
  projects 读取本机已配置的项目(名称与绝对路径);提供 JSON(projects 列表)时整体替换保存。