ai_co_discuss 0.5.61 → 0.5.62

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.
@@ -228,6 +228,22 @@ def overview(facts, start, end, sealed):
228
228
  return {**result, "delivery": delivery, "coverage": {"numerator": delivery["samples"], "denominator": result["ended"]}}
229
229
 
230
230
 
231
+ def union_seconds(spans):
232
+ """Return the wall-clock duration covered by at least one interval."""
233
+ total = 0
234
+ current = None
235
+ for start, end in sorted(spans):
236
+ if current is None:
237
+ current = [start, end]
238
+ elif start <= current[1]:
239
+ if end > current[1]:
240
+ current[1] = end
241
+ else:
242
+ total += current[1] - current[0]
243
+ current = [start, end]
244
+ return total + (current[1] - current[0] if current is not None else 0)
245
+
246
+
231
247
  def peak_concurrent(intervals):
232
248
  """Union each key's intervals, then return the most keys active at once and the first moment it happened."""
233
249
  events = Counter()
@@ -396,11 +412,12 @@ def time_stats(connection, requests, executions, bounds, now, sealed):
396
412
  seen.add(r["message_id"])
397
413
  if start <= r["created_at"] < end and r["dispatched"] is not None and r["dispatched"] >= r["created_at"]:
398
414
  waits.append(r["dispatched"] - r["created_at"])
399
- spans, member_spans, shown_spans = defaultdict(list), defaultdict(list), defaultdict(list)
415
+ all_spans, spans, member_spans, shown_spans = [], defaultdict(list), defaultdict(list), defaultdict(list)
400
416
  elapsed, rework = [], []
401
417
  for r in executions:
402
418
  left, right = max(start, r["created_at"]), min(end, r["finished_at"] or now, now)
403
419
  if left < right:
420
+ all_spans.append((left, right))
404
421
  spans[r["room_id"]].append((left, right))
405
422
  member_spans[(r["room_id"], r["name"])].append((left, right))
406
423
  shown_spans[(r["room_id"], r["label"] or r["name"])].append((left, right))
@@ -422,6 +439,7 @@ def time_stats(connection, requests, executions, bounds, now, sealed):
422
439
  active_rooms = [room for room in room_rows.values() if room["initiated"] or room["execution_seconds"]]
423
440
  return {"folders": list(folders.values()), "rooms": active_rooms, "peak": peak, "concurrency": concurrency, "sealed_execution_seconds": counts["execution_seconds"],
424
441
  "execution_seconds": sum(f["execution_seconds"] for f in folders.values()) + counts["execution_seconds"],
442
+ "active_seconds": union_seconds(all_spans),
425
443
  "waiting": distribution(waits, histograms["waiting"]),
426
444
  "execution": distribution(elapsed, histograms["execution"]), "rework": distribution(rework, histograms["rework"]),
427
445
  "queue": {"count": count, "oldest_seconds": max(0, now-oldest) if count else None}}
@@ -601,14 +619,15 @@ def previous_work(rows, start, end, now):
601
619
  Same rules as the current period (clipped to the window, overlaps merged per room and per room + member), over
602
620
  existing rooms only.
603
621
  """
604
- seconds, rooms, members = 0, defaultdict(list), defaultdict(list)
622
+ seconds, all_spans, rooms, members = 0, [], defaultdict(list), defaultdict(list)
605
623
  for r in rows:
606
624
  left, right = max(start, r["created_at"]), min(end, r["finished_at"] or now, now)
607
625
  if left < right:
608
626
  seconds += right - left
627
+ all_spans.append((left, right))
609
628
  rooms[r["room_id"]].append((left, right))
610
629
  members[(r["room_id"], r["name"])].append((left, right))
611
- return {"execution_seconds": seconds, "peak_rooms": peak_concurrent(rooms)[0], "peak_members": peak_concurrent(members)[0]}
630
+ return {"execution_seconds": seconds, "active_seconds": union_seconds(all_spans), "peak_rooms": peak_concurrent(rooms)[0], "peak_members": peak_concurrent(members)[0]}
612
631
 
613
632
 
614
633
  MOSS_COUNTERS = ("task_rooms", "project_rooms", "delegations", "reworks", "unreported", "reclaimed")
@@ -712,7 +731,7 @@ def snapshot(connection, params, cache, now):
712
731
  scope = {"mode": mode, "rooms": len(rooms), "sealed_rooms": retained, "included_rooms": len(rooms) + retained,
713
732
  "includes_archived": True, "sealed_day_tz": "UTC", "sealed_counts": SEALED_COUNTS,
714
733
  "sealed_distributions": SEALED_DISTRIBUTIONS,
715
- "current_only": ["folders", "rooms", "peak", "concurrency", "issues", "queue", "affected_requests", "members", "models", "workflows", "insights", "scheduler"]}
734
+ "current_only": ["active_seconds", "folders", "rooms", "peak", "concurrency", "issues", "queue", "affected_requests", "members", "models", "workflows", "insights", "scheduler"]}
716
735
  scheduler = scheduler_quality(connection, start, end, distribution)
717
736
  result = dict(range=dates, scope=scope,
718
737
  overview=overview(facts, start, end, sealed), previous=overview(facts, previous, start, prior),
@@ -79,11 +79,8 @@ def guard_route(connect, headers, parts):
79
79
  return
80
80
  hashed = token_hash(headers.get("X-Discussion-Token", ""))
81
81
  if not marked and hashed:
82
- connection = connect()
83
- try:
82
+ with connect() as connection:
84
83
  marked = connection.execute("SELECT 1 FROM external_members WHERE token_hash=?", (hashed,)).fetchone() is not None
85
- finally:
86
- connection.close()
87
84
  if marked:
88
85
  raise classified(PermissionError, Text("外部成员只能使用成员范围接口"), "external_route_forbidden")
89
86
 
@@ -1406,9 +1406,10 @@ def recent_executions(connection, room_id, span=None):
1406
1406
  (room_id, low, low, MAX_MESSAGE_ID if high is None else high, room_id))
1407
1407
  else:
1408
1408
  rows = connection.execute(
1409
- f"""{query} AND (e.status IN ('dispatched','started')
1410
- OR e.id IN (SELECT id FROM member_executions WHERE room_id=? ORDER BY id DESC LIMIT ?))
1411
- ORDER BY e.id DESC""", (room_id, room_id, RECENT_EXECUTIONS))
1409
+ f"""{query} AND e.id IN (
1410
+ SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')
1411
+ UNION SELECT id FROM (SELECT id FROM member_executions WHERE room_id=? ORDER BY id DESC LIMIT ?))
1412
+ ORDER BY e.id DESC""", (room_id, room_id, room_id, RECENT_EXECUTIONS))
1412
1413
  executions = []
1413
1414
  positions = relay_positions(connection, room_id)
1414
1415
  for row in rows:
@@ -1676,8 +1677,9 @@ def free_view(connection, room_id):
1676
1677
  JOIN member_executions e ON e.id=rr.execution_id WHERE rr.request_id=member_requests.id),
1677
1678
  created_at) AS layout_at,
1678
1679
  EXISTS(SELECT 1 FROM retried_requests rr WHERE rr.request_id=member_requests.id) AS retried FROM member_requests
1679
- WHERE room_id=? AND (status IN ('pending','delivering')
1680
- OR id IN (SELECT id FROM member_requests WHERE room_id=? ORDER BY id DESC LIMIT ?))
1680
+ WHERE id IN (
1681
+ SELECT id FROM member_requests WHERE room_id=? AND status IN ('pending','delivering')
1682
+ UNION SELECT id FROM (SELECT id FROM member_requests WHERE room_id=? ORDER BY id DESC LIMIT ?))
1681
1683
  ORDER BY id DESC""", (room_id, room_id, RECENT_REQUESTS))]
1682
1684
  tag_group_requests(connection, room_id, requests)
1683
1685
  chains = [dict(row) for row in connection.execute(
@@ -1916,6 +1918,7 @@ def check_proactive(connection, room_id, member, payload):
1916
1918
  reason = payload.get("continue")
1917
1919
  if reason is not None and (not isinstance(reason, str) or not reason.strip() or len(reason) > MAX_CONTINUE_REASON):
1918
1920
  raise ValueError(Text("continue 写明房间空闲后继续做什么,最多 {max_continue_reason} 字", max_continue_reason=MAX_CONTINUE_REASON))
1921
+ check_host_undispatched_mentions(connection, room_id, member, payload)
1919
1922
 
1920
1923
 
1921
1924
  def after_proactive(connection, room_id, message_id, member, payload):
@@ -1975,7 +1978,7 @@ def check_answer(connection, room_id, member, payload):
1975
1978
  purposes.append(row["purpose"])
1976
1979
  requests.append(row)
1977
1980
  discussion.validate_session_request_answer(connection, room_id, requests)
1978
- check_dispatch(member, payload, purposes)
1981
+ check_dispatch(connection, room_id, member, payload, purposes)
1979
1982
  return None
1980
1983
  execution_id = payload.get("execution_id")
1981
1984
  if type(execution_id) is not int:
@@ -2004,16 +2007,45 @@ def check_answer(connection, room_id, member, payload):
2004
2007
  requests = [dict(item) for item in connection.execute(
2005
2008
  "SELECT id,purpose FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,))]
2006
2009
  discussion.validate_session_request_answer(connection, room_id, requests)
2007
- check_dispatch(member, payload, [item["purpose"] for item in requests])
2010
+ check_dispatch(connection, room_id, member, payload, [item["purpose"] for item in requests])
2008
2011
  return row
2009
2012
 
2010
2013
 
2011
- def check_dispatch(member, payload, purposes):
2014
+ HOST_MENTION_PREFIX = r"(^|[\s((\[【*,,。;;::、])@"
2015
+ MENTION_SUFFIX = r"(?![A-Za-z0-9_\-\u4e00-\u9fff])"
2016
+
2017
+
2018
+ def check_host_undispatched_mentions(connection, room_id, member, payload, purposes=()):
2019
+ """Reject a host reply that @-mentions active members in prose without passing `to` or `detach`."""
2020
+ if (member["role"] != "host" or payload.get("source") == "auto" or payload.get("to") or payload.get("detach")
2021
+ or purposes and (all(purpose == "all" for purpose in purposes)
2022
+ or any(purpose in ("discuss", "discuss_host") for purpose in purposes))):
2023
+ return
2024
+ prose = mention_prose(str(payload.get("text") or ""))
2025
+ if "@" not in prose:
2026
+ return
2027
+ active = active_members(connection, room_id)
2028
+ shown = member_display_names(connection, room_id)
2029
+ mentioned = []
2030
+ for handle, name in member_handles(connection, room_id).items():
2031
+ if name in active and name != member["name"] and name not in mentioned and re.search(
2032
+ HOST_MENTION_PREFIX + re.escape(handle) + MENTION_SUFFIX, prose):
2033
+ mentioned.append(name)
2034
+ if mentioned:
2035
+ mentions = "、".join(f"@{shown.get(name, name)}" for name in mentioned)
2036
+ raise ValueError(Text(
2037
+ "正文提到了 {mentions} 但未指定 --to(或 --detach),这样不会唤醒对方;要派活请补上 --to,仅作文本提及请去掉 @ 符号",
2038
+ mentions=mentions,
2039
+ ))
2040
+
2041
+
2042
+ def check_dispatch(connection, room_id, member, payload, purposes):
2012
2043
  """A host answering only its share of an everyone request answers as a member, so it may not dispatch others."""
2013
2044
  if member["role"] == "host" and payload.get("to") and purposes and all(purpose == "all" for purpose in purposes):
2014
2045
  raise ValueError(Text("这次是请全体成员各自回应,其他成员已收到请求;主持人只回答自己的部分,不能用 --to 派活"))
2015
2046
  if payload.get("keep_working") and any(purpose in ("discuss", "discuss_host") for purpose in purposes):
2016
2047
  raise ValueError(Text("讨论中的发言不能用 keep_working"))
2048
+ check_host_undispatched_mentions(connection, room_id, member, payload, purposes)
2017
2049
 
2018
2050
 
2019
2051
  def check_keep_working(member, payload):
@@ -53,9 +53,11 @@ def queue_view(connection, room_id):
53
53
  items = []
54
54
  for row in connection.execute("SELECT * FROM queued_messages WHERE room_id=? ORDER BY position,id", (room_id,)):
55
55
  payload = json.loads(row["payload"])
56
- files = [dict(item) for item in connection.execute(
57
- "SELECT id,file_name,content_type FROM attachments WHERE room_id=? AND id IN (SELECT value FROM json_each(?))",
58
- (room_id, json.dumps(payload.get("attachment_ids", []))))]
56
+ attachment_ids = payload.get("attachment_ids") or []
57
+ by_id = {entry["id"]: dict(entry) for entry in connection.execute(
58
+ "SELECT id,file_name,content_type,size,storage,cleared_at FROM attachments WHERE room_id=? AND id IN (SELECT value FROM json_each(?))",
59
+ (room_id, json.dumps(attachment_ids)))} if attachment_ids else {}
60
+ files = [by_id[identifier] for identifier in attachment_ids if identifier in by_id]
59
61
  item = {"id": row["id"], "text": payload.get("text", ""), "attachments": files, "failure": row["failure"],
60
62
  "texts": load_texts(connection, "queued_message", row["id"]), "created_at": row["created_at"]}
61
63
  if relay := payload.get("relay"):
@@ -170,7 +170,7 @@ CREATE TABLE IF NOT EXISTS room_relay_sends (
170
170
  target_message_id INTEGER,
171
171
  queued_id INTEGER,
172
172
  interrupted INTEGER NOT NULL DEFAULT 0,
173
- state TEXT NOT NULL DEFAULT 'delivered' CHECK(state IN ('queued','delivered','replied')),
173
+ state TEXT NOT NULL DEFAULT 'delivered' CHECK(state IN ('queued','delivered','replied','cancelled')),
174
174
  host TEXT NOT NULL,
175
175
  member TEXT NOT NULL DEFAULT ''
176
176
  );
@@ -398,6 +398,7 @@ CREATE TABLE IF NOT EXISTS room_members (
398
398
  );
399
399
  CREATE UNIQUE INDEX IF NOT EXISTS member_name ON room_members(room_id,name) WHERE status<>'removed';
400
400
  CREATE UNIQUE INDEX IF NOT EXISTS member_credential ON room_members(room_id,token_hash) WHERE token_hash<>'';
401
+ CREATE INDEX IF NOT EXISTS room_members_by_status ON room_members(room_id,status);
401
402
 
402
403
  -- Local service attestation, never a permission grant. Re-imported rooms require a fresh attestation.
403
404
  CREATE TABLE IF NOT EXISTS member_review_capabilities (
@@ -581,6 +582,7 @@ CREATE TABLE IF NOT EXISTS execution_segments (
581
582
  PRIMARY KEY(source,execution_id,seq)
582
583
  );
583
584
  CREATE INDEX IF NOT EXISTS execution_segments_room ON execution_segments(room_id);
585
+ CREATE INDEX IF NOT EXISTS execution_segments_by_phase ON execution_segments(source,execution_id,phase);
584
586
  -- One live execution per member: different members may run in parallel, one session never twice.
585
587
  CREATE UNIQUE INDEX IF NOT EXISTS one_member_execution ON member_executions(member_id)
586
588
  WHERE status IN ('dispatched','started');
@@ -611,6 +613,7 @@ CREATE INDEX IF NOT EXISTS member_requests_answer ON member_requests(answer_id);
611
613
  CREATE INDEX IF NOT EXISTS member_requests_room ON member_requests(room_id);
612
614
  CREATE INDEX IF NOT EXISTS member_requests_room_chain ON member_requests(room_id,chain_id);
613
615
  CREATE INDEX IF NOT EXISTS member_requests_room_status ON member_requests(room_id,status);
616
+ CREATE INDEX IF NOT EXISTS member_requests_by_message ON member_requests(room_id,message_id,status);
614
617
  CREATE INDEX IF NOT EXISTS member_requests_batch ON member_requests(batch_id,status);
615
618
  -- Where a request's cards sit on the page: the room's latest message when the request was made. The page shows every
616
619
  -- card (working, failed, stopped, answer) under the top-level message at or before it, ordered by when its work started,
@@ -1085,6 +1088,7 @@ CREATE TABLE IF NOT EXISTS execution_continuations (
1085
1088
  execution_id INTEGER PRIMARY KEY REFERENCES member_executions(id) ON DELETE CASCADE,
1086
1089
  next_id INTEGER NOT NULL REFERENCES member_executions(id) ON DELETE CASCADE
1087
1090
  );
1091
+ CREATE INDEX IF NOT EXISTS execution_continuations_by_next ON execution_continuations(next_id);
1088
1092
  -- A follow-up execution (续报): background work (a sub-agent, a background command, a monitor) that the ended execution
1089
1093
  -- `source_id` left running reported, and the member's software started a new turn on it; the runner opened this one
1090
1094
  -- for that turn, so its answer has a source (red line 4, user 2026-11-25). One per source: a later report follows the
@@ -1120,6 +1124,7 @@ CREATE TABLE IF NOT EXISTS free_host_wakes (
1120
1124
  message_id INTEGER NOT NULL,
1121
1125
  PRIMARY KEY (room_id,key)
1122
1126
  );
1127
+ CREATE INDEX IF NOT EXISTS free_host_wakes_by_message ON free_host_wakes(message_id,key);
1123
1128
  -- The host's latest answer asked to continue once the room is idle; a later request for the host or a new owner
1124
1129
  -- message supersedes it (`after_request` is the newest request when it was asked).
1125
1130
  -- The host's timed check-in: while the room still has work in flight, the host gets a notice every interval to look
@@ -1996,6 +2001,8 @@ CREATE TABLE IF NOT EXISTS stored_texts (
1996
2001
  );
1997
2002
  CREATE INDEX IF NOT EXISTS room_events_room ON room_events(room_id,id);
1998
2003
  CREATE INDEX IF NOT EXISTS room_events_kind_at ON room_events(kind,at);
2004
+ CREATE INDEX IF NOT EXISTS room_events_host_changes ON room_events(room_id,id)
2005
+ WHERE kind IN ('member.joined','member.changed');
1999
2006
  -- Stop analytics names this index so it does not scan every api.write event.
2000
2007
  CREATE INDEX IF NOT EXISTS room_events_owner_stop ON room_events(at,room_id)
2001
2008
  WHERE kind='api.write' AND CASE WHEN json_valid(data) THEN json_extract(data,'$.path') END='/stop';
@@ -2222,6 +2229,7 @@ CREATE TABLE IF NOT EXISTS room_goals (
2222
2229
  pending_fallback INTEGER NOT NULL DEFAULT 0
2223
2230
  );
2224
2231
  CREATE UNIQUE INDEX IF NOT EXISTS one_open_goal ON room_goals(room_id) WHERE status IN ('active','paused');
2232
+ CREATE INDEX IF NOT EXISTS room_goals_pending_by_room ON room_goals(room_id) WHERE status='active' AND phase='pending';
2225
2233
  CREATE UNIQUE INDEX IF NOT EXISTS room_goals_start_request ON room_goals(start_request_id) WHERE start_request_id IS NOT NULL;
2226
2234
  -- Each automatic wake-up: the visible system message it hangs on and the host request it created.
2227
2235
  CREATE TABLE IF NOT EXISTS goal_continuations (