ai_co_discuss 0.5.32 → 0.5.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/discuss-host/references/control.md +1 -1
- package/README.md +1 -0
- package/README.zh-CN.md +1 -0
- package/backend/analytics.py +532 -0
- package/backend/free_room.py +108 -15
- package/backend/message_queue.py +0 -16
- package/backend/schema.sql +8 -1
- package/backend/server.py +103 -59
- package/docs/en/guide/README.md +1 -0
- package/docs/en/guide/analytics.md +42 -0
- package/docs/en/guide/members.md +2 -2
- package/docs/en/guide/rooms.md +3 -1
- package/docs/en/guide/working.md +1 -1
- package/docs/guide/README.md +1 -0
- package/docs/guide/analytics.md +42 -0
- package/docs/guide/members.md +2 -2
- package/docs/guide/rooms.md +3 -1
- package/docs/guide/working.md +1 -1
- package/frontend/locales/en/analytics.json +110 -0
- package/frontend/locales/en/backend.json +3 -1
- package/frontend/locales/en/discussion.json +30 -2
- package/frontend/locales/en/room.json +1 -0
- package/package.json +1 -1
- package/runner/adapters/codex_bridge.mjs +19 -4
- package/runner/analytics.mjs +25 -0
- package/runner/codiscuss.mjs +2 -1
- package/runner/discussion_launch.mjs +6 -5
- package/runner/discussion_service.mjs +1 -1
- package/runner/expert_prompts.mjs +4 -2
- package/runner/free_runner.mjs +6 -1
- package/runner/i18n_en.mjs +12 -2
- package/runner/relay_channel.mjs +1 -1
- package/runner/share_shared.mjs +31 -3
- package/runner/storage_guard.mjs +3 -2
- package/web/admin.js +1 -1
- package/web/app.js +255 -104
- package/web/i18n.js +3 -3
- package/web/modern.css +1 -1
- package/web/modern.js +70 -67
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
|
|
47
47
|
用 `launch host-control room-post --room 编号 --body-file FILE --expect reply` 交给对方主持人,普通通知用 `--expect none`;短消息可用 `--text`。对方忙时排队,只有父房间能用 `--interrupt` 打断子房间。达到互传上限时,请房主决定是否继续。
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
跨房请求用 `requests[].relay.reply` 中的命令回答:`launch host-control room-post --room 来源房编号 --reply-to 原消息编号 --body-file 回答.md`。先读原文,在本房权限内处理;发送或排队成功即完成该请求,本房发送卡片保留全文。若先派活,收尾时用原消息编号手动回传。若 `relay.expect` 为 `none`,读完即止。需要超出本房权限时在本房问用户。
|
|
50
50
|
|
|
51
51
|
## 定时检查
|
|
52
52
|
|
package/README.md
CHANGED
|
@@ -33,6 +33,7 @@ The [User Guide](docs/en/guide/README.md) covers each of these in full.
|
|
|
33
33
|
- **Structured discussions** — set a goal and round or time limits; the host schedules speakers and follow-ups, and you can produce a sourced report. See [Discussions](docs/en/guide/discussion.md).
|
|
34
34
|
- **Goal** — give the host an objective; it keeps going, stops when it needs your confirmation and can remind you on WeChat. See [Goal](docs/en/guide/goal.md).
|
|
35
35
|
- **Workflows** — save a fixed division of work among several agents and start it in a room with one click. See [Workflows](docs/en/guide/workflows.md).
|
|
36
|
+
- **Cross-room analytics** — review unassisted rates, folder activity, parallel room peaks, member scorecards and bottlenecks for today, the last 7 or 30 days, or all time, and export a local summary PNG. See [Analytics](docs/en/guide/analytics.md).
|
|
36
37
|
- **Smart Scheduling** — optionally let a decision model handle routine routing instead of waking the host; it uses your own key, and the room title and recent messages are sent to the provider. See [Smart Scheduling](docs/en/guide/scheduling.md).
|
|
37
38
|
- **Mix any participant** — local CLIs and desktop apps, model APIs and manually connected sessions in one room; resume existing agent sessions and give each member read-only or writable access. See [Members](docs/en/guide/members.md).
|
|
38
39
|
- **Shared projects and records** — point a room at project folders and browse them; attachments, export and import between sites, and branching; destroy a room, with its members’ AI sessions, at any time or after a set idle period. See [Rooms](docs/en/guide/rooms.md).
|
package/README.zh-CN.md
CHANGED
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
- **结构化讨论**:设定目标与轮次或时长上限,主持人安排发言与追问,可生成带来源的报告。见[讨论](docs/guide/discussion.md)。
|
|
34
34
|
- **Goal**:交给主持人一个目标,它持续推进,需要你确认时停下,可发微信提醒。见 [Goal](docs/guide/goal.md)。
|
|
35
35
|
- **工作流**:把固定的多人分工存成工作流,在房间里一键启用。见[工作流](docs/guide/workflows.md)。
|
|
36
|
+
- **全房间统计**:按今日、近 7 天、近 30 天或全部时间复盘免介入率、文件夹精力分布、同时推进的房间数、成员表现与卡点,并本地导出汇总分享图。见[统计](docs/guide/analytics.md)。
|
|
36
37
|
- **智能调度**:可选由决策模型处理日常分派,不必每次唤醒主持人;使用你自己的密钥,房间标题与最近消息会发给所选供应商。见[智能调度](docs/guide/scheduling.md)。
|
|
37
38
|
- **混合接入**:本地 CLI 与桌面 App、模型 API、手动接入的会话同房协作;可续接已有的 AI 会话,为每位成员设置只读或可写。见[成员](docs/guide/members.md)。
|
|
38
39
|
- **共享项目与记录**:为房间指定项目目录并在“文件”页浏览;附件、跨站点导出导入与分支;房间可随时或按设定期限销毁,连同成员的 AI 会话记录一起删除。见[房间目录与建房](docs/guide/rooms.md)。
|
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
"""Owner-only weekly reports over the current rooms of one Python site."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import subprocess
|
|
5
|
+
from bisect import bisect_right
|
|
6
|
+
from collections import Counter, defaultdict
|
|
7
|
+
from datetime import date, datetime, time, timedelta, timezone
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from math import floor
|
|
10
|
+
from time import monotonic
|
|
11
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
12
|
+
|
|
13
|
+
from .texts import Text
|
|
14
|
+
|
|
15
|
+
CACHE_SECONDS = 60
|
|
16
|
+
CACHE_ENTRIES = 32
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# A standard Windows Python installation may have no IANA database. Node ships ICU.
|
|
20
|
+
NODE_CALENDAR = """
|
|
21
|
+
const [zone, ...dates] = process.argv.slice(1);
|
|
22
|
+
const calendar = new Intl.DateTimeFormat('en-CA', {timeZone: zone, year:'numeric', month:'2-digit', day:'2-digit'});
|
|
23
|
+
process.env.TZ = calendar.resolvedOptions().timeZone;
|
|
24
|
+
const result = dates.length === 1 && !dates[0].includes("-", 1) ? calendar.format(new Date(Number(dates[0]) * 60000)) :
|
|
25
|
+
dates.map(day => new Date(day + 'T00:00:00').getTime() / 1000);
|
|
26
|
+
process.stdout.write(JSON.stringify(result));
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@lru_cache(maxsize=128)
|
|
31
|
+
def node_calendar(zone, *dates):
|
|
32
|
+
"""Use bundled ICU when the host Python has no timezone files."""
|
|
33
|
+
try:
|
|
34
|
+
run = subprocess.run(["node", "-e", NODE_CALENDAR, "--", zone, *dates], capture_output=True,
|
|
35
|
+
text=True, timeout=5, check=True)
|
|
36
|
+
return json.loads(run.stdout)
|
|
37
|
+
except (OSError, subprocess.SubprocessError, ValueError):
|
|
38
|
+
raise ValueError(Text("统计日期范围或时区无效")) from None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def report_zone(name):
|
|
42
|
+
"""Resolve the requested zone, falling back to ICU only when Python lacks a zone database."""
|
|
43
|
+
if name == "UTC":
|
|
44
|
+
return timezone.utc
|
|
45
|
+
try:
|
|
46
|
+
return ZoneInfo(name)
|
|
47
|
+
except ZoneInfoNotFoundError:
|
|
48
|
+
try:
|
|
49
|
+
ZoneInfo("Etc/UTC")
|
|
50
|
+
except ZoneInfoNotFoundError:
|
|
51
|
+
return None
|
|
52
|
+
raise
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
ROLLING_DAYS = {"today": 1, "7d": 7, "30d": 30}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def period(params, now, earliest=None):
|
|
59
|
+
"""Return local calendar boundaries and their UTC timestamps.
|
|
60
|
+
|
|
61
|
+
`today`, `7d` and `30d` end tomorrow and compare with the same number of days before; `all` starts on the local
|
|
62
|
+
date of `earliest` (the oldest recorded activity, Unix seconds) and has an empty previous period.
|
|
63
|
+
"""
|
|
64
|
+
name = params.get("tz", "UTC")
|
|
65
|
+
try:
|
|
66
|
+
zone = report_zone(name)
|
|
67
|
+
today = (datetime.fromtimestamp(now, zone).date() if zone is not None
|
|
68
|
+
else date.fromisoformat(node_calendar(name, str(int(now)//60))))
|
|
69
|
+
mode = params.get("range", "7d")
|
|
70
|
+
if mode not in ("week", "month", "all", *ROLLING_DAYS):
|
|
71
|
+
raise ValueError
|
|
72
|
+
if "from" in params or "to" in params:
|
|
73
|
+
start, end = (date.fromisoformat(params[key]) for key in ("from", "to"))
|
|
74
|
+
previous = start - (end - start)
|
|
75
|
+
if start.day == end.day == 1 and (end - start).days <= 31:
|
|
76
|
+
previous = (start - timedelta(days=1)).replace(day=1)
|
|
77
|
+
elif mode in ROLLING_DAYS:
|
|
78
|
+
end = today + timedelta(days=1)
|
|
79
|
+
start = end - timedelta(days=ROLLING_DAYS[mode])
|
|
80
|
+
previous = start - timedelta(days=ROLLING_DAYS[mode])
|
|
81
|
+
elif mode == "all":
|
|
82
|
+
end = today + timedelta(days=1)
|
|
83
|
+
first = (datetime.fromtimestamp(earliest, zone).date() if zone is not None and earliest
|
|
84
|
+
else date.fromisoformat(node_calendar(name, str(int(earliest) // 60))) if earliest else today)
|
|
85
|
+
start = previous = min(first, today)
|
|
86
|
+
elif mode == "month":
|
|
87
|
+
start = today.replace(day=1)
|
|
88
|
+
end = (start + timedelta(days=32)).replace(day=1)
|
|
89
|
+
previous = (start - timedelta(days=1)).replace(day=1)
|
|
90
|
+
else:
|
|
91
|
+
start = today - timedelta(days=today.weekday())
|
|
92
|
+
end, previous = start + timedelta(days=7), start - timedelta(days=7)
|
|
93
|
+
if end <= start:
|
|
94
|
+
raise ValueError
|
|
95
|
+
days = (previous, start, end)
|
|
96
|
+
stamps = (tuple(int(datetime.combine(day, time.min, zone).timestamp()) for day in days)
|
|
97
|
+
if zone is not None else tuple(node_calendar(name, *map(str, days))))
|
|
98
|
+
return {"tz": name, "from": str(start), "to": str(end), "previous_from": str(previous),
|
|
99
|
+
"previous_to": str(start)}, stamps
|
|
100
|
+
except (KeyError, OverflowError, ValueError, ZoneInfoNotFoundError):
|
|
101
|
+
raise ValueError(Text("统计日期范围或时区无效")) from None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def distribution(values, histogram=None):
|
|
105
|
+
"""Combine exact observations with weighted anonymous bucket midpoints."""
|
|
106
|
+
counts = Counter(values)
|
|
107
|
+
for bucket, count in (histogram or {}).items():
|
|
108
|
+
low = int(bucket)
|
|
109
|
+
midpoint = (3 * low - 1) / 2 if low else 0
|
|
110
|
+
counts[midpoint] += count
|
|
111
|
+
ordered = sorted(counts.items())
|
|
112
|
+
total = sum(counts.values())
|
|
113
|
+
|
|
114
|
+
def sample(rank):
|
|
115
|
+
for seconds, weight in ordered:
|
|
116
|
+
if rank < weight:
|
|
117
|
+
return seconds
|
|
118
|
+
rank -= weight
|
|
119
|
+
|
|
120
|
+
def quantile(fraction):
|
|
121
|
+
if not total:
|
|
122
|
+
return None
|
|
123
|
+
index = (total - 1) * fraction
|
|
124
|
+
low = floor(index)
|
|
125
|
+
first = sample(low)
|
|
126
|
+
return round(first + (sample(min(low + 1, total - 1)) - first) * (index - low), 2)
|
|
127
|
+
|
|
128
|
+
return {"p50": quantile(.5), "p90": quantile(.9), "samples": total, "approximate": bool(histogram)}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
REQUESTS = """
|
|
132
|
+
WITH prior AS (SELECT rr.request_id,min(e.created_at) AS dispatched
|
|
133
|
+
FROM retried_requests rr JOIN member_executions e ON e.id=rr.execution_id GROUP BY rr.request_id)
|
|
134
|
+
SELECT r.room_id,r.message_id,r.chain_id,r.created_at,r.status,mbr.name,mbr.adapter,
|
|
135
|
+
coalesce(l.label,mbr.name) AS label,coalesce(e.model,'') AS model,coalesce(e.effort,'') AS effort,
|
|
136
|
+
(m.author='用户' AND NOT EXISTS(SELECT 1 FROM message_relays l WHERE l.message_id=m.id)
|
|
137
|
+
AND NOT EXISTS(SELECT 1 FROM internal_task_messages i WHERE i.message_id=m.id)) AS initiated,
|
|
138
|
+
CAST(strftime('%s',m.created_at) AS INTEGER) AS sent,CAST(strftime('%s',a.created_at) AS INTEGER) AS answered,
|
|
139
|
+
coalesce(w.kind,aw.kind) AS withdrawal,e.result,c.reason,coalesce(prior.dispatched,e.created_at) AS dispatched,
|
|
140
|
+
CASE WHEN c.reason='user_stop' AND e.id IS NULL THEN EXISTS(
|
|
141
|
+
SELECT 1 FROM room_events stop JOIN room_events cancelled ON cancelled.room_id=stop.room_id
|
|
142
|
+
AND cancelled.kind='request.cancel_reason'
|
|
143
|
+
AND cancelled.at BETWEEN stop.at AND stop.at+json_extract(stop.data,'$.elapsed_ms')+1
|
|
144
|
+
WHERE stop.room_id=r.room_id AND stop.kind='api.write' AND json_extract(stop.data,'$.path')='/stop'
|
|
145
|
+
AND json_extract(cancelled.data,'$.request_id')=r.id) END AS stopped_pending
|
|
146
|
+
FROM member_requests r LEFT JOIN prior ON prior.request_id=r.id JOIN messages m ON m.id=r.message_id
|
|
147
|
+
JOIN room_members mbr ON mbr.id=r.member_id LEFT JOIN member_labels l ON l.room_id=r.room_id AND l.name=mbr.name
|
|
148
|
+
LEFT JOIN messages a ON a.id=r.answer_id LEFT JOIN member_executions e ON e.id=r.execution_id
|
|
149
|
+
LEFT JOIN request_cancel_reasons c ON c.request_id=r.id
|
|
150
|
+
LEFT JOIN message_withdrawals w ON w.message_id=m.id LEFT JOIN message_withdrawals aw ON aw.message_id=a.id
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def user_stopped(row):
|
|
155
|
+
"""Separate owner interventions from host cancellations and send-now follow-ups."""
|
|
156
|
+
return row["reason"] == "user_stop" and (row["stopped_pending"] or row["result"] in ("用户打断", "用户停止全部", "用户回退了对话"))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def overview_facts(rows):
|
|
160
|
+
"""Yield additive facts with their original message or chain cohort timestamp."""
|
|
161
|
+
messages, chains = defaultdict(list), defaultdict(list)
|
|
162
|
+
for row in rows:
|
|
163
|
+
if row["initiated"]:
|
|
164
|
+
messages[row["message_id"]].append(row)
|
|
165
|
+
chains[row["room_id"], row["chain_id"] or row["message_id"]].append(row)
|
|
166
|
+
for group in messages.values():
|
|
167
|
+
sent = group[0]["sent"]
|
|
168
|
+
yield sent, "initiated", 1
|
|
169
|
+
if any(row["answered"] is not None for row in group):
|
|
170
|
+
yield sent, "answered", 1
|
|
171
|
+
for group in chains.values():
|
|
172
|
+
if any(r["status"] in ("pending", "delivering") for r in group):
|
|
173
|
+
continue
|
|
174
|
+
first = min(row["created_at"] for row in group)
|
|
175
|
+
yield first, "ended", 1
|
|
176
|
+
if not any(r["withdrawal"] or user_stopped(r) for r in group):
|
|
177
|
+
yield first, "unassisted", 1
|
|
178
|
+
answers = [r["answered"] for r in group if r["answered"] is not None]
|
|
179
|
+
if answers and all(r["status"] == "completed" for r in group):
|
|
180
|
+
yield first, "delivery", max(0, max(answers) - first)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def overview(facts, start, end, sealed):
|
|
184
|
+
counts, histograms = sealed
|
|
185
|
+
result = {key: counts[key] for key in ("initiated", "answered", "ended", "unassisted")}
|
|
186
|
+
durations = []
|
|
187
|
+
for stamp, key, value in facts:
|
|
188
|
+
if start <= stamp < end:
|
|
189
|
+
if key == "delivery":
|
|
190
|
+
durations.append(value)
|
|
191
|
+
else:
|
|
192
|
+
result[key] += value
|
|
193
|
+
delivery = distribution(durations, histograms["delivery"])
|
|
194
|
+
return {**result, "delivery": delivery, "coverage": {"numerator": delivery["samples"], "denominator": result["ended"]}}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def peak_concurrent(intervals):
|
|
198
|
+
"""Union each key's intervals, then return the most keys active at once and the first moment it happened."""
|
|
199
|
+
events = Counter()
|
|
200
|
+
for spans in intervals.values():
|
|
201
|
+
merged = []
|
|
202
|
+
for start, end in sorted(spans):
|
|
203
|
+
if merged and start <= merged[-1][1]:
|
|
204
|
+
merged[-1][1] = max(merged[-1][1], end)
|
|
205
|
+
else:
|
|
206
|
+
merged.append([start, end])
|
|
207
|
+
for start, end in merged:
|
|
208
|
+
events[start] += 1
|
|
209
|
+
events[end] -= 1
|
|
210
|
+
count = peak = 0
|
|
211
|
+
at = None
|
|
212
|
+
for stamp, change in sorted(events.items()):
|
|
213
|
+
count += change
|
|
214
|
+
if count > peak:
|
|
215
|
+
peak, at = count, stamp
|
|
216
|
+
return peak, at
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
EXECUTIONS = """
|
|
220
|
+
WITH attempts AS (
|
|
221
|
+
SELECT request_id,execution_id FROM retried_requests
|
|
222
|
+
UNION ALL SELECT id,execution_id FROM member_requests WHERE execution_id IS NOT NULL
|
|
223
|
+
), failed_attempts AS (
|
|
224
|
+
SELECT rr.request_id,min(rr.execution_id) AS first_failed FROM retried_requests rr
|
|
225
|
+
JOIN member_executions e ON e.id=rr.execution_id WHERE e.status='failed' GROUP BY rr.request_id
|
|
226
|
+
), rework AS (
|
|
227
|
+
SELECT DISTINCT a.execution_id FROM attempts a JOIN failed_attempts f ON f.request_id=a.request_id
|
|
228
|
+
WHERE a.execution_id>f.first_failed
|
|
229
|
+
)
|
|
230
|
+
SELECT e.id,e.room_id,e.created_at,e.finished_at,e.status,e.result,e.model,e.effort,m.name,m.adapter,
|
|
231
|
+
coalesce(l.label,m.name) AS label,f.failure_class,
|
|
232
|
+
EXISTS(SELECT 1 FROM execution_denials d WHERE d.execution_id=e.id AND d.denials NOT IN ('','[]','{}')) AS denied,
|
|
233
|
+
(e.status='failed' AND EXISTS(SELECT 1 FROM retried_requests rr WHERE rr.execution_id=e.id)) AS retried,
|
|
234
|
+
(rework.execution_id IS NOT NULL) AS rework
|
|
235
|
+
FROM member_executions e LEFT JOIN rework ON rework.execution_id=e.id JOIN room_members m ON m.id=e.member_id
|
|
236
|
+
LEFT JOIN member_labels l ON l.room_id=e.room_id AND l.name=m.name
|
|
237
|
+
LEFT JOIN execution_failures f ON f.execution_id=e.id
|
|
238
|
+
WHERE e.created_at<? AND (e.created_at>=? OR e.finished_at>=? OR e.finished_at=0)
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def member_stats(rows, requests, revived, by_model=False):
|
|
243
|
+
"""Aggregate the underlying requests and executions, including pooled model duration samples."""
|
|
244
|
+
groups = {}
|
|
245
|
+
identity = ("adapter", "model", "effort") if by_model else ("room_id", "name", "adapter", "model", "effort")
|
|
246
|
+
|
|
247
|
+
def bucket(row):
|
|
248
|
+
key = tuple(row[field] for field in identity)
|
|
249
|
+
if key not in groups:
|
|
250
|
+
item = {field: row[field] for field in ("adapter", "model", "effort")}
|
|
251
|
+
if not by_model:
|
|
252
|
+
item.update(room_id=row["room_id"], member=row["name"], label=row["label"])
|
|
253
|
+
item.update(accepted=0, executions=0, completed=0, failed=0, cancelled=0, interrupted=0,
|
|
254
|
+
retries=0, denied=0, revived=0, failures=Counter(), durations=[])
|
|
255
|
+
groups[key] = item
|
|
256
|
+
return groups[key]
|
|
257
|
+
|
|
258
|
+
for row in requests:
|
|
259
|
+
bucket(row)["accepted"] += 1
|
|
260
|
+
for r in rows:
|
|
261
|
+
item = bucket(r)
|
|
262
|
+
item["executions"] += 1
|
|
263
|
+
if r["status"] in ("completed", "failed", "cancelled"):
|
|
264
|
+
item[r["status"]] += 1
|
|
265
|
+
if r["failure_class"] and r["status"] == "failed":
|
|
266
|
+
item["failures"][r["failure_class"]] += 1
|
|
267
|
+
item["interrupted"] += r["status"] == "cancelled" and r["result"] in ("用户打断", "用户停止全部")
|
|
268
|
+
item["retries"] += r["retried"]
|
|
269
|
+
item["denied"] += r["denied"]
|
|
270
|
+
item["revived"] += r["id"] in revived and r["status"] == "completed"
|
|
271
|
+
if r["finished_at"] >= r["created_at"] and r["finished_at"]:
|
|
272
|
+
item["durations"].append(r["finished_at"] - r["created_at"])
|
|
273
|
+
for item in groups.values():
|
|
274
|
+
item["duration"] = distribution(item.pop("durations"))
|
|
275
|
+
return list(groups.values())
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def insights(connection, members, start, end):
|
|
279
|
+
"""Return observed counts with denominators and drill-down keys."""
|
|
280
|
+
result = []
|
|
281
|
+
def add(rule, count, total, params, target):
|
|
282
|
+
if count >= 3 and total >= 10:
|
|
283
|
+
result.append(dict(rule=rule, numerator=count, denominator=total, params=params, target=target))
|
|
284
|
+
for item in members:
|
|
285
|
+
target = {k: item[k] for k in ("room_id", "member", "adapter", "model", "effort")}
|
|
286
|
+
for kind, count in item["failures"].items():
|
|
287
|
+
add("failure_cluster", count, item["executions"], {"failure_class": kind}, target)
|
|
288
|
+
for rule, key in (("permission_denial", "denied"), ("late_recovery", "revived")):
|
|
289
|
+
add(rule, item[key], item["executions"], {}, target)
|
|
290
|
+
for room, bad, total in connection.execute("""SELECT d.room_id,sum(f.rating='bad'),count(*)
|
|
291
|
+
FROM scheduler_feedback f JOIN scheduler_decisions d ON d.id=f.decision_id
|
|
292
|
+
WHERE CAST(strftime('%s',f.created_at) AS INTEGER)>=? AND CAST(strftime('%s',f.created_at) AS INTEGER)<? GROUP BY d.room_id""", (start, end)):
|
|
293
|
+
add("scheduler_feedback", bad, total, {}, {"room_id": room})
|
|
294
|
+
return result
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def time_stats(connection, requests, executions, bounds, now, sealed):
|
|
298
|
+
"""Summarize folder activity, observed waiting and the current message queue."""
|
|
299
|
+
start, end = bounds
|
|
300
|
+
counts, histograms = sealed
|
|
301
|
+
folders, room_folder = {}, {}
|
|
302
|
+
for room, folder, name in connection.execute("""SELECT r.id,f.id,f.name FROM rooms r
|
|
303
|
+
LEFT JOIN room_folder_assignments a ON a.room_id=r.id LEFT JOIN topic_folders f ON f.id=a.folder_id"""):
|
|
304
|
+
room_folder[room] = folder
|
|
305
|
+
folders.setdefault(folder, dict(folder_id=folder, name=name, initiated=0, execution_seconds=0))
|
|
306
|
+
seen, waits = set(), []
|
|
307
|
+
for r in requests:
|
|
308
|
+
if r["initiated"] and start <= r["sent"] < end and r["message_id"] not in seen:
|
|
309
|
+
folders[room_folder[r["room_id"]]]["initiated"] += 1
|
|
310
|
+
seen.add(r["message_id"])
|
|
311
|
+
if start <= r["created_at"] < end and r["dispatched"] is not None and r["dispatched"] >= r["created_at"]:
|
|
312
|
+
waits.append(r["dispatched"] - r["created_at"])
|
|
313
|
+
spans, member_spans = defaultdict(list), defaultdict(list)
|
|
314
|
+
elapsed, rework = [], []
|
|
315
|
+
for r in executions:
|
|
316
|
+
left, right = max(start, r["created_at"]), min(end, r["finished_at"] or now, now)
|
|
317
|
+
if left < right:
|
|
318
|
+
spans[r["room_id"]].append((left, right))
|
|
319
|
+
member_spans[(r["room_id"], r["name"])].append((left, right))
|
|
320
|
+
folders[room_folder[r["room_id"]]]["execution_seconds"] += right-left
|
|
321
|
+
if start <= r["created_at"] and r["finished_at"] >= r["created_at"] and r["finished_at"]:
|
|
322
|
+
duration = r["finished_at"] - r["created_at"]
|
|
323
|
+
elapsed.append(duration)
|
|
324
|
+
if r["rework"]:
|
|
325
|
+
rework.append(duration)
|
|
326
|
+
count, oldest = connection.execute("SELECT count(*),min(created_at) FROM queued_messages").fetchone()
|
|
327
|
+
rooms, rooms_at = peak_concurrent(spans)
|
|
328
|
+
members, members_at = peak_concurrent(member_spans)
|
|
329
|
+
peak = {"rooms": rooms, "at": rooms_at, "members": members, "members_at": members_at}
|
|
330
|
+
return {"folders": list(folders.values()), "peak": peak, "sealed_execution_seconds": counts["execution_seconds"],
|
|
331
|
+
"execution_seconds": sum(f["execution_seconds"] for f in folders.values()) + counts["execution_seconds"],
|
|
332
|
+
"waiting": distribution(waits, histograms["waiting"]),
|
|
333
|
+
"execution": distribution(elapsed, histograms["execution"]), "rework": distribution(rework, histograms["rework"]),
|
|
334
|
+
"queue": {"count": count, "oldest_seconds": max(0, now-oldest) if count else None}}
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def actions(connection, start, end):
|
|
338
|
+
"""Count corrections by operation and rewound requests separately."""
|
|
339
|
+
def count(sql):
|
|
340
|
+
return connection.execute(sql, (start, end)).fetchone()[0]
|
|
341
|
+
rewind = count("SELECT count(*) FROM room_rewinds WHERE created_at>=? AND created_at<?")
|
|
342
|
+
affected = count("""WITH window(lo,hi) AS (VALUES(?,?))
|
|
343
|
+
SELECT count(*) FROM member_requests r CROSS JOIN window
|
|
344
|
+
LEFT JOIN member_executions e ON e.id=r.execution_id
|
|
345
|
+
WHERE (e.result='用户回退了对话' AND e.status='cancelled' AND e.finished_at>=lo AND e.finished_at<hi)
|
|
346
|
+
OR EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id IN (r.message_id,r.answer_id)
|
|
347
|
+
AND w.kind='rewound' AND w.created_at>=lo AND w.created_at<hi)""")
|
|
348
|
+
retract = count("SELECT count(*) FROM message_withdrawals WHERE kind='retracted' AND created_at>=? AND created_at<?")
|
|
349
|
+
stops = count("""SELECT count(*) FROM room_events WHERE at>=?*1000 AND at<?*1000 AND kind='api.write'
|
|
350
|
+
AND json_extract(data,'$.path')='/stop'""")
|
|
351
|
+
stops += count("""SELECT count(*) FROM room_events WHERE at>=?*1000 AND at<?*1000 AND kind='execution.changed'
|
|
352
|
+
AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断'""")
|
|
353
|
+
extra = count("""SELECT count(*) FROM execution_interjections i LEFT JOIN interjection_authors a ON a.interjection_id=i.id
|
|
354
|
+
WHERE a.interjection_id IS NULL AND i.created_at>=? AND i.created_at<?""")
|
|
355
|
+
return {"corrections": {"stops": stops, "withdrawals": retract, "rewinds": rewind, "affected_requests": affected},
|
|
356
|
+
"additions": {"interjections": extra}}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
DAY_SECONDS = 86400
|
|
360
|
+
SEALED_DISTRIBUTIONS = ("delivery", "waiting", "execution", "rework")
|
|
361
|
+
SEALED_COUNTS = ("initiated", "answered", "ended", "unassisted", "execution_seconds", "rewinds",
|
|
362
|
+
"withdrawals", "stops", "interjections")
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def archive_key(room_id, secret):
|
|
366
|
+
"""Compute a private join key for idempotence and same-ID restores."""
|
|
367
|
+
return hashlib.blake2b(room_id.encode(), key=bytes.fromhex(secret), digest_size=20).hexdigest()
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def room_time_facts(connection, room_id, rows, now):
|
|
371
|
+
for row in rows:
|
|
372
|
+
sent, dispatched = row["created_at"], row["dispatched"]
|
|
373
|
+
if dispatched is not None and dispatched >= sent:
|
|
374
|
+
yield sent, "waiting", dispatched - sent
|
|
375
|
+
query = EXECUTIONS + " AND e.room_id=?"
|
|
376
|
+
for row in connection.execute(query, (now+1, 0, 0, room_id)):
|
|
377
|
+
start, end = row["created_at"], row["finished_at"]
|
|
378
|
+
if end and end >= start:
|
|
379
|
+
yield start, "execution", end - start
|
|
380
|
+
if row["rework"]:
|
|
381
|
+
yield start, "rework", end - start
|
|
382
|
+
limit = min(end or now, now)
|
|
383
|
+
while start < limit:
|
|
384
|
+
boundary = min((start // DAY_SECONDS + 1) * DAY_SECONDS, limit)
|
|
385
|
+
yield start, "execution_seconds", boundary - start
|
|
386
|
+
start = boundary
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
ARCHIVE_ACTIONS = """
|
|
390
|
+
SELECT created_at,'rewinds',1 FROM room_rewinds WHERE room_id=:room
|
|
391
|
+
UNION ALL SELECT w.created_at,'withdrawals',1 FROM message_withdrawals w JOIN messages m ON m.id=w.message_id
|
|
392
|
+
WHERE m.room_id=:room AND w.kind='retracted'
|
|
393
|
+
UNION ALL SELECT i.created_at,'interjections',1 FROM execution_interjections i
|
|
394
|
+
LEFT JOIN interjection_authors a ON a.interjection_id=i.id WHERE i.room_id=:room AND a.interjection_id IS NULL
|
|
395
|
+
UNION ALL SELECT at/1000,'stops',1 FROM room_events WHERE room_id=:room AND
|
|
396
|
+
((kind='api.write' AND json_extract(data,'$.path')='/stop') OR (kind='execution.changed'
|
|
397
|
+
AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断'))
|
|
398
|
+
"""
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def seal_room(connection, room_id, now):
|
|
402
|
+
"""Replace this room's anonymous daily contribution within the destruction transaction."""
|
|
403
|
+
connection.execute("INSERT OR IGNORE INTO site_preferences VALUES ('analytics_salt',hex(randomblob(32)))")
|
|
404
|
+
secret = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_salt'").fetchone()[0]
|
|
405
|
+
key = archive_key(room_id, secret)
|
|
406
|
+
rows = connection.execute(REQUESTS + " WHERE r.room_id=?", (room_id,)).fetchall()
|
|
407
|
+
days = defaultdict(lambda: (Counter(), defaultdict(Counter)))
|
|
408
|
+
for facts in (overview_facts(rows), room_time_facts(connection, room_id, rows, now),
|
|
409
|
+
connection.execute(ARCHIVE_ACTIONS, {"room": room_id})):
|
|
410
|
+
for stamp, metric, value in facts:
|
|
411
|
+
if stamp is None:
|
|
412
|
+
continue
|
|
413
|
+
day = datetime.fromtimestamp(stamp, timezone.utc).date().isoformat()
|
|
414
|
+
counts, histograms = days[day]
|
|
415
|
+
if metric in SEALED_DISTRIBUTIONS:
|
|
416
|
+
bucket = 1 << (int(value).bit_length() - 1) if value else 0
|
|
417
|
+
histograms[metric][bucket] += 1
|
|
418
|
+
else:
|
|
419
|
+
counts[metric] += value
|
|
420
|
+
# An empty room contributes only to the total number of retained rooms.
|
|
421
|
+
if not days:
|
|
422
|
+
days[datetime.fromtimestamp(now, timezone.utc).date().isoformat()]
|
|
423
|
+
connection.execute("""INSERT INTO site_preferences VALUES ('analytics_revision','1')
|
|
424
|
+
ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1""")
|
|
425
|
+
connection.execute("DELETE FROM analytics_sealed_days WHERE archive_key=?", (key,))
|
|
426
|
+
connection.executemany("INSERT INTO analytics_sealed_days VALUES (?,?,?,?)",
|
|
427
|
+
[(key, day, json.dumps(counts), json.dumps(hist)) for day, (counts, hist) in days.items()])
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def sealed_periods(connection, mode, rooms, dates):
|
|
431
|
+
periods = [(Counter(), defaultdict(Counter)) for _ in range(2)]
|
|
432
|
+
daily = defaultdict(Counter)
|
|
433
|
+
if mode == "current":
|
|
434
|
+
return periods, 0, daily
|
|
435
|
+
salt = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_salt'").fetchone()
|
|
436
|
+
if not salt:
|
|
437
|
+
return periods, 0, daily
|
|
438
|
+
live = {archive_key(room_id, salt[0]) for room_id in rooms}
|
|
439
|
+
retained = {r[0] for r in connection.execute("SELECT DISTINCT archive_key FROM analytics_sealed_days")} - live
|
|
440
|
+
for key, day, counts, hist in connection.execute("""SELECT archive_key,day,counts,histograms
|
|
441
|
+
FROM analytics_sealed_days WHERE day>=? AND day<?""", (dates["previous_from"], dates["to"])):
|
|
442
|
+
if key not in retained:
|
|
443
|
+
continue
|
|
444
|
+
totals, bins = periods[int(day >= dates["from"])]
|
|
445
|
+
counts = json.loads(counts)
|
|
446
|
+
totals.update(counts)
|
|
447
|
+
if day >= dates["from"]:
|
|
448
|
+
daily[day].update(counts)
|
|
449
|
+
for name, weights in json.loads(hist).items():
|
|
450
|
+
bins[name].update(weights)
|
|
451
|
+
return periods, len(retained), daily
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def daily_overview(dates, facts, executions, sealed_days, now):
|
|
455
|
+
"""Split running intervals at local midnight, including 23- and 25-hour days."""
|
|
456
|
+
first, end = map(date.fromisoformat, (dates["from"], dates["to"]))
|
|
457
|
+
days = [first + timedelta(days=i) for i in range((end-first).days + 1)]
|
|
458
|
+
zone = report_zone(dates["tz"])
|
|
459
|
+
if zone is not None:
|
|
460
|
+
bounds = [int(datetime.combine(day, time.min, zone).timestamp()) for day in days]
|
|
461
|
+
else:
|
|
462
|
+
# Limit each ICU subprocess command line on Windows.
|
|
463
|
+
bounds = []
|
|
464
|
+
for offset in range(0, len(days), 100):
|
|
465
|
+
bounds.extend(node_calendar(dates["tz"], *map(str, days[offset:offset+100])))
|
|
466
|
+
rows = []
|
|
467
|
+
for day in days[:-1]:
|
|
468
|
+
label = str(day)
|
|
469
|
+
counts = sealed_days.get(label, {})
|
|
470
|
+
rows.append({"date": label, **{k: counts.get(k, 0) for k in ("initiated", "ended", "unassisted", "execution_seconds")}})
|
|
471
|
+
for stamp, key, value in facts:
|
|
472
|
+
if key in ("initiated", "ended", "unassisted") and bounds[0] <= stamp < bounds[-1]:
|
|
473
|
+
rows[bisect_right(bounds, stamp)-1][key] += value
|
|
474
|
+
for row in executions:
|
|
475
|
+
left = max(bounds[0], row["created_at"])
|
|
476
|
+
right = min(bounds[-1], row["finished_at"] or now, now)
|
|
477
|
+
index = bisect_right(bounds, left)-1
|
|
478
|
+
while left < right:
|
|
479
|
+
boundary = min(right, bounds[index+1])
|
|
480
|
+
rows[index]["execution_seconds"] += boundary-left
|
|
481
|
+
left, index = boundary, index+1
|
|
482
|
+
return rows
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def snapshot(connection, params, cache, now):
|
|
486
|
+
"""Build one SQLite read snapshot, caching only within the same server and room scope."""
|
|
487
|
+
earliest = None
|
|
488
|
+
if params.get("range") == "all" and "from" not in params and "to" not in params:
|
|
489
|
+
first = connection.execute("SELECT MIN(created_at) FROM member_requests").fetchone()[0]
|
|
490
|
+
sealed_first = connection.execute("SELECT MIN(day) FROM analytics_sealed_days").fetchone()[0]
|
|
491
|
+
candidates = [int(first)] if first else []
|
|
492
|
+
if sealed_first:
|
|
493
|
+
candidates.append(int(datetime.combine(date.fromisoformat(sealed_first), time.min, timezone.utc).timestamp()))
|
|
494
|
+
earliest = min(candidates) if candidates else None
|
|
495
|
+
dates, (previous, start, end) = period(params, now, earliest)
|
|
496
|
+
mode = params.get("scope", "all")
|
|
497
|
+
if mode not in ("all", "current"):
|
|
498
|
+
raise ValueError("scope ∈ {all, current}")
|
|
499
|
+
connection.execute("BEGIN")
|
|
500
|
+
rooms = tuple(r[0] for r in connection.execute("SELECT id FROM rooms ORDER BY id"))
|
|
501
|
+
revision = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_revision'").fetchone()
|
|
502
|
+
key = (tuple(dates.values()), rooms, mode, revision[0] if revision else None)
|
|
503
|
+
hit = cache.get(key)
|
|
504
|
+
if hit and monotonic() < hit[0]:
|
|
505
|
+
return hit[1]
|
|
506
|
+
requests = connection.execute(REQUESTS).fetchall()
|
|
507
|
+
executions = connection.execute(EXECUTIONS, (end, start, start)).fetchall()
|
|
508
|
+
revived = {r[0] for r in connection.execute("""SELECT DISTINCT json_extract(data,'$.execution_id') FROM room_events
|
|
509
|
+
WHERE kind='execution.changed' AND json_extract(data,'$.from_status')='failed' AND json_extract(data,'$.status')='started'""")}
|
|
510
|
+
attempts = [r for r in executions if r["created_at"] >= start]
|
|
511
|
+
assigned = [r for r in requests if start <= r["created_at"] < end]
|
|
512
|
+
members = member_stats(attempts, assigned, revived)
|
|
513
|
+
models = member_stats(attempts, assigned, revived, by_model=True)
|
|
514
|
+
(prior, sealed), retained, sealed_days = sealed_periods(connection, mode, rooms, dates)
|
|
515
|
+
facts = list(overview_facts(requests))
|
|
516
|
+
activity = actions(connection, start, end)
|
|
517
|
+
for group in activity.values():
|
|
518
|
+
for name in group:
|
|
519
|
+
group[name] += sealed[0][name]
|
|
520
|
+
scope = {"mode": mode, "rooms": len(rooms), "sealed_rooms": retained, "included_rooms": len(rooms) + retained,
|
|
521
|
+
"includes_archived": True, "sealed_day_tz": "UTC", "sealed_counts": SEALED_COUNTS,
|
|
522
|
+
"sealed_distributions": SEALED_DISTRIBUTIONS,
|
|
523
|
+
"current_only": ["folders", "peak", "queue", "affected_requests", "members", "models", "insights"]}
|
|
524
|
+
result = dict(range=dates, scope=scope,
|
|
525
|
+
overview=overview(facts, start, end, sealed), previous=overview(facts, previous, start, prior),
|
|
526
|
+
time={**time_stats(connection, requests, executions, (start, end), now, sealed), **activity},
|
|
527
|
+
members=members, models=models, insights=insights(connection, members, start, end))
|
|
528
|
+
result["overview"]["daily"] = daily_overview(dates, facts, executions, sealed_days, now)
|
|
529
|
+
if len(cache) >= CACHE_ENTRIES:
|
|
530
|
+
cache.clear()
|
|
531
|
+
cache[key] = (monotonic() + CACHE_SECONDS, result)
|
|
532
|
+
return result
|