ai_co_discuss 0.5.19 → 0.5.20
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-participant/SKILL.md +2 -1
- package/.agents/skills/share-card/SKILL.md +15 -0
- package/.agents/skills/share-card/references/share-card.md +43 -0
- package/backend/execution_diagnostics.py +149 -0
- package/backend/free_room.py +133 -40
- package/backend/message_queue.py +6 -4
- package/backend/room_trace.py +219 -0
- package/backend/schema.sql +7 -1
- package/backend/server.py +113 -8
- package/docs/en/guide/cli.md +20 -0
- package/docs/en/guide/faq.md +1 -0
- package/docs/en/guide/members.md +3 -1
- package/docs/en/guide/rooms.md +7 -3
- package/docs/en/guide/working.md +9 -4
- package/docs/guide/cli.md +20 -0
- package/docs/guide/faq.md +1 -0
- package/docs/guide/members.md +3 -1
- package/docs/guide/rooms.md +7 -3
- package/docs/guide/working.md +9 -4
- package/frontend/locales/en/app.json +8 -0
- package/frontend/locales/en/backend.json +5 -0
- package/frontend/locales/en/discussion.json +10 -3
- package/frontend/locales/en/execution-diagnostics.json +32 -0
- package/frontend/locales/en/room.json +1 -0
- package/package.json +3 -2
- package/runner/adapters/antigravity_cli.mjs +15 -1
- package/runner/adapters/api.mjs +27 -3
- package/runner/adapters/api_images.mjs +1 -1
- package/runner/adapters/api_pi.mjs +30 -1
- package/runner/adapters/cli.mjs +15 -6
- package/runner/adapters/codex_bridge.mjs +20 -6
- package/runner/adapters/codex_cli.mjs +2 -1
- package/runner/codiscuss.mjs +7 -0
- package/runner/discuss.py +24 -2
- package/runner/discussion_launch.mjs +1 -1
- package/runner/discussion_setup.mjs +1 -1
- package/runner/discussion_skills.mjs +1 -1
- package/runner/expert_prompts.mjs +4 -3
- package/runner/free_runner.mjs +102 -24
- package/runner/i18n_en.mjs +45 -2
- package/runner/remote_launch.mjs +2 -2
- package/runner/share_card.mjs +1314 -0
- package/runner/share_service.mjs +25 -7
- package/runner/share_shared.mjs +28 -7
- package/runner/site_deploy.mjs +125 -4
- package/runner/timeline_metrics.mjs +185 -0
- package/runner/workflows.mjs +12 -1
- package/web/app.js +303 -81
- package/web/i18n.js +3 -3
- package/web/modern.css +1 -1
- package/web/modern.js +100 -69
|
@@ -19,6 +19,7 @@ description: "AI CoDiscuss 的通用参与技能,所有参与者(包括主
|
|
|
19
19
|
| 写入结果不明、被拒、超长正文 | [写入与恢复](references/writing.md) |
|
|
20
20
|
| 接力(`sequence`)、向用户提问(`question`)、生图(`image`)、主动发言 | [按需场景](references/situations.md) |
|
|
21
21
|
| 回答需要用户亲手操作的演示(交互式可视化,正文里的 `visual` 代码块) | [交付交互式可视化](references/interactive-html.md) |
|
|
22
|
+
| 为本房间或指定房间制作分享卡封面 | [share-card](../share-card/SKILL.md) |
|
|
22
23
|
|
|
23
24
|
## 硬约束
|
|
24
25
|
|
|
@@ -32,7 +33,7 @@ description: "AI CoDiscuss 的通用参与技能,所有参与者(包括主
|
|
|
32
33
|
|
|
33
34
|
## 命令与身份
|
|
34
35
|
|
|
35
|
-
- 用 `codiscuss room …`、`codiscuss message …` 等;任务或用户指定了 CLI 路径就沿用,未安装时用 `python 路径/runner/discuss.py …`。裸 `codiscuss`
|
|
36
|
+
- 用 `codiscuss room …`、`codiscuss message …` 等;任务或用户指定了 CLI 路径就沿用,未安装时用 `python 路径/runner/discuss.py …`。裸 `codiscuss` 会启动服务,不要单独运行。查命令看 `codiscuss --help`(定位房间或排障见“排障速查”),查参数用 `codiscuss schema 命令`。
|
|
36
37
|
- 任务凭据已绑定站点、房间、身份与本次执行:命令省略房间、`--as`、`--execution`、`--submission-id`,由 CLI 补齐。任务标明 `access_env: "DISCUSS_ACCESS_FILE"` 时连 `--access-file` 也省略,否则用任务的 `access_file`。下文命令里的 `ROOM`、`--as`、执行编号只在没有绑定凭据时填写。站点、房间和身份以任务或用户指定值为准,不从网页或聊天推测;文件权限以任务的项目与 `cwd` 为准,CLI 所在仓库不是讨论项目。
|
|
37
38
|
- 回答正文写成 UTF-8 草稿文件,用 `message post --body-file 草稿.md` 提交(需要摘要时草稿开头写 `---`、`summary: 摘要`、`---`)。房间按 Markdown 显示。
|
|
38
39
|
- 不超过 200 字的一两句短答可用快捷发言 `message post --body "回答"`,但正文不能含反引号、英文括号、`$`、`;`、`&`、`|`、`<`、`>` 或换行,含这些时改用 `--body-file`;超过 200 字 CLI 直接拒收。(只能运行 codiscuss 命令时,带这些符号的命令会被当成拼接其他命令而整条拒绝;PowerShell 还会改写引号里的 `$` 与反引号。被拒时程序会把原因发回给你,照提示改正后重交。)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: share-card
|
|
3
|
+
description: 为 AI CoDiscuss 当前房间或指定房间制作分享卡封面。用户只需给出想突出的内容,例如成品、协作过程或讨论结论。按房间真实素材制作并交付可上传的 PNG。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# 房间分享卡
|
|
7
|
+
|
|
8
|
+
从用户给的侧重点做出一张可直接使用的封面。示例:`$share-card 为 <房间链接> 做分享卡,重点展示最终产品。` 在目标房间内说“重点展示最终产品”即可。
|
|
9
|
+
|
|
10
|
+
1. **找到房间。** 优先用本次消息或上下文里明确指定的房间。链接取查询参数 `room`,ID 可直接用,只有房间名时用 `codiscuss room list` 匹配;重名且无法确定时再问。没有指定其他房间时用当前任务绑定的房间。跨房间只读同一站点的素材,保留当前任务凭据。
|
|
11
|
+
2. **按主题取材。** 运行 `codiscuss share-card materials [房间ID]`,同站点完整链接可用 `--site <链接的源站>` 核对。侧重产品就先看真实成品图和交付结果,侧重协作就看并发曲线和执行统计,侧重讨论就提炼分歧和结论。根据 `scope` 标明部分统计,省略无法核实的内容。数字、操作步骤、文件路径由你处理。
|
|
12
|
+
3. **制作并检查 PNG。** 在自己的草稿目录写 750 CSS 像素宽的静态 HTML,图片用本地素材,图表可用内联 SVG。运行 `codiscuss share-card render cover.html --out cover.png`,检查成图清晰且内容完整。二维码、域名和到期时间由分享面板追加。完整素材字段、尺寸和渲染说明见[制卡参考](references/share-card.md)。
|
|
13
|
+
4. **交付成图。** 在房间任务中用 `codiscuss attachment upload --file <PNG路径>` 上传至接单房间,再用 `message post --attachment <返回的附件ID>` 随本次回答提交。跨房间时说明到目标房间的“已分享 → 查看分享卡 → 上传封面”选用这张 PNG。终端里直接交付可打开的文件路径。
|
|
14
|
+
|
|
15
|
+
若本机安装版尚无 `share-card` 子命令,使用可访问的共议源码入口 `node "<仓库>/runner/codiscuss.mjs" share-card ...`。开发机可在 `~/.codiscuss/share-card-cli.txt` 指定该入口的绝对路径。普通房间和附件命令仍用任务指定的 CLI。
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 分享卡素材与导出参考
|
|
2
|
+
|
|
3
|
+
用户请你为本房间或同站点其他房间制作一张分享卡封面时读本页。分享面板只接收成图(PNG / JPG / WebP),并在封面下方自动拼接统一的扫码底栏(二维码、分享域名与最新有效期)。
|
|
4
|
+
|
|
5
|
+
## 工作流程
|
|
6
|
+
|
|
7
|
+
### 1. 读取可分享素材与协作指标
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
codiscuss share-card materials [房间ID]
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- 省略房间 ID 时读取当前任务绑定的房间;传入同站点其他房间的 ID 可跨房间只读取材(不发送本房间 token,仅带只读头);带任务凭据时目标站点必须与凭据绑定站点一致。
|
|
14
|
+
- 返回结果按可分享口径整理:排除已撤回消息及其关联执行和外部执行、不含私聊、把已知项目目录改写为相对路径、家目录改写为 `~`,并跳过疑似含密钥或联系方式的敏感摘录。
|
|
15
|
+
- `metrics` 使用与网页“执行 → 并发全景”相同的指标定义(`busy_text` / `busy_percent`、`self_started` / `runs` / `self_started_percent`、`unattended`、`peak_concurrency`、`active_members`),但口径存在两处差异:本命令分页回溯历史,只统计关联消息可确认仍公开的执行。消息被撤回或落在读取范围以外时,相应执行也会省略。读取上限为 20 页时间线、10000 条消息。网页“并发全景”默认只加载最近 100 次且不剔除撤回执行。使用数字前先核对 `scope.truncated`(`messages_truncated` / `timeline_truncated`)与 `scope.curve_sampled`,若为 `true` 应在封面上按部分统计口径措辞、不宣称全量精确值。
|
|
16
|
+
- `concurrency_curve` 给出归一化 `[0, 1]` 时间步(`steps`)、空闲区间(`idle_gaps`)与任务分段(`tasks`),可直接用内联 SVG 画并发曲线或柱状图。
|
|
17
|
+
- `materials` 给出开场实质需求(`opening_request`,若房间里只有问题卡回执则为 `null`)、代表发言索引(`highlights`)、房间图片附件(`images`,含已加引号的下载命令)、附件分类统计(`attachments_by_kind`)与已上线站点(`sites`)。需要某条发言的完整原文时,用 `codiscuss message view` 补读(不要引用已撤回消息或私聊)。
|
|
18
|
+
|
|
19
|
+
### 2. 创作静态 HTML 封面(或直接使用成图)
|
|
20
|
+
|
|
21
|
+
根据用户这次想突出的重点自由搭配版式——例如晒产品交付(放成品图 + 一句话卖点 + 交付物徽章)、晒长时间多 AI 无人值守(放大并发指标 + SVG 并发全景图)、或晒讨论争点(提炼议题 + 有出处的各方观点)。
|
|
22
|
+
|
|
23
|
+
**规格与约束**:
|
|
24
|
+
- **尺寸**:固定宽 `750 CSS px`(导出默认 2×,即 `1500 px` 宽);建议高 `560–1100 CSS px`,最大不超过 `1500 CSS px`(高宽比 ≤ 2:1)。
|
|
25
|
+
- **底部留白与衔接**:不要在封面里画二维码、分享链接、有效期或“扫码阅读”。程序会在封面正下方无缝拼接标准扫码底栏,并可吸取封面最底行的背景色,底部保持干净的纯色或平滑底色过渡最协调。
|
|
26
|
+
- **纯静态与离线**:`render` 在离线沙箱浏览器里渲染并启用严格 CSP(`script-src 'none'`、`connect-src 'none'`),**不执行 JavaScript、不请求外网字体或外链图片**。
|
|
27
|
+
- 全部样式用内联 `<style>`,图表和图标用内联 `<svg>`;中文字体优先系统无衬线字体栈(如 `"PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`)。
|
|
28
|
+
- 需要嵌入房间里的图片时,先用 `codiscuss attachment download` 下到草稿目录中与 HTML 同级(或子目录),用相对路径 `<img src="./poster.png">` 或 `data:` URL 引入。
|
|
29
|
+
- **事实与脱敏**:统计数字和成员名以 `materials` 返回的真实数据为准,不编造;不放入密钥、令牌、个人联系方式、本机绝对路径或已撤回消息内容;正文口吻面向外部读者,不写“附在这条消息里”“我在浏览器点了一遍”这类内部汇报话术。
|
|
30
|
+
|
|
31
|
+
### 3. 导出为 PNG 并自查交付
|
|
32
|
+
|
|
33
|
+
把静态 HTML 写在草稿目录,运行:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
codiscuss share-card render cover.html --out cover.png
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
- 常用可选参数:`--width 750`、`--height N`(省略时按内容自适应高度,受 `--max-height 1500` 约束)、`--scale 2`、`--background #12141c`。
|
|
40
|
+
- 命令返回 JSON 回执,含 `output`、`width_px`、`height_px`、`clipped`(内容是否超出最大高度)。若 `clipped: true`,收紧排版后重导出。
|
|
41
|
+
- 持任务凭据运行时,输入 HTML 与输出 PNG 均受成员文件权限约束:只读成员须把 HTML 与导出的 PNG 放在自己的草稿目录(`draft_directory`)内;可读自己的运行时目录(任务附件副本)。(房主在本机终端不带任务凭据手动运行时,沿用当前系统账号的文件权限。)
|
|
42
|
+
- `render` 经进程私有控制通道(`--remote-debugging-pipe`)驱动系统可信安装位置的沙箱浏览器,不开 TCP 调试端口,并拦截顶层跳转(如 `meta refresh`)。若系统未安装浏览器或操作系统沙箱不可用,命令会明确报错;此时如实说明,或改用房间已有成图 / 生图工具(有 `image` 字段时)。
|
|
43
|
+
- 打开导出的 `cover.png` 检查文字和留白。用当前任务的 CLI 上传图片后,通过 `message post --attachment <附件ID>` 随回答交付。同房间可在分享面板点“选择房间图片”,跨房间可下载后在目标房间点“上传封面”。
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Store bounded evidence reported by the runner and expose it only on authorized execution reads."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
IDENTIFIER = re.compile(r"[A-Za-z0-9_-]{1,128}\Z")
|
|
8
|
+
REVISION = re.compile(r"[0-9a-f]{7,64}\Z")
|
|
9
|
+
TIME_LIMITS = ("total_ms", "idle_ms")
|
|
10
|
+
MAX_LIMIT_MS = 7 * 24 * 60 * 60 * 1000
|
|
11
|
+
MAX_ITEMS = 50
|
|
12
|
+
ACTION_FIELDS = {"renew", "segments", "delivery", "fail", "report"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def integer(value, maximum):
|
|
16
|
+
"""Accept only positive integers in the report's supported range."""
|
|
17
|
+
return value if type(value) is int and 0 < value <= maximum else None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def selected(value, options):
|
|
21
|
+
"""Accept a known protocol value or None."""
|
|
22
|
+
return value if isinstance(value, str) and value in options else None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def matching(value, pattern):
|
|
26
|
+
"""Accept a bounded identifier or revision, never a path or free text."""
|
|
27
|
+
return value if isinstance(value, str) and pattern.fullmatch(value) else None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def binding(value):
|
|
31
|
+
"""Keep a delivery's selected workflow metadata, without prompts or paths."""
|
|
32
|
+
if not isinstance(value, dict) or not matching(value.get("id"), IDENTIFIER):
|
|
33
|
+
return None
|
|
34
|
+
skills = value.get("skills")
|
|
35
|
+
return {"id": value["id"], "revision": matching(value.get("revision"), REVISION),
|
|
36
|
+
"card": matching(value.get("card"), IDENTIFIER),
|
|
37
|
+
"sub_workflow": matching(value.get("sub_workflow"), IDENTIFIER),
|
|
38
|
+
"sub_revision": matching(value.get("sub_revision"), REVISION),
|
|
39
|
+
"skills": [skill for skill in skills[:MAX_ITEMS] if matching(skill, IDENTIFIER)] if isinstance(skills, list) else []}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def append_unique(data, key, item):
|
|
43
|
+
"""Retain recent distinct evidence when the same progress report is retried."""
|
|
44
|
+
items = data.setdefault(key, [])
|
|
45
|
+
if item not in items:
|
|
46
|
+
items.append(item)
|
|
47
|
+
del items[:-MAX_ITEMS]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def merge_retry(data, item, layers, now):
|
|
51
|
+
"""Distinguish model, adapter, and runner retries and omit unrecognized fields."""
|
|
52
|
+
if not isinstance(item, dict):
|
|
53
|
+
return
|
|
54
|
+
layer = selected(item.get("layer"), layers)
|
|
55
|
+
state = selected(item.get("state"), ("started", "ended", "succeeded", "failed", "waiting"))
|
|
56
|
+
if not layer or not state:
|
|
57
|
+
return
|
|
58
|
+
attempt = integer(item.get("attempt"), 10_000)
|
|
59
|
+
if layer == "runner":
|
|
60
|
+
append_unique(data, "retries", {"layer": layer, "state": state, "attempt": attempt,
|
|
61
|
+
"mode": selected(item.get("mode"), ("resume", "redeliver"))})
|
|
62
|
+
elif (at := integer(item.get("at"), now + MAX_LIMIT_MS)) is not None:
|
|
63
|
+
append_unique(data, "retries", {"layer": layer, "state": state, "attempt": attempt, "at": at})
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def merge_progress(data, report, now):
|
|
67
|
+
"""Merge only consumed diagnostic fields, keeping latest confirmed activity."""
|
|
68
|
+
if (at := integer(report.get("last_activity_at"), now + MAX_LIMIT_MS)) is not None:
|
|
69
|
+
data["last_activity_at"] = max(at, data.get("last_activity_at", 0))
|
|
70
|
+
if isinstance(report.get("timeout_limits"), dict):
|
|
71
|
+
limits = {key: limit for key in TIME_LIMITS if (limit := integer(report["timeout_limits"].get(key), MAX_LIMIT_MS)) is not None}
|
|
72
|
+
if limits:
|
|
73
|
+
data["timeout_limits"] = limits
|
|
74
|
+
if kind := selected(report.get("timeout_kind"), ("total", "idle")):
|
|
75
|
+
data["timeout_kind"] = kind
|
|
76
|
+
if isinstance(report.get("retries"), list):
|
|
77
|
+
for item in report["retries"][-MAX_ITEMS:]:
|
|
78
|
+
merge_retry(data, item, ("model", "adapter"), now)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def merge_interjection(data, report, payload, now):
|
|
82
|
+
"""A delayed empty transport report cannot erase a matching software receipt."""
|
|
83
|
+
transport = selected(report.get("transport"), ("steer", "resumed_turn"))
|
|
84
|
+
interjection_id = integer(payload.get("interjection_id"), 2**53 - 1)
|
|
85
|
+
if not transport or not interjection_id:
|
|
86
|
+
return
|
|
87
|
+
reports = data.setdefault("interjections", {})
|
|
88
|
+
receipt = reports.setdefault(str(interjection_id), {"transport": transport, "confirmed_at": None,
|
|
89
|
+
"status": selected(payload.get("status"), ("delivered", "failed"))})
|
|
90
|
+
if payload.get("status") == "delivered" and receipt["confirmed_at"] is None:
|
|
91
|
+
receipt["confirmed_at"] = integer(report.get("confirmed_at"), now + MAX_LIMIT_MS)
|
|
92
|
+
while len(reports) > MAX_ITEMS:
|
|
93
|
+
del reports[next(iter(reports))]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def stored_diagnostics(connection, execution_id):
|
|
97
|
+
"""Read one execution's private diagnostic metadata."""
|
|
98
|
+
row = connection.execute("SELECT details FROM execution_diagnostics WHERE execution_id=?", (execution_id,)).fetchone()
|
|
99
|
+
return json.loads(row[0]) if row else {}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def record_diagnostics(connection, execution_id, payload, now):
|
|
103
|
+
"""Persist authorized evidence inside the transaction of the original execution action."""
|
|
104
|
+
action = payload.get("action")
|
|
105
|
+
report = payload.get("diagnostics")
|
|
106
|
+
if action not in ("renew", "report") and (not isinstance(report, dict) or not report):
|
|
107
|
+
return
|
|
108
|
+
report = report if isinstance(report, dict) else {}
|
|
109
|
+
data = stored_diagnostics(connection, execution_id)
|
|
110
|
+
if action == "renew":
|
|
111
|
+
data["last_heartbeat_at"] = max(now, data.get("last_heartbeat_at", 0))
|
|
112
|
+
if action in ACTION_FIELDS:
|
|
113
|
+
merge_progress(data, report, now)
|
|
114
|
+
if action in ACTION_FIELDS and "workflow" in report:
|
|
115
|
+
workflow = binding(report["workflow"])
|
|
116
|
+
if workflow is not None or report["workflow"] is None:
|
|
117
|
+
append_unique(data, "workflow_bindings", workflow)
|
|
118
|
+
if action in ("retry_wait", "retry_start"):
|
|
119
|
+
merge_retry(data, report.get("retry"), ("runner",), now)
|
|
120
|
+
if action == "interjection":
|
|
121
|
+
merge_interjection(data, report, payload, now)
|
|
122
|
+
if action == "report":
|
|
123
|
+
attribution = report.get("file_attribution")
|
|
124
|
+
omitted = attribution.get("omitted") if isinstance(attribution, dict) else None
|
|
125
|
+
if type(omitted) is int and 0 <= omitted <= 2**53 - 1:
|
|
126
|
+
data["omitted_files"] = omitted
|
|
127
|
+
else:
|
|
128
|
+
data.pop("omitted_files", None)
|
|
129
|
+
if data:
|
|
130
|
+
connection.execute("""INSERT INTO execution_diagnostics(execution_id,details) VALUES(?,?)
|
|
131
|
+
ON CONFLICT(execution_id) DO UPDATE SET details=excluded.details""",
|
|
132
|
+
(execution_id, json.dumps(data, ensure_ascii=False, separators=(",", ":"))))
|
|
133
|
+
elif action == "report":
|
|
134
|
+
connection.execute("DELETE FROM execution_diagnostics WHERE execution_id=?", (execution_id,))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def diagnostic_detail(connection, row, owner=False):
|
|
138
|
+
"""Expose file counts to execution readers and paths only where file patches are already authorized."""
|
|
139
|
+
data = stored_diagnostics(connection, row["id"])
|
|
140
|
+
omitted = data.pop("omitted_files", None)
|
|
141
|
+
if row["changes"]:
|
|
142
|
+
changes = json.loads(row["changes"])
|
|
143
|
+
edited = set(json.loads(row["edited"])) if row["edited"] else None
|
|
144
|
+
files = {"observed": len(changes), "recorded_writes": len(edited) if edited is not None else None,
|
|
145
|
+
"provisional": bool(row["changes_provisional"]), "omitted": omitted}
|
|
146
|
+
if owner:
|
|
147
|
+
files["paths"] = [{"path": path, "recorded_write": path in edited if edited is not None else None} for path in changes]
|
|
148
|
+
data["file_attribution"] = files
|
|
149
|
+
return data
|
package/backend/free_room.py
CHANGED
|
@@ -15,6 +15,7 @@ import re
|
|
|
15
15
|
import time
|
|
16
16
|
import uuid
|
|
17
17
|
|
|
18
|
+
from .execution_diagnostics import diagnostic_detail, record_diagnostics
|
|
18
19
|
from .identity import MAX_ROOM_AGENTS, default_label, is_ai
|
|
19
20
|
from .message_queue import pause as pause_queue, queue_view
|
|
20
21
|
from .texts import Text, incoming_text, load_texts, save_text, text_payload
|
|
@@ -55,11 +56,25 @@ ROOM_EVENT_PAGE = 500
|
|
|
55
56
|
# start, so the page shows the wake-up there instead of a new card.
|
|
56
57
|
HOST_FAILED_SQL = """(SELECT CAST(substr(w.key,13) AS INTEGER) FROM free_host_wakes w WHERE r.purpose='notice'
|
|
57
58
|
AND w.room_id=r.room_id AND w.message_id=r.message_id AND w.key LIKE 'host_failed:%' LIMIT 1)"""
|
|
58
|
-
LAYOUT_AFTER_SQL = f"""COALESCE((SELECT
|
|
59
|
-
WHERE f.execution_id={HOST_FAILED_SQL}
|
|
59
|
+
LAYOUT_AFTER_SQL = f"""COALESCE((SELECT MAX(l.after_message_id) FROM member_requests f JOIN request_layout l ON l.request_id=f.id
|
|
60
|
+
WHERE f.execution_id={HOST_FAILED_SQL} OR f.id IN (SELECT request_id FROM retried_requests WHERE execution_id={HOST_FAILED_SQL})),
|
|
61
|
+
(SELECT after_message_id FROM request_layout WHERE request_id=r.id),r.message_id)"""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def layout_at_sql(execution_id_sql):
|
|
65
|
+
"""When the work behind request `r` started for execution `execution_id_sql`.
|
|
66
|
+
|
|
67
|
+
Only the first execution on a `host_failed:<id>` wake-up takes over the failed host execution's start time; a retry
|
|
68
|
+
of that wake-up starts at its own `created_at` so the new card follows the failed card chronologically.
|
|
69
|
+
"""
|
|
70
|
+
return f"""COALESCE(
|
|
71
|
+
CASE WHEN NOT EXISTS(SELECT 1 FROM retried_requests rr WHERE rr.request_id=r.id AND rr.execution_id<{execution_id_sql})
|
|
72
|
+
THEN (SELECT created_at FROM member_executions WHERE id={HOST_FAILED_SQL}) END,
|
|
73
|
+
(SELECT created_at FROM member_executions WHERE id={execution_id_sql}))"""
|
|
74
|
+
|
|
75
|
+
|
|
60
76
|
# When the work behind a request (aliased `r`) started, ordering cards under the same message: its execution's start.
|
|
61
|
-
LAYOUT_AT_SQL =
|
|
62
|
-
(SELECT created_at FROM member_executions WHERE id=r.execution_id))"""
|
|
77
|
+
LAYOUT_AT_SQL = layout_at_sql("r.execution_id")
|
|
63
78
|
# Rounds used and the owner's additions in the room's recent chains, for "第 2/3 轮"; parameter: the room.
|
|
64
79
|
# A round is a host dispatch (a batch) or a continue the host asked for (`free_host_wakes` with a `continue:` key); a
|
|
65
80
|
# relay's later steps in the same pass (`free_relay_steps`) ride on its first, so a whole pass is one round.
|
|
@@ -211,7 +226,8 @@ LATER_COLUMNS = {"room_members": {"access": "TEXT NOT NULL DEFAULT 'runner'", "s
|
|
|
211
226
|
"execution_capabilities": {"steer": "INTEGER", "resume": "INTEGER"},
|
|
212
227
|
"member_capabilities": {"image_model": "TEXT NOT NULL DEFAULT ''"},
|
|
213
228
|
"execution_failures": {"reset_at": "INTEGER NOT NULL DEFAULT 0"},
|
|
214
|
-
"free_host_checkins": {"idle_notice": "INTEGER NOT NULL DEFAULT 0"}
|
|
229
|
+
"free_host_checkins": {"idle_notice": "INTEGER NOT NULL DEFAULT 0"},
|
|
230
|
+
"retried_requests": {"retried_at": "INTEGER NOT NULL DEFAULT 0"}}
|
|
215
231
|
|
|
216
232
|
|
|
217
233
|
def migrate_free_tables(connection):
|
|
@@ -1024,7 +1040,13 @@ def recent_executions(connection, room_id, span=None):
|
|
|
1024
1040
|
(SELECT MAX({LAYOUT_AFTER_SQL}) FROM member_requests r WHERE r.execution_id=e.id
|
|
1025
1041
|
OR r.id IN (SELECT request_id FROM retried_requests WHERE execution_id=e.id)) AS layout_after,
|
|
1026
1042
|
EXISTS(SELECT 1 FROM retried_requests WHERE execution_id=e.id) AS retried,
|
|
1027
|
-
(SELECT
|
|
1043
|
+
(SELECT CAST(substr(w.key,13) AS INTEGER) FROM free_host_wakes w
|
|
1044
|
+
WHERE w.room_id=e.room_id AND w.key LIKE 'host_failed:%'
|
|
1045
|
+
AND w.message_id IN (SELECT message_id FROM member_requests WHERE execution_id=e.id
|
|
1046
|
+
UNION SELECT r.message_id FROM retried_requests rr JOIN member_requests r ON r.id=rr.request_id WHERE rr.execution_id=e.id)
|
|
1047
|
+
LIMIT 1) AS replaces_execution_id,
|
|
1048
|
+
(SELECT MIN({layout_at_sql("e.id")}) FROM member_requests r WHERE r.execution_id=e.id
|
|
1049
|
+
OR r.id IN (SELECT request_id FROM retried_requests WHERE execution_id=e.id)) AS layout_at,
|
|
1028
1050
|
(SELECT COUNT(*) FROM execution_notes WHERE execution_id=e.id) AS note_count,
|
|
1029
1051
|
(SELECT COUNT(*) FROM execution_segments WHERE source='free' AND execution_id=e.id
|
|
1030
1052
|
AND phase IN ('command','tool','editing')) AS step_count,
|
|
@@ -1039,7 +1061,10 @@ def recent_executions(connection, room_id, span=None):
|
|
|
1039
1061
|
rows = connection.execute(f"SELECT * FROM ({query}) WHERE layout_after>? AND layout_after<=? ORDER BY id DESC",
|
|
1040
1062
|
(room_id, span[0], MAX_MESSAGE_ID if span[1] is None else span[1]))
|
|
1041
1063
|
else:
|
|
1042
|
-
rows = connection.execute(
|
|
1064
|
+
rows = connection.execute(
|
|
1065
|
+
f"""{query} AND (e.status IN ('dispatched','started')
|
|
1066
|
+
OR e.id IN (SELECT id FROM member_executions WHERE room_id=? ORDER BY id DESC LIMIT ?))
|
|
1067
|
+
ORDER BY e.id DESC""", (room_id, room_id, RECENT_EXECUTIONS))
|
|
1043
1068
|
executions = []
|
|
1044
1069
|
positions = relay_positions(connection, room_id)
|
|
1045
1070
|
for row in rows:
|
|
@@ -1057,7 +1082,7 @@ def recent_executions(connection, room_id, span=None):
|
|
|
1057
1082
|
"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 "",
|
|
1058
1083
|
"capabilities": reported_capabilities(row), "stop_result": row["stop_result"] or "",
|
|
1059
1084
|
"late_answer": json.loads(row["late_answer"]) if row["late_answer"] else None, "background": bool(row["background"]),
|
|
1060
|
-
"retried": bool(row["retried"]), "line": line,
|
|
1085
|
+
"retried": bool(row["retried"]), "replaces_execution_id": row["replaces_execution_id"], "line": line,
|
|
1061
1086
|
"interjections": execution_interjections(connection, row["id"], row["status"]),
|
|
1062
1087
|
"retry": execution_retry(connection, row["id"])})
|
|
1063
1088
|
return executions
|
|
@@ -1139,6 +1164,34 @@ GROUP_STATE_SQL = f"""SELECT json_object(
|
|
|
1139
1164
|
FROM rooms WHERE id=?"""
|
|
1140
1165
|
|
|
1141
1166
|
|
|
1167
|
+
def room_failure_wakes(connection, room_id, span=None):
|
|
1168
|
+
"""Map host-failure wake-up notice messages to the failed execution they replaced; `span` (low, high] pages history."""
|
|
1169
|
+
if span:
|
|
1170
|
+
rows = connection.execute(
|
|
1171
|
+
"SELECT key,message_id FROM free_host_wakes WHERE room_id=? AND key LIKE 'host_failed:%' AND message_id>? AND message_id<=? ORDER BY message_id DESC",
|
|
1172
|
+
(room_id, span[0], MAX_MESSAGE_ID if span[1] is None else span[1]))
|
|
1173
|
+
else:
|
|
1174
|
+
rows = connection.execute(
|
|
1175
|
+
"SELECT key,message_id FROM free_host_wakes WHERE room_id=? AND key LIKE 'host_failed:%' ORDER BY message_id DESC LIMIT ?",
|
|
1176
|
+
(room_id, RECENT_EXECUTIONS))
|
|
1177
|
+
return [{"message_id": row["message_id"], "execution_id": int(row["key"][len("host_failed:"):])} for row in rows]
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def room_quiet_checkins(connection, room_id, span=None):
|
|
1181
|
+
"""Timed checks the host answered without dispatching; `span` (low, high] returns pairs touching that history page."""
|
|
1182
|
+
base = """SELECT w.message_id,r.answer_id FROM free_host_wakes w
|
|
1183
|
+
JOIN member_requests r ON r.message_id=w.message_id AND r.purpose='notice' AND r.status='completed' AND r.answer_id IS NOT NULL
|
|
1184
|
+
WHERE w.room_id=? AND w.key LIKE 'checkin:%' AND NOT EXISTS (SELECT 1 FROM member_requests d WHERE d.message_id=r.answer_id)"""
|
|
1185
|
+
if span:
|
|
1186
|
+
high = MAX_MESSAGE_ID if span[1] is None else span[1]
|
|
1187
|
+
rows = connection.execute(
|
|
1188
|
+
f"{base} AND ((w.message_id>? AND w.message_id<=?) OR (r.answer_id>? AND r.answer_id<=?)) ORDER BY w.message_id DESC",
|
|
1189
|
+
(room_id, span[0], high, span[0], high))
|
|
1190
|
+
else:
|
|
1191
|
+
rows = connection.execute(f"{base} ORDER BY w.message_id DESC LIMIT ?", (room_id, RECENT_EXECUTIONS))
|
|
1192
|
+
return [dict(row) for row in rows]
|
|
1193
|
+
|
|
1194
|
+
|
|
1142
1195
|
def free_view(connection, room_id):
|
|
1143
1196
|
"""Summarize members, their live execution, recent requests and possible file conflicts."""
|
|
1144
1197
|
now = int(time.time())
|
|
@@ -1171,14 +1224,22 @@ def free_view(connection, room_id):
|
|
|
1171
1224
|
member["external"] = external_members.room_view_field(connection, row["id"])
|
|
1172
1225
|
members.append(member)
|
|
1173
1226
|
names = {row["id"]: row["name"] for row in connection.execute("SELECT id,name FROM room_members WHERE room_id=?", (room_id,))}
|
|
1174
|
-
|
|
1227
|
+
next_batch = next_batch_request_ids(connection, members)
|
|
1228
|
+
requests = [{**dict(row), "member": names.get(row["member_id"], ""), "retried": bool(row["retried"]),
|
|
1229
|
+
"next_batch": row["id"] in next_batch,
|
|
1175
1230
|
**session_request_source(connection, row["id"], row["message_id"]),
|
|
1176
1231
|
} for row in connection.execute(
|
|
1177
1232
|
"""SELECT id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose,created_by,created_at,
|
|
1178
1233
|
(SELECT reason FROM request_cancel_reasons c WHERE c.request_id=member_requests.id) AS cancel_reason,
|
|
1179
1234
|
(SELECT outcome FROM external_declines x WHERE x.request_id=member_requests.id) AS external_outcome,
|
|
1180
|
-
(SELECT after_message_id FROM request_layout l WHERE l.request_id=member_requests.id) AS layout_after
|
|
1181
|
-
|
|
1235
|
+
(SELECT after_message_id FROM request_layout l WHERE l.request_id=member_requests.id) AS layout_after,
|
|
1236
|
+
COALESCE((SELECT MAX(MAX(rr.retried_at, e.finished_at, e.created_at)) FROM retried_requests rr
|
|
1237
|
+
JOIN member_executions e ON e.id=rr.execution_id WHERE rr.request_id=member_requests.id),
|
|
1238
|
+
created_at) AS layout_at,
|
|
1239
|
+
EXISTS(SELECT 1 FROM retried_requests rr WHERE rr.request_id=member_requests.id) AS retried FROM member_requests
|
|
1240
|
+
WHERE room_id=? AND (status IN ('pending','delivering')
|
|
1241
|
+
OR id IN (SELECT id FROM member_requests WHERE room_id=? ORDER BY id DESC LIMIT ?))
|
|
1242
|
+
ORDER BY id DESC""", (room_id, room_id, RECENT_REQUESTS))]
|
|
1182
1243
|
chains = [dict(row) for row in connection.execute(
|
|
1183
1244
|
"SELECT chain_id,reason FROM free_chains WHERE room_id=? ORDER BY chain_id DESC LIMIT 10", (room_id,))]
|
|
1184
1245
|
max_rounds = chain_rounds(connection, room_id)
|
|
@@ -1189,14 +1250,9 @@ def free_view(connection, room_id):
|
|
|
1189
1250
|
"SELECT chain_id,asked_rounds,asked_reason FROM free_chain_holds WHERE room_id=? AND asked_rounds>0", (room_id,))}
|
|
1190
1251
|
chains = [{**chain, **asks.get(chain["chain_id"], {})} for chain in chains]
|
|
1191
1252
|
checkin = connection.execute("SELECT interval_seconds,due_at FROM free_host_checkins WHERE room_id=?", (room_id,)).fetchone()
|
|
1192
|
-
failure_wakes =
|
|
1193
|
-
"SELECT key,message_id FROM free_host_wakes WHERE room_id=? AND key LIKE 'host_failed:%' ORDER BY message_id DESC LIMIT ?",
|
|
1194
|
-
(room_id, RECENT_EXECUTIONS))]
|
|
1253
|
+
failure_wakes = room_failure_wakes(connection, room_id)
|
|
1195
1254
|
# A timed check the host answered without dispatching folds its answer into the check's own line.
|
|
1196
|
-
quiet_checkins =
|
|
1197
|
-
JOIN member_requests r ON r.message_id=w.message_id AND r.purpose='notice' AND r.status='completed' AND r.answer_id IS NOT NULL
|
|
1198
|
-
WHERE w.room_id=? AND w.key LIKE 'checkin:%' AND NOT EXISTS (SELECT 1 FROM member_requests d WHERE d.message_id=r.answer_id)
|
|
1199
|
-
ORDER BY w.message_id DESC LIMIT ?""", (room_id, RECENT_EXECUTIONS))]
|
|
1255
|
+
quiet_checkins = room_quiet_checkins(connection, room_id)
|
|
1200
1256
|
return {"failure_wakes": failure_wakes, "quiet_checkins": quiet_checkins, "host_checkin": {"minutes": checkin["interval_seconds"] // 60, "due_at": checkin["due_at"]} if checkin else None,
|
|
1201
1257
|
"members": members, "ended_externals": external_members.ended_view(connection, room_id),
|
|
1202
1258
|
"requests": requests[::-1], "executions": recent_executions(connection, room_id),
|
|
@@ -2924,8 +2980,8 @@ def stop_member_work(connection, member_id, reason, cancel_reason, keep_pending=
|
|
|
2924
2980
|
(member_id,)).fetchall():
|
|
2925
2981
|
# The interrupted turn's card stays under the message it was answering, marked stopped, after its requests move on.
|
|
2926
2982
|
if requeue:
|
|
2927
|
-
connection.execute("INSERT OR IGNORE INTO retried_requests (execution_id,request_id) SELECT ?,id FROM member_requests WHERE execution_id=?",
|
|
2928
|
-
(row["id"], row["id"]))
|
|
2983
|
+
connection.execute("INSERT OR IGNORE INTO retried_requests (execution_id,request_id,retried_at) SELECT ?,id,? FROM member_requests WHERE execution_id=?",
|
|
2984
|
+
(row["id"], int(time.time()), row["id"]))
|
|
2929
2985
|
finish_execution(connection, row["id"], "cancelled", reason, "pending" if requeue else "cancelled", "" if requeue else cancel_reason)
|
|
2930
2986
|
if not keep_pending:
|
|
2931
2987
|
record_cancel_reasons(connection, "member_id=? AND status='pending'", (member_id,), cancel_reason)
|
|
@@ -3380,19 +3436,11 @@ def one_line(connection, member_id, request_filter, request_values):
|
|
|
3380
3436
|
return (f"{request_filter} AND NOT {MAIN_LINE} AND NOT (purpose='ask' AND created_by<>?)", (*request_values, branch[0]))
|
|
3381
3437
|
|
|
3382
3438
|
|
|
3383
|
-
def
|
|
3384
|
-
"""
|
|
3385
|
-
client_id = str(payload.get("client_id", ""))
|
|
3386
|
-
if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
|
|
3387
|
-
(member["id"],)).fetchone():
|
|
3388
|
-
raise FileExistsError(Text("该成员已有进行中的执行;同一会话不并发续接"))
|
|
3389
|
-
if quota_held_until(connection, member["id"]):
|
|
3390
|
-
raise FileExistsError(Text("该成员额度已用尽,暂停投递;等额度重置后重试它失败的执行,或改派其他成员"))
|
|
3391
|
-
if held_until(connection, member["id"]):
|
|
3392
|
-
raise FileExistsError(Text("该成员上一轮已作废但本机无法停止,可能仍在处理;等它结束或等待时限到后再投递"))
|
|
3439
|
+
def next_batch_filter(connection, member_id, request_ids=None):
|
|
3440
|
+
"""Return `(where_sql, values)` selecting the pending requests `open_execution` will bundle next, or `None` if none."""
|
|
3393
3441
|
# A group request waits for the runner to choose how everyone answers; it is never delivered itself.
|
|
3394
3442
|
pending = connection.execute("""SELECT id,purpose,EXISTS(SELECT 1 FROM review_plans WHERE review_batch_id=member_requests.message_id AND reviewer_id=member_requests.member_id) AS review FROM member_requests
|
|
3395
|
-
WHERE member_id=? AND status='pending' AND purpose<>'group' ORDER BY id""", (
|
|
3443
|
+
WHERE member_id=? AND status='pending' AND purpose<>'group' ORDER BY id""", (member_id,)).fetchall()
|
|
3396
3444
|
if request_ids is not None:
|
|
3397
3445
|
# An external member's computer agreed to these requests only; the others stay pending for its owner to decide.
|
|
3398
3446
|
missing = sorted(set(request_ids) - {row["id"] for row in pending})
|
|
@@ -3401,10 +3449,9 @@ def open_execution(connection, room_id, member, payload, request_ids=None):
|
|
|
3401
3449
|
pending = [row for row in pending if row["id"] in request_ids]
|
|
3402
3450
|
session_purpose = next((row["purpose"] for row in pending if row["purpose"] == "discuss"), None)
|
|
3403
3451
|
if not pending:
|
|
3404
|
-
|
|
3452
|
+
return None
|
|
3405
3453
|
if session_purpose:
|
|
3406
|
-
request_filter = "purpose=?"
|
|
3407
|
-
request_values = (session_purpose,)
|
|
3454
|
+
request_filter, request_values = "purpose=?", (session_purpose,)
|
|
3408
3455
|
elif pending[0]["review"]:
|
|
3409
3456
|
request_filter, request_values = "id=?", (pending[0]["id"],)
|
|
3410
3457
|
else:
|
|
@@ -3414,7 +3461,43 @@ def open_execution(connection, room_id, member, payload, request_ids=None):
|
|
|
3414
3461
|
request_filter += f" AND id IN ({','.join('?' * len(request_ids))})"
|
|
3415
3462
|
request_values = (*request_values, *request_ids)
|
|
3416
3463
|
if not session_purpose and not pending[0]["review"]:
|
|
3417
|
-
request_filter, request_values = one_line(connection,
|
|
3464
|
+
request_filter, request_values = one_line(connection, member_id, request_filter, request_values)
|
|
3465
|
+
return request_filter, request_values
|
|
3466
|
+
|
|
3467
|
+
|
|
3468
|
+
def next_batch_request_ids(connection, members):
|
|
3469
|
+
"""Pending request ids that each non-external member's next execution will claim together.
|
|
3470
|
+
|
|
3471
|
+
External members claim chosen requests one by one, so their pending requests are never assumed to bundle.
|
|
3472
|
+
"""
|
|
3473
|
+
next_batch = set()
|
|
3474
|
+
for member in members:
|
|
3475
|
+
if member["status"] != "active" or member["access"] == "external" or not member["pending"]:
|
|
3476
|
+
continue
|
|
3477
|
+
batch = next_batch_filter(connection, member["id"])
|
|
3478
|
+
if not batch:
|
|
3479
|
+
continue
|
|
3480
|
+
request_filter, request_values = batch
|
|
3481
|
+
rows = connection.execute(f"SELECT id FROM member_requests WHERE member_id=? AND status='pending' AND {request_filter}",
|
|
3482
|
+
(member["id"], *request_values)).fetchall()
|
|
3483
|
+
next_batch.update(row["id"] for row in rows)
|
|
3484
|
+
return next_batch
|
|
3485
|
+
|
|
3486
|
+
|
|
3487
|
+
def open_execution(connection, room_id, member, payload, request_ids=None):
|
|
3488
|
+
"""Open one execution over a checked member's pending requests, or only over `request_ids` among them."""
|
|
3489
|
+
client_id = str(payload.get("client_id", ""))
|
|
3490
|
+
if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
|
|
3491
|
+
(member["id"],)).fetchone():
|
|
3492
|
+
raise FileExistsError(Text("该成员已有进行中的执行;同一会话不并发续接"))
|
|
3493
|
+
if quota_held_until(connection, member["id"]):
|
|
3494
|
+
raise FileExistsError(Text("该成员额度已用尽,暂停投递;等额度重置后重试它失败的执行,或改派其他成员"))
|
|
3495
|
+
if held_until(connection, member["id"]):
|
|
3496
|
+
raise FileExistsError(Text("该成员上一轮已作废但本机无法停止,可能仍在处理;等它结束或等待时限到后再投递"))
|
|
3497
|
+
batch = next_batch_filter(connection, member["id"], request_ids)
|
|
3498
|
+
if not batch:
|
|
3499
|
+
raise FileExistsError(Text("该成员没有待投递的请求"))
|
|
3500
|
+
request_filter, request_values = batch
|
|
3418
3501
|
if not connection.execute(f"SELECT 1 FROM member_requests WHERE member_id=? AND status='pending' AND {request_filter}",
|
|
3419
3502
|
(member["id"], *request_values)).fetchone():
|
|
3420
3503
|
raise FileExistsError(Text("该成员没有待投递的请求"))
|
|
@@ -3487,11 +3570,14 @@ def view_execution(connection, room_id, execution_id, token):
|
|
|
3487
3570
|
raise LookupError(Text("执行不存在"))
|
|
3488
3571
|
try:
|
|
3489
3572
|
require_owner(connection, room_id, token)
|
|
3573
|
+
owner = True
|
|
3490
3574
|
except PermissionError:
|
|
3575
|
+
owner = False
|
|
3491
3576
|
member = require_member(connection, room_id, token)
|
|
3492
3577
|
if member["id"] != row["member_id"] and member["role"] != "host":
|
|
3493
3578
|
raise
|
|
3494
|
-
return {**execution_detail(connection, row), "delivery": {"last_submission": execution_delivery(connection, room_id, row)}
|
|
3579
|
+
return {**execution_detail(connection, row), "delivery": {"last_submission": execution_delivery(connection, room_id, row)},
|
|
3580
|
+
"diagnostics": diagnostic_detail(connection, row, owner)}
|
|
3495
3581
|
|
|
3496
3582
|
|
|
3497
3583
|
def changed_files(payload):
|
|
@@ -3852,6 +3938,8 @@ def execution_action(connection, room_id, execution_id, token, payload, member=N
|
|
|
3852
3938
|
finish_execution(connection, execution_id, "cancelled", reason, "pending")
|
|
3853
3939
|
else:
|
|
3854
3940
|
raise ValueError(Text("action 须为 renew、fail、release、report、segments、interject、interjection、retry_wait、retry_start、retry_now、retry_stop 或 retry"))
|
|
3941
|
+
if action != "fail" or not member:
|
|
3942
|
+
record_diagnostics(connection, execution_id, payload, time.time_ns() // 1_000_000)
|
|
3855
3943
|
detail = execution_detail(connection, connection.execute("SELECT * FROM member_executions WHERE id=?", (execution_id,)).fetchone())
|
|
3856
3944
|
if action == "retry" and quota:
|
|
3857
3945
|
# Retrying a usage-limit failure is allowed (the owner may know the quota is back) but likely fails again before the reset.
|
|
@@ -3892,13 +3980,15 @@ def retry_failed(connection, room_id, execution):
|
|
|
3892
3980
|
if execution["status"] != "failed":
|
|
3893
3981
|
raise FileExistsError(Text("只有失败的执行可以重试"))
|
|
3894
3982
|
requests = connection.execute("""SELECT id,batch_id,chain_id FROM member_requests r WHERE execution_id=? AND status='failed'
|
|
3983
|
+
AND NOT EXISTS(SELECT 1 FROM message_withdrawals w WHERE w.message_id=r.message_id)
|
|
3895
3984
|
AND NOT EXISTS(SELECT 1 FROM session_requests s WHERE s.member_request_id=r.id)""", (execution["id"],)).fetchall()
|
|
3896
3985
|
if not requests:
|
|
3897
3986
|
raise FileExistsError(Text("这次执行没有可重试的请求:已重试过,或是讨论发言(由主持人重新安排)"))
|
|
3898
3987
|
if not connection.execute("SELECT 1 FROM room_members WHERE id=? AND status='active'", (execution["member_id"],)).fetchone():
|
|
3899
3988
|
raise FileExistsError(Text("该成员已离开或暂离,无法重试"))
|
|
3900
|
-
|
|
3901
|
-
|
|
3989
|
+
now = int(time.time())
|
|
3990
|
+
connection.executemany("INSERT OR IGNORE INTO retried_requests (execution_id,request_id,retried_at) VALUES (?,?,?)",
|
|
3991
|
+
[(execution["id"], request["id"], now) for request in requests])
|
|
3902
3992
|
connection.execute(f"UPDATE member_requests SET status='pending',execution_id=NULL WHERE id IN ({','.join('?' * len(requests))})",
|
|
3903
3993
|
[request["id"] for request in requests])
|
|
3904
3994
|
reopen_batches(connection, room_id, requests)
|
|
@@ -3923,6 +4013,9 @@ def revive_failed(connection, room_id, execution):
|
|
|
3923
4013
|
if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND id<>? AND status IN ('dispatched','started')",
|
|
3924
4014
|
(execution["member_id"], execution["id"])).fetchone():
|
|
3925
4015
|
return None
|
|
4016
|
+
if connection.execute("""SELECT 1 FROM member_requests r JOIN message_withdrawals w ON w.message_id=r.message_id
|
|
4017
|
+
WHERE r.execution_id=?""", (execution["id"],)).fetchone():
|
|
4018
|
+
return None
|
|
3926
4019
|
requests = connection.execute("""SELECT id,batch_id,chain_id FROM member_requests r WHERE execution_id=? AND status='failed'
|
|
3927
4020
|
AND NOT EXISTS(SELECT 1 FROM session_requests s WHERE s.member_request_id=r.id)""", (execution["id"],)).fetchall()
|
|
3928
4021
|
if not requests:
|
|
@@ -4112,8 +4205,8 @@ def rewind_room(connection, room_id, token, payload):
|
|
|
4112
4205
|
now = int(time.time())
|
|
4113
4206
|
for row in connection.execute("SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')", (room_id,)).fetchall():
|
|
4114
4207
|
finish_execution(connection, row["id"], "cancelled", Text("用户回退了对话"), "cancelled", "user_stop")
|
|
4115
|
-
record_cancel_reasons(connection, "room_id=? AND message_id>=? AND status
|
|
4116
|
-
connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND message_id>=? AND status
|
|
4208
|
+
record_cancel_reasons(connection, "room_id=? AND message_id>=? AND status IN ('pending','failed')", (room_id, message_id), "user_stop")
|
|
4209
|
+
connection.execute("UPDATE member_requests SET status='cancelled' WHERE room_id=? AND message_id>=? AND status IN ('pending','failed')", (room_id, message_id))
|
|
4117
4210
|
connection.execute("DELETE FROM free_queue WHERE room_id=? AND message_id>=?", (room_id, message_id))
|
|
4118
4211
|
# Batches of taken-back dispatches never hand back, and a dispatch the round limit held from them is never sent.
|
|
4119
4212
|
connection.execute("UPDATE free_batches SET settled=1 WHERE room_id=? AND batch_id>=?", (room_id, message_id))
|
package/backend/message_queue.py
CHANGED
|
@@ -337,15 +337,16 @@ def queue_action(connection, room_id, token, payload, post, check, interrupt):
|
|
|
337
337
|
action = payload.get("action")
|
|
338
338
|
if action not in QUEUE_ACTIONS:
|
|
339
339
|
raise ValueError(Text('action 须为 {value1} 之一', value1='、'.join(QUEUE_ACTIONS)))
|
|
340
|
+
sent_message_id = None
|
|
340
341
|
if action == "send":
|
|
341
342
|
row = queued_row(connection, room_id, payload.get("id"))
|
|
342
343
|
connection.execute("UPDATE queued_messages SET failure='' WHERE id=?", (row["id"],))
|
|
343
344
|
result = post_item(connection, room_id, row, post)
|
|
344
345
|
if not result:
|
|
345
346
|
raise ValueError(connection.execute("SELECT failure FROM queued_messages WHERE id=?", (row["id"],)).fetchone()[0])
|
|
346
|
-
|
|
347
|
-
if
|
|
348
|
-
interrupt(connection, room_id,
|
|
347
|
+
sent_message_id = result["message"]["id"] if result.get("message") else result.get("message_id")
|
|
348
|
+
if sent_message_id:
|
|
349
|
+
interrupt(connection, room_id, sent_message_id)
|
|
349
350
|
elif action == "edit":
|
|
350
351
|
edit_item(connection, queued_row(connection, room_id, payload.get("id")), payload.get("text"), check)
|
|
351
352
|
elif action == "delete":
|
|
@@ -355,4 +356,5 @@ def queue_action(connection, room_id, token, payload, post, check, interrupt):
|
|
|
355
356
|
else:
|
|
356
357
|
connection.execute("DELETE FROM queued_message_pauses WHERE room_id=?", (room_id,))
|
|
357
358
|
drain(connection, room_id, post)
|
|
358
|
-
|
|
359
|
+
view = queue_view(connection, room_id)
|
|
360
|
+
return {**view, "message_id": sent_message_id} if sent_message_id else view
|