ai_co_discuss 0.5.26 → 0.5.27

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.
Files changed (70) hide show
  1. package/.agents/skills/discuss-host/SKILL.md +1 -1
  2. package/.agents/skills/discuss-host/references/control.md +5 -1
  3. package/.agents/skills/discuss-participant/references/room.md +1 -0
  4. package/backend/free_room.py +304 -20
  5. package/backend/message_queue.py +17 -7
  6. package/backend/room_links.py +125 -0
  7. package/backend/schema.sql +61 -1
  8. package/backend/server.py +82 -13
  9. package/docs/en/guide/admin.md +1 -1
  10. package/docs/en/guide/external-members.md +1 -1
  11. package/docs/en/guide/faq.md +2 -2
  12. package/docs/en/guide/members.md +6 -3
  13. package/docs/en/guide/remote.md +1 -1
  14. package/docs/en/guide/rooms.md +13 -6
  15. package/docs/en/guide/workflows.md +3 -1
  16. package/docs/en/guide/working.md +6 -2
  17. package/docs/guide/admin.md +1 -1
  18. package/docs/guide/external-members.md +1 -1
  19. package/docs/guide/faq.md +2 -2
  20. package/docs/guide/members.md +6 -3
  21. package/docs/guide/remote.md +1 -1
  22. package/docs/guide/rooms.md +13 -7
  23. package/docs/guide/workflows.md +3 -1
  24. package/docs/guide/working.md +6 -2
  25. package/frontend/locales/en/admin.json +3 -3
  26. package/frontend/locales/en/app.json +7 -3
  27. package/frontend/locales/en/backend.json +67 -2
  28. package/frontend/locales/en/core.json +11 -22
  29. package/frontend/locales/en/discussion.json +12 -2
  30. package/frontend/locales/en/room.json +47 -3
  31. package/frontend/locales/en/settings.json +27 -2
  32. package/package.json +1 -1
  33. package/runner/account_env.mjs +55 -28
  34. package/runner/adapters/antigravity_app.mjs +213 -14
  35. package/runner/adapters/antigravity_cli.mjs +99 -2
  36. package/runner/adapters/api.mjs +57 -6
  37. package/runner/adapters/api_pi.mjs +41 -7
  38. package/runner/adapters/api_pi_extension.mjs +94 -4
  39. package/runner/adapters/claude.mjs +284 -18
  40. package/runner/adapters/codex_app.mjs +47 -3
  41. package/runner/adapters/codex_bridge.mjs +162 -19
  42. package/runner/adapters/codex_cli.mjs +50 -4
  43. package/runner/adapters/common.mjs +47 -0
  44. package/runner/adapters/index.mjs +20 -1
  45. package/runner/adapters/profiles.mjs +20 -10
  46. package/runner/admin_cli.mjs +14 -14
  47. package/runner/admin_panel.mjs +20 -46
  48. package/runner/admin_storage.mjs +2 -1
  49. package/runner/discuss.py +31 -0
  50. package/runner/discussion_launch.mjs +211 -37
  51. package/runner/discussion_runner.mjs +2 -1
  52. package/runner/expert_prompts.mjs +23 -4
  53. package/runner/external_client.mjs +11 -12
  54. package/runner/free_runner.mjs +358 -33
  55. package/runner/host_permissions.mjs +1 -1
  56. package/runner/i18n_en.mjs +30 -4
  57. package/runner/relay_channel.mjs +20 -3
  58. package/runner/remote_policy.mjs +27 -4
  59. package/runner/storage_guard.mjs +14 -5
  60. package/runner/workflows.mjs +97 -0
  61. package/web/admin.css +1 -1
  62. package/web/admin.js +8 -8
  63. package/web/app.js +84 -10
  64. package/web/backup.js +1 -1
  65. package/web/i18n.js +4 -4
  66. package/web/index.html +1 -1
  67. package/web/markdown.css +1 -1
  68. package/web/markdown.js +2 -2
  69. package/web/modern.css +1 -1
  70. package/web/modern.js +72 -70
@@ -25,7 +25,7 @@ description: "AI CoDiscuss 的主持技能,仅主持人调用,且须同时
25
25
  2. **收束前自查**:收束、宣告完成(含 Goal 完成)或关闭定时检查前,对照任务里的 `room_goal` 和用户最近的要求;还有遗留方向就继续安排,或告诉用户还差什么。(一次派活或一个 Goal 做完,不等于房间任务完成。)
26
26
  3. **权限由用户授予**:不邀请成员,不开启讨论或 Goal,不扩大工作目录、软件权限或执行额度,派活不超出用户给的范围。唯一例外是任务有 `host_workflows: true`(房主勾选了主持人权限,`host_permissions` 列出勾选的项),边界见 [房间控制与恢复](references/control.md)。(扩权与刹车留在用户手里。)
27
27
  4. **有工作流先分流**:任务有 `workflow` 字段时,派活或改文件之前先读 `workflow.skill_path`,把请求对照主线和每个 `workflow.sub_workflows` 的 `description`;命中就读它的 SKILL.md 并照做,不问用户要不要用,回答开头用一句话写明走的哪条;都不命中就按普通请求处理,回答里不必说明;写明只在用户要求时用的,用户没要求就不用。(靠临场想起来会漏掉,流程也就形同虚设。)
28
- 5. **不用软件自带的定时、唤醒或后台等待**,也不手动通知已配置的本地成员;要隔一段时间再看进展用 `checkin`。(本轮结束即执行结束,之后回来的结果无法提交;自带唤醒还会和程序投递并发续接同一会话。)
28
+ 5. **软件自带的定时只在 Claude Code 原窗口里用**:你在 Claude Code 原窗口里主持、且房主为本房间勾选了主持人权限“推进方式”(与 `checkin` 同一项)时,可以用它自带的定时(CronCreate)隔一段时间回来看,到点那一轮的结果作为“定时回报”收进房间,可以派活(计入你上一次工作所在任务链的轮数上限,用满要用户批准);没有要处理的就直接结束、不发消息;不再需要时用 CronDelete 删掉。用户停止你或“全部停止”之后,之前设的定时不再收进房间,要继续就在之后的房间任务里重新设。没勾选这一项时自带定时的结果不进房间,也不能用 `checkin`,要回来看就请用户安排。其他情况要隔一段时间再看进展用 `checkin`。不用软件自带的唤醒或后台等待,也不手动通知已配置的本地成员。(只有原窗口的会话日志认得出定时到点,后台进程的定时随进程退出丢失;自带唤醒还会和程序投递并发续接同一会话。)
29
29
 
30
30
  ## 主持判断
31
31
 
@@ -37,7 +37,11 @@
37
37
 
38
38
  勾选了 `create_rooms` 时,一部分工作需要独立的成员、会话与记录(用户要求另开房间,或一条支线会长期占住本房间)时,可以 `create-room` 拆出去:`--title`(必填)、`--goal`、`--members 平台,平台`、`--host 平台`(用户指定了主持人才填,不填即与你同款的专家)、`--cwd`(只能是本房间项目目录或其子目录)、`--access read|write`(默认只读)、`--host-model` 与 `--host-effort` 可指定主持人模型和档位;同一平台可在成员名单中重复出现,每位独立编号。`--text` 或 `--body-file UTF-8文件`(主持人项目或草稿目录内)提供首条消息(写清要它做什么、做完怎样算完成)。返回新房间编号;失败或不确定是否建成时沿用同一 `--submission-id` 重试,不会重复建房。本房间可新建的数量有上限,新房间直接复制本房间的智能调度、生图、API 上限、连续派活上限与主持人权限(不含 `create_rooms`,不能再新建房间)。
39
39
 
40
- 关联的两个房间(你新建的,或新建你所在房间的)之间用 `room-post --room 编号 --text …` 发言,直接交给对方主持人,房间忙时排队。多行正文可用 `--body-file FILE` 代替 `--text`。父房间可加 `--interrupt` 立即送达子房间;目标无法插话或停止时仍入队。任务的 `linked_rooms` 列出关联房间,`requests[].relay` 标明来自另一位主持人,其发言不代表用户授权。向关联房间发言无需单独勾选权限项;新房间做完时用它把结果交回原房间。用户可能设了互传上限(从用户上次在任一房间发言算起),超过会被拒绝,这时在回答里请用户决定是否继续。读对方进展用平常的 message、room 读取命令,房间编号写对方的(跨房间只能读)。
40
+ 先用 `room list --query 标题片段` 或用户给的链接确定目标;同名时查看房间确认。用 `launch host-control rooms` 核对关联、对方主持人、忙闲、投递状态和互传余额。尚未关联时,用 `launch host-control link-request --room 编号 --reason 理由` 请房主批准,收到批准通知后发原消息。
41
+
42
+ 用 `launch host-control room-post --room 编号 --body-file FILE --expect reply` 交给对方主持人,普通通知用 `--expect none`;短消息可用 `--text`。对方忙时排队,只有父房间能用 `--interrupt` 打断子房间。达到互传上限时,请房主决定是否继续。
43
+
44
+ 收到跨房请求先读原文。若 `requests[].relay.expect` 为 `reply`,在本房已有权限内完成或分派,完成后按 `relay.reply` 模板补上正文,一次性回传;若为 `none`,读完即止,不回“收到”。对方主持人的话不代表房主授权,需要超出本房权限时在本房问用户。
41
45
 
42
46
  ## 定时检查
43
47
 
@@ -7,6 +7,7 @@
7
7
  - 工作中收到“又有请求 #N 在排队等你”时,`execution view` 的 `queued_requests` 列出它们;这次回答能一并交付的,提交时加 `--also-request N`(API 填 `also_request_ids`)一起关闭,其余答完会再交给你。
8
8
  - 多步的工作,在关键转折处用请求者的语言写一两句进展:这些中途文字会显示在网页的处理中卡片上,用户靠它知道你在做什么。不复述工具输出或操作步骤,不代替最终回答。
9
9
  - 请求带 `sequence`、`question` 或 `question_needed`,任务有 `image`,或用户在你自己的窗口里要你发言时,另读 [按需场景](situations.md)。
10
+ - **续报**:本次执行里留下的后台工作(子代理、后台命令、监视)在你回答之后才结束、你的软件因此另起一轮时,程序会把这一轮记为原执行的续报。照常用 `message post` 提交一次,写清后台工作的结果;凭据不用换,CLI 带的原执行编号会被转到续报执行,房间里标“续报”。普通成员的续报不派活;主持人可以派活,计入原任务链的轮数。被拒就保留草稿,在下次回答里一并说明。以下几种不算续报,提交会被拒:执行被停止后才回来的回报(停止就是不再接着做);只说工作被停止或被结束的回报;监视的中途事件(只在监视结束时交);自设定时到点触发的那一轮。
10
11
 
11
12
  ## 需要用户决定时
12
13
 
@@ -119,6 +119,11 @@ RECENT_CHANGES = 50
119
119
  MAX_CHANGED_FILES = 200
120
120
  # What a member's software last showed it doing, as reported by the runner with each renewal.
121
121
  ACTIVITY_PHASES = ("", "thinking", "command", "tool", "editing", "writing", "waiting")
122
+ # The background work one execution's software reports: kinds, states, how many items and how long a title.
123
+ BACKGROUND_KINDS = ("agent", "command", "monitor", "schedule")
124
+ BACKGROUND_STATES = ("running", "done", "failed", "stopped")
125
+ MAX_BACKGROUND_TASKS = 20
126
+ MAX_BACKGROUND_TITLE = 120
122
127
  # Progress notes per execution, their length, and how many one renewal may carry.
123
128
  MAX_EXECUTION_NOTES = 50
124
129
  MAX_NOTE_LENGTH = 500
@@ -171,7 +176,7 @@ TERMINAL = ("completed", "cancelled", "failed")
171
176
  # A queued member has been asked once its request for that message exists.
172
177
  QUEUE_ASKED = "EXISTS(SELECT 1 FROM member_requests r WHERE r.message_id={row}.message_id AND r.member_id={row}.member_id)"
173
178
  SESSION_MODES = ("new", "borrowed")
174
- FREE_OPERATIONS = ("messages", "attachments", "move", "folder", "rename", "archive", "restore", "delete", "auto-destroy")
179
+ FREE_OPERATIONS = ("messages", "attachments", "move", "folder", "detach", "pin", "rename", "archive", "restore", "delete", "auto-destroy")
175
180
  MEMBER_FIELDS = ("id", "name", "adapter", "role", "status", "access", "session_mode", "read_until")
176
181
  EXECUTION_FIELDS = ("id", "member_id", "status", "session_id", "lease_until", "created_at", "finished_at", "result",
177
182
  "activity", "activity_at", "paused_at", "model", "effort")
@@ -807,6 +812,31 @@ def label_members(connection, room_id, token, payload):
807
812
  connection.execute("DELETE FROM member_labels WHERE room_id=? AND name=?", (room_id, name))
808
813
  return {"labels": member_labels(connection, room_id)}
809
814
 
815
+ def background_tasks(connection, execution_id):
816
+ """The background work list the runner last reported for one execution ([] before any report)."""
817
+ row = connection.execute("SELECT tasks FROM execution_background_tasks WHERE execution_id=?", (execution_id,)).fetchone()
818
+ return json.loads(row["tasks"]) if row else []
819
+
820
+
821
+ def checked_background_tasks(payload):
822
+ """Validate a reported background work list; times are milliseconds, 0 when unknown."""
823
+ tasks = payload.get("tasks")
824
+ if not isinstance(tasks, list) or len(tasks) > MAX_BACKGROUND_TASKS:
825
+ raise ValueError(Text("tasks 须为最多 {value1} 项的列表", value1=MAX_BACKGROUND_TASKS))
826
+ checked = []
827
+ for item in tasks:
828
+ if (not isinstance(item, dict) or not isinstance(item.get("id"), str) or not item["id"] or len(item["id"]) > MAX_BACKGROUND_TITLE
829
+ or item.get("kind") not in BACKGROUND_KINDS or item.get("state") not in BACKGROUND_STATES
830
+ or not isinstance(item.get("title", ""), str) or len(item.get("title", "")) > MAX_BACKGROUND_TITLE
831
+ or not isinstance(item.get("schedule", ""), str) or len(item.get("schedule", "")) > MAX_BACKGROUND_TITLE
832
+ or any(type(item.get(field, 0)) is not int or item.get(field, 0) < 0 for field in ("started_at", "ended_at", "next_at"))):
833
+ raise ValueError(Text("tasks 每项须为 {{id, kind: {value1}, title, state: {value2}, started_at, ended_at, next_at, schedule}}",
834
+ value1="、".join(BACKGROUND_KINDS), value2="、".join(BACKGROUND_STATES)))
835
+ checked.append({field: item.get(field, default) for field, default in (("id", ""), ("kind", ""), ("title", ""), ("state", ""),
836
+ ("started_at", 0), ("ended_at", 0), ("next_at", 0), ("schedule", ""))})
837
+ return checked
838
+
839
+
810
840
  def note_count(connection, execution_id):
811
841
  """How many progress notes an execution has; the texts are read separately so room views stay small."""
812
842
  return connection.execute("SELECT COUNT(*) FROM execution_notes WHERE execution_id=?", (execution_id,)).fetchone()[0]
@@ -1050,7 +1080,10 @@ def recent_executions(connection, room_id, span=None):
1050
1080
  (SELECT denials FROM execution_denials WHERE execution_id=e.id) AS denials,{CAPABILITY_COLUMNS},
1051
1081
  (SELECT failure_class FROM execution_failures WHERE execution_id=e.id) AS failure_class,
1052
1082
  (SELECT json_object('created_at',created_at) FROM late_answers WHERE execution_id=e.id) AS late_answer,
1053
- {BACKGROUND_SQL} AS background
1083
+ (SELECT source_id FROM execution_followups WHERE execution_id=e.id) AS followup_of,
1084
+ EXISTS(SELECT 1 FROM execution_schedules WHERE execution_id=e.id) AS scheduled,
1085
+ {BACKGROUND_SQL} AS background,
1086
+ (SELECT tasks FROM execution_background_tasks WHERE execution_id=e.id) AS background_tasks
1054
1087
  FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.room_id=?"""
1055
1088
  if span:
1056
1089
  rows = connection.execute(f"SELECT * FROM ({query}) WHERE layout_after>? AND layout_after<=? ORDER BY id DESC",
@@ -1077,6 +1110,8 @@ def recent_executions(connection, room_id, span=None):
1077
1110
  "notes": row["note_count"], "steps": row["step_count"], "commands": row["command_count"], "edits": row["edit_count"], "denials": json.loads(row["denials"] or "[]"), "failure_class": row["failure_class"] or "",
1078
1111
  "capabilities": reported_capabilities(row), "stop_result": row["stop_result"] or "",
1079
1112
  "late_answer": json.loads(row["late_answer"]) if row["late_answer"] else None, "background": bool(row["background"]),
1113
+ "followup_of": row["followup_of"], "scheduled": bool(row["scheduled"]),
1114
+ "background_tasks": json.loads(row["background_tasks"]) if row["background_tasks"] else [],
1080
1115
  "retried": bool(row["retried"]), "replaces_execution_id": row["replaces_execution_id"], "line": line,
1081
1116
  "interjections": execution_interjections(connection, row["id"], row["status"]),
1082
1117
  "retry": execution_retry(connection, row["id"])})
@@ -1236,7 +1271,8 @@ def free_view(connection, room_id):
1236
1271
  member["execution"] = public_execution(latest)
1237
1272
  if latest:
1238
1273
  member["execution"]["texts"] = execution_texts(connection, latest["id"])
1239
- member["execution"].update(capabilities=reported_capabilities(latest), stop_result=latest["stop_result"] or "")
1274
+ member["execution"].update(capabilities=reported_capabilities(latest), stop_result=latest["stop_result"] or "",
1275
+ background_tasks=background_tasks(connection, latest["id"]))
1240
1276
  if latest and latest["status"] in ACTIVE:
1241
1277
  member["execution"]["stale"] = latest["lease_until"] <= now
1242
1278
  member["execution"]["notes"] = note_count(connection, latest["id"])
@@ -1569,8 +1605,9 @@ def check_answer(connection, room_id, member, payload):
1569
1605
  if not row or row["member_id"] != member["id"]:
1570
1606
  raise PermissionError(Text("执行编号不属于本成员"))
1571
1607
  if row["status"] == "completed":
1572
- # The host dispatched with keep_working and went on in the same turn: its answer belongs to where that turn went.
1573
- # A continuation stopped or failed since takes the answer as that one's late answer, which ends its hold.
1608
+ # The host dispatched with keep_working and went on in the same turn, or background work this execution left
1609
+ # reported after it completed (a follow-up): the answer belongs to where that turn went. A continuation stopped or
1610
+ # failed since takes the answer as that one's late answer, which ends its hold.
1574
1611
  row = continuation_end(connection, row)
1575
1612
  execution_id = payload["execution_id"] = row["id"]
1576
1613
  revived = revive_failed(connection, room_id, row) if row["status"] == "failed" else None
@@ -1611,10 +1648,13 @@ def check_keep_working(member, payload):
1611
1648
 
1612
1649
 
1613
1650
  def continuation_end(connection, row):
1614
- """The last execution a host's `keep_working` moved this answered execution's turn onto, in whatever state it is now;
1615
- the row itself when its turn did not move."""
1651
+ """The last execution a host's `keep_working` moved this answered execution's turn onto, or a follow-up (续报) opened
1652
+ after it completed, in whatever state it is now; the row itself when its turn did not move. The member's software
1653
+ still holds the first execution's credential, so its answer goes where the turn went."""
1616
1654
  while row["status"] == "completed":
1617
- link = connection.execute("SELECT next_id FROM execution_continuations WHERE execution_id=?", (row["id"],)).fetchone()
1655
+ link = connection.execute("""SELECT next_id FROM execution_continuations WHERE execution_id=?
1656
+ UNION ALL SELECT execution_id FROM execution_followups WHERE source_id=?
1657
+ UNION ALL SELECT execution_id FROM execution_schedules WHERE source_id=?""", (row["id"], row["id"], row["id"])).fetchone()
1618
1658
  if not link:
1619
1659
  break
1620
1660
  row = connection.execute("SELECT * FROM member_executions WHERE id=?", (link[0],)).fetchone()
@@ -3076,9 +3116,12 @@ def stop_room_work(connection, room_id, reason, cancel_reason):
3076
3116
  finish_execution(connection, row["id"], "cancelled", reason, "cancelled", cancel_reason)
3077
3117
  record_cancel_reasons(connection, "room_id=? AND status='pending'", (room_id,), cancel_reason)
3078
3118
  connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND status='pending'", (room_id,))
3079
- # Stopping everything also stops a goal, the host's own "continue" or its timed check-in from waking the host again.
3119
+ # Stopping everything also stops a goal, the host's own "continue" or its timed check-in from waking the host again,
3120
+ # and a schedule the host set in its own software from coming in (`open_scheduled`).
3080
3121
  connection.execute("DELETE FROM free_host_continues WHERE room_id=?", (room_id,))
3081
3122
  connection.execute("DELETE FROM free_host_checkins WHERE room_id=?", (room_id,))
3123
+ connection.execute("""INSERT OR REPLACE INTO member_schedule_stops (member_id,stopped_at)
3124
+ SELECT id,? FROM room_members WHERE room_id=?""", (int(time.time() * 1000), room_id))
3082
3125
  connection.execute("UPDATE room_goals SET status='paused',paused_at=? WHERE room_id=? AND status='active'", (int(time.time()), room_id))
3083
3126
  # A relay waiting for the owner has nothing running to cancel; stopping everything ends it too.
3084
3127
  connection.execute("UPDATE free_sequences SET status='stopped' WHERE room_id=? AND status='checkpoint' AND handoff_request=0", (room_id,))
@@ -3200,6 +3243,7 @@ def inbox(connection, room_id, token):
3200
3243
  member_view["label"] = shown.get(row["name"], row["name"])
3201
3244
  member_view["review_capability"] = review_capability(connection, room_id, row["id"], token)
3202
3245
  member_view["held_until"] = held_until(connection, row["id"])
3246
+ member_view["schedule_stopped_at"] = schedule_stopped_at(connection, row["id"])
3203
3247
  member_view["quota_until"] = quota_held_until(connection, row["id"])
3204
3248
  # The runner compares this with its adapter's effect and reports a change.
3205
3249
  reported = connection.execute("SELECT rewind,image_model FROM member_capabilities WHERE member_id=?", (row["id"],)).fetchone()
@@ -3214,6 +3258,10 @@ def inbox(connection, room_id, token):
3214
3258
  executions = [{**public_execution(row), "member": row["name"], "retry": execution_retry(connection, row["id"]),
3215
3259
  "continues": (connection.execute("SELECT execution_id FROM execution_continuations WHERE next_id=?",
3216
3260
  (row["id"],)).fetchone() or [None])[0],
3261
+ # A follow-up (续报) names the execution it follows, so a restarted runner still knows it for one.
3262
+ "followup_of": (connection.execute("SELECT source_id FROM execution_followups WHERE execution_id=?",
3263
+ (row["id"],)).fetchone() or [None])[0],
3264
+ "scheduled": bool(connection.execute("SELECT 1 FROM execution_schedules WHERE execution_id=?", (row["id"],)).fetchone()),
3217
3265
  "interjections": [dict(item) for item in connection.execute(
3218
3266
  """SELECT i.id,i.text,COALESCE(a.author,'') AS author FROM execution_interjections i
3219
3267
  LEFT JOIN interjection_authors a ON a.interjection_id=i.id WHERE i.execution_id=? AND i.status='pending' ORDER BY i.id""",
@@ -3458,9 +3506,147 @@ def reserve_execution(connection, room_id, token, payload):
3458
3506
  (room_id, payload.get("member_id"))).fetchone()
3459
3507
  if not member:
3460
3508
  raise LookupError(Text("成员不存在、已离开或为手动接入"))
3509
+ if payload.get("follows") is not None:
3510
+ return open_followup(connection, room_id, member, payload)
3511
+ if payload.get("scheduled") is not None:
3512
+ return open_scheduled(connection, room_id, member, payload)
3461
3513
  return open_execution(connection, room_id, member, payload)
3462
3514
 
3463
3515
 
3516
+ MAX_FOLLOWUP_REPORTS = 20
3517
+ MAX_FOLLOWUP_ID = 120
3518
+ MAX_FOLLOWUP_SUMMARY = 300
3519
+ # Background report states that bring no result of their own.
3520
+ FOLLOWUP_ENDED_ONLY = ("stopped", "killed")
3521
+
3522
+
3523
+ def followup_reports(payload):
3524
+ """The background reports a follow-up execution was opened on, as [{id, status, summary}], checked and trimmed."""
3525
+ reports = payload.get("reports", [])
3526
+ if not isinstance(reports, list) or len(reports) > MAX_FOLLOWUP_REPORTS or any(
3527
+ not isinstance(item, dict) or not isinstance(item.get("id"), str) or not item["id"]
3528
+ or not isinstance(item.get("status", ""), str) or not isinstance(item.get("summary", ""), str) for item in reports):
3529
+ raise ValueError(Text("reports 须为最多 {value1} 项的 {{id, status, summary}} 列表", value1=MAX_FOLLOWUP_REPORTS))
3530
+ return [{"id": item["id"][:MAX_FOLLOWUP_ID], "status": item.get("status", "")[:40],
3531
+ "summary": item.get("summary", "")[:MAX_FOLLOWUP_SUMMARY]} for item in reports]
3532
+
3533
+
3534
+ def open_followup(connection, room_id, member, payload):
3535
+ """Open a follow-up execution (续报, user 2026-11-25): background work the ended execution `follows` left running
3536
+ reported, and the member's software started a new turn on it. Its request hangs on that execution's answer (a program
3537
+ notice when it has none) in the same task chain, so the answer has a source and a host's dispatch from it counts
3538
+ against the chain's rounds; a member's `to` stays a suggestion as always. Only a completed execution of this member
3539
+ (a stopped one is not carried on, as `stopped_executions` says), once: a later report follows the follow-up. Reports
3540
+ that only say the work was stopped or killed (a server Claude Code ended at its timeout) bring nothing new."""
3541
+ source_id = payload.get("follows")
3542
+ if type(source_id) is not int:
3543
+ raise ValueError(Text("follows 须为原执行编号"))
3544
+ reports = followup_reports(payload)
3545
+ source = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, source_id)).fetchone()
3546
+ if not source or source["member_id"] != member["id"]:
3547
+ raise LookupError(Text("原执行不存在或不属于该成员"))
3548
+ if source["status"] in ("cancelled", "failed"):
3549
+ # A stopped, withdrawn or rewound execution is not carried on, nor answered for later (`stopped_executions`).
3550
+ raise FileExistsError(Text("原执行 E{value1} 已被停止或判为失败,不再接收续报", value1=source_id))
3551
+ if source["status"] != "completed":
3552
+ raise FileExistsError(Text("原执行 E{value1} 仍在进行,后台回报照常交给它", value1=source_id))
3553
+ if reports and all(item["status"] in FOLLOWUP_ENDED_ONLY for item in reports):
3554
+ raise FileExistsError(Text("这批回报只说后台工作被停止或被结束,没有新结果,不开续报"))
3555
+ taken = connection.execute("SELECT execution_id FROM execution_followups WHERE source_id=?", (source_id,)).fetchone()
3556
+ if taken:
3557
+ raise FileExistsError(Text("原执行 E{value1} 已有续报 E{value2},之后的回报接在续报上", value1=source_id, value2=taken[0]))
3558
+ if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
3559
+ (member["id"],)).fetchone():
3560
+ raise FileExistsError(Text("该成员已有进行中的执行;同一会话不并发续接"))
3561
+ origin = connection.execute("""SELECT chain_id,created_by FROM member_requests WHERE execution_id=? ORDER BY id DESC LIMIT 1""",
3562
+ (source_id,)).fetchone()
3563
+ if not origin:
3564
+ raise LookupError(Text("原执行没有关联的请求"))
3565
+ answer = connection.execute("SELECT MAX(answer_id) FROM member_requests WHERE execution_id=?", (source_id,)).fetchone()[0]
3566
+ anchor = answer or followup_notice(connection, room_id, member, source_id)
3567
+ now = int(time.time())
3568
+ execution_id = connection.execute("""INSERT INTO member_executions (room_id,member_id,client_id,session_id,lease_until,created_at,cwd,model,effort)
3569
+ VALUES (?,?,?,?,?,?,?,?,?)""", (room_id, member["id"], str(payload["client_id"]), source["session_id"], now + LEASE_SECONDS, now,
3570
+ str(payload.get("cwd") or source["cwd"] or "")[:MAX_PATH_LENGTH], source["model"], source["effort"])).lastrowid
3571
+ connection.execute("""INSERT INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at,status,execution_id)
3572
+ VALUES (?,?,?,?,'followup',?,?,'delivering',?)""", (room_id, member["id"], anchor, origin["chain_id"], origin["created_by"], now, execution_id))
3573
+ connection.execute("INSERT INTO execution_followups (execution_id,source_id,reports) VALUES (?,?,?)",
3574
+ (execution_id, source_id, json.dumps(reports, ensure_ascii=False)))
3575
+ return execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (execution_id,)).fetchone())
3576
+
3577
+
3578
+ MAX_SCHEDULE_FIELD = 120
3579
+ MAX_SCHEDULE_PROMPT = 300
3580
+
3581
+
3582
+ class ScheduleStopped(FileExistsError):
3583
+ """A schedule set before the owner last stopped the member: it no longer comes in (code `schedule_stopped`)."""
3584
+
3585
+ details = {"code": "schedule_stopped"}
3586
+
3587
+
3588
+ def schedule_stopped_at(connection, member_id):
3589
+ """When the owner last stopped this member, in milliseconds, or 0."""
3590
+ row = connection.execute("SELECT stopped_at FROM member_schedule_stops WHERE member_id=?", (member_id,)).fetchone()
3591
+ return row[0] if row else 0
3592
+
3593
+
3594
+ def open_scheduled(connection, room_id, member, payload):
3595
+ """Open a scheduled execution (定时回报, user 2026-11-25 #10925, option B): a schedule the host set in its own software
3596
+ fired and started a turn there. Only the host's: the host waking itself is within its full control, while a member
3597
+ waking itself would bypass red line 3. Its request hangs on a program notice, in the task chain of the host's latest
3598
+ execution (as a follow-up's does), so a recurring schedule's dispatches all count against that chain's rounds and
3599
+ the owner approves going past them (user 2026-11-25 #10989); only a host with no earlier work starts a chain at the
3600
+ notice. A schedule set (`set_at`, ms) no later than the owner last stopped the member is refused with code
3601
+ `schedule_stopped`: the owner's stop also stops the host waking itself. Refused while the member has a live
3602
+ execution: that one takes the turn."""
3603
+ scheduled = payload.get("scheduled")
3604
+ if (not isinstance(scheduled, dict) or not isinstance(scheduled.get("id"), str) or not scheduled["id"]
3605
+ or any(not isinstance(scheduled.get(field, ""), str) for field in ("schedule", "prompt"))):
3606
+ raise ValueError(Text("scheduled 须为 {{id, schedule, prompt}}"))
3607
+ if member["role"] != "host":
3608
+ raise FileExistsError(Text("只有主持人自设定时的结果会收进房间,普通成员的定时只显示"))
3609
+ set_at, stopped = scheduled.get("set_at"), schedule_stopped_at(connection, member["id"])
3610
+ if set_at is not None and (type(set_at) is not int or set_at < 0):
3611
+ raise ValueError(Text("scheduled.set_at 须为设定时的毫秒时间"))
3612
+ if stopped and (set_at is None or set_at <= stopped):
3613
+ raise ScheduleStopped(Text("用户在这个定时设好之后停止过主持人,它到点的结果不再收进房间;主持人在新的房间任务里重新设定时后才会再收"))
3614
+ if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
3615
+ (member["id"],)).fetchone():
3616
+ raise FileExistsError(Text("该成员已有进行中的执行;同一会话不并发续接"))
3617
+ schedule, prompt = scheduled.get("schedule", "")[:MAX_SCHEDULE_FIELD], scheduled.get("prompt", "")[:MAX_SCHEDULE_PROMPT]
3618
+ source = connection.execute("SELECT MAX(id) FROM member_executions WHERE member_id=?", (member["id"],)).fetchone()[0]
3619
+ origin = connection.execute("SELECT chain_id FROM member_requests WHERE execution_id=? AND chain_id>0 ORDER BY id DESC LIMIT 1",
3620
+ (source,)).fetchone() if source else None
3621
+ text = Text("主持人自设的定时到点({value1}):{value2}", value1=schedule or scheduled["id"], value2=prompt)
3622
+ notice = connection.execute("INSERT INTO messages(room_id,author,text,source,submission_id,created_at) VALUES(?,?,?,?,?,?)",
3623
+ (room_id, NOTICE_AUTHOR, str(text), "notice", f"notice-scheduled:{payload['client_id']}"[:100],
3624
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))).lastrowid
3625
+ save_text(connection, "message", notice, "text", text)
3626
+ connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,?,?)", (notice, "notice", NOTICE_AUTHOR))
3627
+ now = int(time.time())
3628
+ execution_id = connection.execute("""INSERT INTO member_executions (room_id,member_id,client_id,lease_until,created_at,cwd)
3629
+ VALUES (?,?,?,?,?,?)""", (room_id, member["id"], str(payload["client_id"]), now + LEASE_SECONDS, now,
3630
+ str(payload.get("cwd") or "")[:MAX_PATH_LENGTH])).lastrowid
3631
+ connection.execute("""INSERT INTO member_requests (room_id,member_id,message_id,chain_id,purpose,created_by,created_at,status,execution_id)
3632
+ VALUES (?,?,?,?,'scheduled','system',?,'delivering',?)""", (room_id, member["id"], notice, origin[0] if origin else notice, now, execution_id))
3633
+ connection.execute("INSERT INTO execution_schedules (execution_id,source_id,task_id,schedule) VALUES (?,?,?,?)",
3634
+ (execution_id, source, scheduled["id"][:MAX_SCHEDULE_FIELD], schedule))
3635
+ return execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (execution_id,)).fetchone())
3636
+
3637
+
3638
+ def followup_notice(connection, room_id, member, source_id):
3639
+ """The program notice a follow-up of an execution that left no answer (it ended on program notices alone) hangs on."""
3640
+ name = member_display_names(connection, room_id).get(member["name"], member["name"])
3641
+ text = Text("{value1} 在执行 E{value2} 里留下的后台任务有了回报,以下是它的续报。", value1=name, value2=source_id)
3642
+ message_id = connection.execute("INSERT INTO messages(room_id,author,text,source,submission_id,created_at) VALUES(?,?,?,?,?,?)",
3643
+ (room_id, NOTICE_AUTHOR, str(text), "notice", f"notice-followup:{source_id}",
3644
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))).lastrowid
3645
+ save_text(connection, "message", message_id, "text", text)
3646
+ connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,?,?)", (message_id, "notice", NOTICE_AUTHOR))
3647
+ return message_id
3648
+
3649
+
3464
3650
  def claim_execution(connection, room_id, member, payload):
3465
3651
  """An external member claims its own open requests as one execution; a retried client_id returns the same one."""
3466
3652
  begin_write(connection)
@@ -3915,6 +4101,12 @@ def execution_action(connection, room_id, execution_id, token, payload, member=N
3915
4101
  ON CONFLICT(execution_id) DO UPDATE SET stoppable=excluded.stoppable,progress=excluded.progress,steer=excluded.steer,
3916
4102
  resume=excluded.resume""", (execution_id, room_id, int(payload["stoppable"]), int(payload["progress"]),
3917
4103
  int(payload.get("steer", False)), int(payload.get("resume", False))))
4104
+ elif action == "background_tasks":
4105
+ # The latest list replaces the earlier one; it may arrive just after the execution ended, with the final states.
4106
+ tasks = checked_background_tasks(payload)
4107
+ connection.execute("""INSERT INTO execution_background_tasks (execution_id,room_id,tasks,updated_at) VALUES (?,?,?,?)
4108
+ ON CONFLICT(execution_id) DO UPDATE SET tasks=excluded.tasks,updated_at=excluded.updated_at""",
4109
+ (execution_id, room_id, json.dumps(tasks, ensure_ascii=False), now))
3918
4110
  elif action == "interjection":
3919
4111
  # The runner's report on one interjection: it reached the software, or why it could not; a repeated report changes nothing.
3920
4112
  record_interjection_result(connection, room_id, execution_id, payload, now)
@@ -3991,12 +4183,15 @@ def execution_action(connection, room_id, execution_id, token, payload, member=N
3991
4183
  finish_execution(connection, execution_id, "failed", reason, "failed")
3992
4184
  settle_batches(connection, room_id)
3993
4185
  elif action == "quiet":
3994
- # A program notice (failure reminder, timed check, hand-back) with nothing to handle ends without a message.
4186
+ # A program notice (failure reminder, timed check, hand-back) with nothing to handle ends without a message; so
4187
+ # does a follow-up whose turn brought nothing to say (the program opened it, nobody asked for an answer).
3995
4188
  purposes = {item[0] for item in connection.execute(
3996
4189
  "SELECT purpose FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,))}
3997
- if purposes != {"notice"}:
3998
- raise ValueError(Text("只有只带程序通知的执行可以不回答就结束"))
3999
- finish_execution(connection, execution_id, "completed", Text("没有需要处理的事,未发消息"), "completed")
4190
+ if not purposes or not purposes <= {"notice", "followup", "scheduled"}:
4191
+ raise ValueError(Text("只有只带程序通知、续报或定时回报的执行可以不回答就结束"))
4192
+ finish_execution(connection, execution_id, "completed", Text("后台回报这一轮没有交来新内容,未发消息") if "followup" in purposes
4193
+ else Text("定时这一轮没有需要处理的事,未发消息") if "scheduled" in purposes
4194
+ else Text("没有需要处理的事,未发消息"), "completed")
4000
4195
  settle_batches(connection, room_id)
4001
4196
  elif action == "release":
4002
4197
  # Only for proven non-delivery: the requests return to the queue unchanged.
@@ -4134,6 +4329,9 @@ def interrupt_member(connection, room_id, member_id, token, by_host=""):
4134
4329
  pause_queue(connection, room_id)
4135
4330
  reason = Text("主持人 {host} 打断", host=by_host) if by_host else Text("用户打断")
4136
4331
  stop_member_work(connection, member_id, reason, "user_stop", keep_pending=True)
4332
+ if not by_host:
4333
+ connection.execute("INSERT OR REPLACE INTO member_schedule_stops (member_id,stopped_at) VALUES (?,?)",
4334
+ (member_id, int(time.time() * 1000)))
4137
4335
  settle_batches(connection, room_id)
4138
4336
  return free_view(connection, room_id)
4139
4337
 
@@ -4425,9 +4623,78 @@ def record_relay_send(connection, room_id, token, payload):
4425
4623
  VALUES(?,?,?,'room_relay_sent',?,?)""", (room_id, NOTICE_AUTHOR, text, identifier,
4426
4624
  time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))).lastrowid
4427
4625
  connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,'notice',?)", (message_id, NOTICE_AUTHOR))
4626
+ if queued and payload.get("target_submission_id"):
4627
+ delivered = connection.execute("SELECT id FROM messages WHERE room_id=? AND submission_id=?",
4628
+ (target, payload["target_submission_id"])).fetchone()
4629
+ sent = delivered[0] if delivered else None
4630
+ state = "queued" if queued and not sent else "delivered"
4631
+ if sent and connection.execute("SELECT 1 FROM message_relays WHERE reply_to=? AND source_room_id=?", (sent, target)).fetchone():
4632
+ state = "replied"
4428
4633
  connection.execute("""INSERT INTO room_relay_sends
4429
- (message_id,room_id,target_room_id,target_message_id,queued_id,interrupted,host,member) VALUES (?,?,?,?,?,?,?,?)""",
4430
- (message_id, room_id, target, sent, queued, interrupted, host, member))
4634
+ (message_id,room_id,target_room_id,target_message_id,queued_id,interrupted,host,member,state) VALUES (?,?,?,?,?,?,?,?,?)""",
4635
+ (message_id, room_id, target, sent, queued, interrupted, host, member, state))
4636
+ return {"message_id": message_id, "duplicate": False}
4637
+
4638
+
4639
+ # What a host did through `launch host-control`, one sentence each; `{detail}` is the step's own value (text, number).
4640
+ HOST_ACTION_TEXTS = {
4641
+ "stop": "主持人 {host} 打断了 {member}",
4642
+ "stop-all": "主持人 {host} 停止了房间里的全部工作",
4643
+ "steer": "主持人 {host} 向 {member} 插话:{detail}",
4644
+ "retry": "主持人 {host} 重试了执行 #{detail}",
4645
+ "withdraw": "主持人 {host} 撤回了 #{detail} 派出的活",
4646
+ "order": "主持人 {host} 调整了发言顺序:{detail}",
4647
+ "invite": "主持人 {host} 邀请 {member} 加入",
4648
+ "away": "主持人 {host} 让 {member} 暂离",
4649
+ "remove": "主持人 {host} 移除了 {member}",
4650
+ "back": "主持人 {host} 请回了 {member}",
4651
+ "access:read": "主持人 {host} 把 {member} 的项目权限改为只读",
4652
+ "access:write": "主持人 {host} 把 {member} 的项目权限改为可写",
4653
+ "adapter": "主持人 {host} 把 {member} 的接入方式改为 {detail}",
4654
+ "label": "主持人 {host} 把 {member} 改名为 {detail}",
4655
+ "description": "主持人 {host} 更新了 {member} 的描述",
4656
+ "checkin": "主持人 {host} 设定每 {detail} 分钟定时检查",
4657
+ "checkin:off": "主持人 {host} 关闭了定时检查",
4658
+ "discussion:start": "主持人 {host} 开启了讨论:{detail}",
4659
+ "discussion:pause": "主持人 {host} 暂停了讨论",
4660
+ "discussion:resume": "主持人 {host} 恢复了讨论",
4661
+ "discussion:end": "主持人 {host} 结束了讨论",
4662
+ "goal:start": "主持人 {host} 开启了 Goal:{detail}",
4663
+ "goal:pause": "主持人 {host} 暂停了 Goal",
4664
+ "goal:resume": "主持人 {host} 恢复了 Goal",
4665
+ "goal:end": "主持人 {host} 结束了 Goal",
4666
+ }
4667
+ HOST_ACTION_DETAIL_LIMIT = 2000
4668
+
4669
+
4670
+ def record_host_action(connection, room_id, token, host, payload):
4671
+ """Leave a one-line record of a control the host ran through `launch host-control`, so the owner sees in the
4672
+ message flow what the host did to members and the room. Nobody is woken.
4673
+
4674
+ The host's name comes from its own credential (`acting_host`), never from the payload; a retry with the same
4675
+ `submission_id` returns the record already there.
4676
+ """
4677
+ require_owner(connection, room_id, token)
4678
+ if not host:
4679
+ raise PermissionError(Text("只有主持人经 host-control 的操作才能留痕"))
4680
+ action, member, detail = payload.get("action"), payload.get("member", ""), payload.get("detail", "")
4681
+ if action not in HOST_ACTION_TEXTS:
4682
+ raise ValueError(Text("主持人操作类型无效"))
4683
+ if not isinstance(member, str) or len(member) > 100 or not isinstance(detail, (str, int)) or len(str(detail)) > HOST_ACTION_DETAIL_LIMIT:
4684
+ raise ValueError(Text("主持人操作留痕的成员或内容无效"))
4685
+ identifier = payload.get("submission_id")
4686
+ if not isinstance(identifier, str) or not re.fullmatch(r"[A-Za-z0-9_-]{8,100}", identifier):
4687
+ raise ValueError(Text("submission_id 必须是 8–100 位字母、数字、下划线或连字符"))
4688
+ begin_write(connection)
4689
+ previous = connection.execute("SELECT id FROM messages WHERE room_id=? AND submission_id=?", (room_id, f"host-action-{identifier}")).fetchone()
4690
+ if previous:
4691
+ return {"message_id": previous[0], "duplicate": True}
4692
+ text = Text(HOST_ACTION_TEXTS[action], host=host, member=member, detail=str(detail))
4693
+ message_id = connection.execute("INSERT INTO messages(room_id,author,text,source,submission_id,created_at) VALUES(?,?,?,?,?,?)",
4694
+ (room_id, NOTICE_AUTHOR, text, "host_action", f"host-action-{identifier}",
4695
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))).lastrowid
4696
+ save_text(connection, "message", message_id, "text", text)
4697
+ connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,?,?)", (message_id, "notice", NOTICE_AUTHOR))
4431
4698
  return {"message_id": message_id, "duplicate": False}
4432
4699
 
4433
4700
 
@@ -4463,6 +4730,14 @@ def record_room_link(connection, room_id, token, payload):
4463
4730
  MAX_RELAY_LIMIT = 100
4464
4731
 
4465
4732
 
4733
+ def relay_count(connection, room_id, source):
4734
+ """Count messages exchanged since the last owner message in either room."""
4735
+ spoke = connection.execute("""SELECT COALESCE(MAX(m.id),0) FROM messages m WHERE m.room_id IN (?,?) AND m.author='用户'
4736
+ AND NOT EXISTS (SELECT 1 FROM message_relays r WHERE r.message_id=m.id)""", (room_id, source)).fetchone()[0]
4737
+ return connection.execute("""SELECT COUNT(*) FROM message_relays r JOIN messages m ON m.id=r.message_id WHERE m.id>?
4738
+ AND ((m.room_id=? AND r.source_room_id=?) OR (m.room_id=? AND r.source_room_id=?))""", (spoke, room_id, source, source, room_id)).fetchone()[0]
4739
+
4740
+
4466
4741
  def check_relay(connection, room_id, relay):
4467
4742
  """Check a message another room's host sends here: the rooms are linked, and the hosts have not passed the limit.
4468
4743
 
@@ -4480,12 +4755,17 @@ def check_relay(connection, room_id, relay):
4480
4755
  raise ValueError(Text("relay.limit 须为 0–100 的整数,0 表示不限"))
4481
4756
  if not connection.execute("SELECT 1 FROM room_links WHERE room_id=? AND other_room_id=?", (room_id, source)).fetchone():
4482
4757
  raise PermissionError(Text("只有互相关联的房间之间才能代主持人发言"))
4758
+ if relay.get("expect", "reply") not in ("reply", "none"):
4759
+ raise ValueError(Text("expect 须为 reply 或 none"))
4760
+ reply_to = relay.get("reply_to")
4761
+ if reply_to is not None and (type(reply_to) is not int or not connection.execute(
4762
+ """SELECT 1 FROM message_relays r JOIN messages m ON m.id=r.message_id
4763
+ WHERE m.room_id=? AND r.source_room_id=? AND r.message_id=? AND r.expect='reply'""",
4764
+ (source, room_id, reply_to)).fetchone()):
4765
+ raise ValueError(Text("只能回复对方发来的、需要回传的消息"))
4483
4766
  if not limit:
4484
4767
  return host
4485
- spoke = connection.execute("""SELECT COALESCE(MAX(m.id),0) FROM messages m WHERE m.room_id IN (?,?) AND m.author='用户'
4486
- AND NOT EXISTS (SELECT 1 FROM message_relays r WHERE r.message_id=m.id)""", (room_id, source)).fetchone()[0]
4487
- passed = connection.execute("""SELECT COUNT(*) FROM message_relays r JOIN messages m ON m.id=r.message_id WHERE m.id>?
4488
- AND ((m.room_id=? AND r.source_room_id=?) OR (m.room_id=? AND r.source_room_id=?))""", (spoke, room_id, source, source, room_id)).fetchone()[0]
4768
+ passed = relay_count(connection, room_id, source)
4489
4769
  if passed >= limit:
4490
4770
  raise FileExistsError(Text("两个房间的主持人自用户上次发言后已互传 {count} 条消息,达到上限;请等用户在任一房间发言后再继续", count=passed))
4491
4771
  return host
@@ -4494,7 +4774,11 @@ def check_relay(connection, room_id, relay):
4494
4774
  def save_message_relay(connection, room_id, message_id, relay):
4495
4775
  """Label an owner-credential message the host of another room sent: `relay = {room_id, host}`."""
4496
4776
  host = check_relay(connection, room_id, relay)
4497
- connection.execute("INSERT INTO message_relays (message_id,source_room_id,host,member) VALUES (?,?,?,?)", (message_id, relay["room_id"], host, relay.get("member", "")))
4777
+ connection.execute("INSERT INTO message_relays (message_id,source_room_id,host,member,expect,reply_to) VALUES (?,?,?,?,?,?)",
4778
+ (message_id, relay["room_id"], host, relay.get("member", ""), relay.get("expect", "reply"), relay.get("reply_to")))
4779
+ if relay.get("reply_to"):
4780
+ connection.execute("""UPDATE room_relay_sends SET state='replied'
4781
+ WHERE room_id=? AND target_room_id=? AND target_message_id=?""", (room_id, relay["room_id"], relay["reply_to"]))
4498
4782
 
4499
4783
 
4500
4784
  def record_model_change(connection, room_id, member, payload):
@@ -9,6 +9,9 @@ whole room: no open request, turn waiting or running discussion. Each release of
9
9
  message path with its own submission_id, so a repeated drain finds the posted message and only moves on. A failed post
10
10
  keeps the row with its reason and holds the queue; the owner's stop pauses it. The owner may send one at once, edit,
11
11
  delete, reorder or resume the queue.
12
+
13
+ A linked room's host message (`relay`) names the room's host as it stands when the queue is read (user 2026-11-25, #10464):
14
+ it waits only for that host, not for the whole room, and a host replaced meanwhile is not waited for.
12
15
  """
13
16
 
14
17
  import json
@@ -58,8 +61,8 @@ def queue_view(connection, room_id):
58
61
  COALESCE(NULLIF(?,''),(SELECT name FROM room_members WHERE room_id=? AND role='host' AND status='active')) AS relay_member""",
59
62
  (source, room_id, source, relay.get("member", ""), source)).fetchone()
60
63
  item.update(relay_room=source, relay_host=relay["host"], **dict(details))
61
- if named_members(connection, room_id, payload) is not None:
62
- item["to"] = payload["to"]
64
+ if (named := named_members(connection, room_id, payload)) is not None:
65
+ item["to"] = list(named)
63
66
  if payload.get("message_id"):
64
67
  item.update(message_id=payload["message_id"], waiting_for=payload.get("to", []))
65
68
  item["send_mode"] = send_mode(connection, room_id, payload)
@@ -93,7 +96,13 @@ def send_mode(connection, room_id, payload):
93
96
 
94
97
 
95
98
  def named_members(connection, room_id, payload):
96
- """The present members a side question names, as {name: id}; None for a message the whole room waits for."""
99
+ """The present members a side question names, as {name: id}; None for a message the whole room waits for.
100
+
101
+ A relay without its own names names the current active host, so it waits for that host alone."""
102
+ if payload.get("relay") and not payload.get("to"):
103
+ host = connection.execute("SELECT id,name FROM room_members WHERE room_id=? AND role='host' AND status='active'",
104
+ (room_id,)).fetchone()
105
+ return {host["name"]: host["id"]} if host else None
97
106
  named = payload.get("to")
98
107
  if not isinstance(named, list) or not named or payload.get("sequential") is True or payload.get("order") == "auto":
99
108
  return None
@@ -132,9 +141,7 @@ def waiting_names(connection, room_id, named, before=None):
132
141
  for row in connection.execute("SELECT id,payload FROM queued_messages WHERE room_id=? ORDER BY position,id", (room_id,)):
133
142
  if row["id"] == before:
134
143
  break
135
- queued = json.loads(row["payload"])
136
- if named_members(connection, room_id, queued) is not None:
137
- earlier.update(queued.get("to") or [])
144
+ earlier.update(named_members(connection, room_id, json.loads(row["payload"])) or {})
138
145
  return [name for name, member_id in named.items() if name in earlier or member_busy(connection, member_id)]
139
146
 
140
147
 
@@ -231,7 +238,7 @@ def post_item(connection, room_id, row, post, names=None):
231
238
  """
232
239
  payload = json.loads(row["payload"])
233
240
  present = list(named_members(connection, room_id, payload) or {})
234
- names = list(payload.get("to") or []) if names is None else names
241
+ names = list(payload.get("to") or present) if names is None else names
235
242
  waiting = [name for name in present if name not in names]
236
243
  if payload.get("message_id"):
237
244
  message_id = give_share(connection, room_id, payload, names)
@@ -248,6 +255,9 @@ def post_item(connection, room_id, row, post, names=None):
248
255
  save_text(connection, "queued_message", row["id"], "failure", failure)
249
256
  return None
250
257
  connection.execute("RELEASE queued_post")
258
+ if payload.get("relay"):
259
+ connection.execute("""UPDATE room_relay_sends SET target_message_id=?,state='delivered'
260
+ WHERE target_room_id=? AND queued_id=? AND state='queued'""", (result["message"]["id"], room_id, row["id"]))
251
261
  keep_rest(connection, row, payload, waiting, result["message"]["id"])
252
262
  return result
253
263