ai_co_discuss 0.4.31 → 0.4.33
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/room.md +1 -0
- package/.agents/skills/discuss-participant/SKILL.md +6 -6
- package/.agents/skills/discuss-participant/references/writing.md +2 -2
- package/.agents/skills/discuss-session/SKILL.md +1 -1
- package/backend/entry_guard.py +111 -0
- package/backend/free_room.py +63 -4
- package/backend/schema.sql +6 -0
- package/backend/server.py +71 -8
- package/gateway/gateway.mjs +379 -26
- package/package.json +1 -1
- package/runner/account_env.mjs +2 -1
- package/runner/account_space.mjs +2 -0
- package/runner/adapters/antigravity_sidecar.mjs +3 -2
- package/runner/adapters/api.mjs +2 -1
- package/runner/adapters/api_images.mjs +2 -1
- package/runner/adapters/claude.mjs +9 -3
- package/runner/adapters/index.mjs +210 -209
- package/runner/admin_panel.mjs +267 -13
- package/runner/cli_login.mjs +9 -9
- package/runner/cli_login_agent.mjs +5 -3
- package/runner/discuss.py +112 -7
- package/runner/discussion_launch.mjs +3 -2
- package/runner/discussion_local.mjs +2 -1
- package/runner/discussion_runner.mjs +2 -1
- package/runner/discussion_service.mjs +9 -2
- package/runner/entry_client.mjs +159 -0
- package/runner/free_runner.mjs +104 -14
- package/runner/os_users.mjs +143 -14
- package/runner/relay_channel.mjs +4 -3
- package/runner/weixin.mjs +7 -6
- package/web/admin.css +1 -1
- package/web/admin.js +3 -3
- package/web/app.js +12 -6
- package/web/modern.css +1 -1
- package/web/modern.js +45 -45
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
- 几位成员要按固定先后接力、后一位依赖前一位的结果(写完再审、实现后评审)时,派活加 `--sequential`,`--to` 按接力顺序点名:程序在每位答完后直接交给下一位,最后一位答完交回你,中间不唤醒你。走完一圈算一轮(中间各棒不另计)。派活正文要把每一棒做什么、按什么标准交给下一棒写清楚,后面的成员靠它和前一棒的回答工作。
|
|
27
27
|
- 某一棒有几位互不依赖、可以同时做的成员(如几位评审各审一类问题)时,把他们写成同一棒:第一位用 `--to`,其余紧跟着用 `--with`(如 `--to 写手 --to 评审甲 --with 评审乙 --sequential --loop`)。这一棒的成员同时开工,全部结束才交下一棒,下一棒能读到他们每一份回答;组里有人失败,接力停下交回你,用户重试失败的那位后接着走。并行的成员看不到彼此的意见,派活正文要分清各自管什么。
|
|
28
28
|
- 派活时想让某位成员同时开工、但不必等它(如评审期间让记录员先整理别的材料),加 `--detach 成员`(可重复,不能与 `--to` 重名):它和这次派活一起开工,交回你或交下一棒都不等它;它做完不交回你,结果在房间里可读;失败时程序通知你。用在依次接力上时,它只随第一棒开工一次。撤回这次派活会一并撤回它。
|
|
29
|
+
- 派活后自己还要接着做、不等派出的成员(如让一位成员后台复核,自己继续改代码)时,派活加 `--keep-working`(API 不提供):这条回答收为派活卡,本轮不要结束,直接接着工作,房间会为后续工作另起一张卡;做完照常用本次凭据 `message post` 回答(可再派活)。派出的工作结束时以一条通知交回你,在你这次回答之后送达。不要先回答“我接着做”再结束本轮——那样后面的工作在房间里看不到。不能与 `--continue`、`--sequential`、`--next-review` 同用。
|
|
29
30
|
- 要“改完再审、审到通过为止”时再加 `--loop`:每走完一圈,交回你的 `handoff` 带 `sequence.phase: checkpoint`。本圈最后一位(最后一棒是同时做的一组时,其中任一位)明确要求返工时,用 `sequence continue ROOM --request 该交接请求编号 --as 本人` 开始下一圈(程序直接接着走,你本次即结束);认可、只剩可不采纳的建议、需要你或用户裁定时,不继续,直接验收或说明。开启智能调度时,它会先替你判断检查点,只有明确返工才自动开始下一圈,其余仍交给你;任务的 `scheduler_suggestions` 记着它的判断。`sequence view ROOM ID` 可读本圈各棒原文。每开始新的一圈算一轮,轮数用尽时循环停下,由用户决定是否继续。
|
|
30
31
|
- 要在接力中途停下来由你把关(验收一稿再交下一位),或只让中间一段循环(写 ⇄ 审到通过再交记录员)时,用检查点,均须与 `--sequential` 同用:`--checkpoint 成员` 在该成员那一棒结束后交回你(`sequence.phase: gate`);`--repeat 成员=起点成员` 在该成员那一棒结束后交回你,作为循环检查点(`sequence.phase: checkpoint`),再来一圈从起点成员那一棒开始,起点不能早于前一个检查点。交回时 `sequence.gate` 给出 `repeat_from`(再来一圈从第几棒开始)与 `can_proceed`(后面还有棒)。处理:要返工就 `sequence continue … --request 交接请求编号`(循环检查点再来一圈);认可并往下走就 `sequence continue … --proceed`(普通检查点不加 `--proceed` 也是往下走);要结束接力、裁定或说明时不继续,直接回答。往下走和再来一圈各算一轮。带检查点的接力不能在右栏调整顺序。
|
|
31
32
|
- 用户要作为接力中的一棒亲自参与(如跑团时用户扮演一位玩家、写作时用户当一位审稿人)时,用 `--wait-user 成员`(或 `成员=起点成员`,与 `--sequential` 同用):该成员那一棒结束后接力停下等用户,不交回你;用户下一条未点名任何人的消息直接接着往下一棒走(写了起点就从起点那一棒再来一圈),这条消息交给下一棒先读,并从它起算新任务链。用户点名某人的消息不影响等待;停止全部或撤回这次派活会结束等待。最后一棒之后等用户须写起点。在派活正文里告诉用户轮到他时要做什么。
|
|
@@ -28,7 +28,7 @@ description: "AI CoDiscuss 的通用参与技能,所有参与者(包括主
|
|
|
28
28
|
2. **执行失效后不再写入**:暂停、到期或被打断的旧任务保留草稿并结束,不换身份、职责或编号绕过拒绝,也不去掉 `--execution` 改作普通发言。只被本机服务判为失败(未被停止、未被重试)的执行,做完后照常带原 `--execution` 提交,网站会收下;仍被拒绝时按拒绝信息处理。任务文件的 `stopped_executions` 列出你此前被用户停止或跳过的执行:会话里如有它们未完成的工作,不接着做、不为它们补交,只处理本次请求。(失效的执行若还能产生可见结果,用户的打断与暂停就失去意义。)
|
|
29
29
|
3. **写入前定好 `--submission-id`**:同次重试沿用编号和原内容,新内容换新编号;`message post` 可省略,CLI 按房间、身份、关联与内容生成,用同一份草稿重试即得同一编号;结果不明时先按原编号查询,再按 [写入与恢复](references/writing.md) 处理。(网站靠它去重,换号会产生重复发言。)
|
|
30
30
|
4. **不创建定时任务、不操作其他软件、不发状态回执**(就绪、开始、完成、停止等说明),除非用户要求或出现需要记录的异常;回执不能作为观点、完成或共识的证据。(这些动作有副作用,回执只会淹没真正的回答。)
|
|
31
|
-
5.
|
|
31
|
+
5. **回复即交付**:一次请求只回答一次,回答后请求即结束。需要较长时间的工作做完再一次性回答,需要派活时在同一次回答里派;不在房间里回复进度,执行卡片会显示正在进行。(中途回复会提前结束请求,做完后就没有可绑定的请求来汇报。)主持人派活后自己还要接着做时例外,见 `discuss-host` 的 `--keep-working`。
|
|
32
32
|
|
|
33
33
|
## 命令入口与身份
|
|
34
34
|
|
|
@@ -36,7 +36,7 @@ description: "AI CoDiscuss 的通用参与技能,所有参与者(包括主
|
|
|
36
36
|
|
|
37
37
|
从实际任务或用户指定值核实站点、房间和身份,不从当前网页或最近聊天猜测。任务标明 `access_env: "DISCUSS_ACCESS_FILE"` 时凭据已由进程绑定,`--access-file FILE` 可省略;否则用任务交付的 `access_file`。任务凭据已绑定站点、房间、身份与本次执行,命令省略房间、`--as`、`--execution` 和 `--submission-id`,由 CLI 从凭据和内容补齐,例如 `message post --body-file 草稿.md`;下文命令里的 `ROOM`、`--as`、执行编号只在没有绑定凭据(如手动接入未带凭据)时需要填写。项目与 cwd 有值时用于本次获准资料;CLI 路径只定位工具,不把 CLI 仓库当作讨论项目或扩大文件权限。
|
|
38
38
|
|
|
39
|
-
每次 shell 调用都是一次模型往返,手动会话里还可能要用户逐条确认,所以互不依赖的只读命令放进同一条 shell
|
|
39
|
+
每次 shell 调用都是一次模型往返,手动会话里还可能要用户逐条确认,所以互不依赖的只读命令放进同一条 shell 命令依次执行。正文想好后,先用当前软件的文件写入工具把正文写成一个草稿文件(需要摘要时写在文件开头:`---`、`summary: 摘要`、`---` 三行,之后是正文),再用一条只含 `codiscuss` 的命令以 `--body-file` 提交;失败重试仍用这份草稿。不要用 heredoc、`echo` 重定向或命令行字面量传长文本,也不要在命令里调用函数生成编号(如 `[guid]::NewGuid()`、`$(uuidgen)`):自动运行时这类组合命令会被权限检查拒绝,文本中的引号(含中文弯引号)还会截断参数。其他写入命令需要编号时直接写一个新的 UUID 字面值。不同的网站写入各自单独执行并核对结果。
|
|
40
40
|
|
|
41
41
|
称呼和点名成员一律用显示名:`room view` 中 `members[].label`(如 `Gemini`)就是它在房间里的名字,正文 `@`、`--to`、`--next-review`、`--expert` 都写它。`name` 是成员 ID,与 `descriptions` 同属成员的完整信息,需要核对时再看,不写进正文;旧消息、`author` 等字段里出现的 ID 指的是同一位成员。普通成员 `@` 其他成员只是引用,不会唤醒对方;只有确实需要主持人处理(超出你的权限或职责)时才 `@` 主持人,程序会在房间空闲后唤醒它。
|
|
42
42
|
|
|
@@ -62,8 +62,8 @@ description: "AI CoDiscuss 的通用参与技能,所有参与者(包括主
|
|
|
62
62
|
|
|
63
63
|
## 保存与核验
|
|
64
64
|
|
|
65
|
-
正文用 UTF-8 `--body-file
|
|
65
|
+
正文用 UTF-8 `--body-file`,摘要写在同一草稿的文件头(见上文“命令入口与身份”),也可另用 `--summary` / `--summary-file`。需要附件时先 `attachment upload ROOM --file FILE --submission-id 上传编号`,再用 `message post --attachment ID` 关联(最多 10 个,单个 20 MiB,须在执行资格结束前上传)。
|
|
66
66
|
|
|
67
|
-
**生图**:任务里有 `image` 字段才能画图或改图;没有时如实说明本房间未开生图,不要找别的办法。按张计费,想清楚再调用,不为试探反复生成。把请求写进 UTF-8 JSON 草稿:`{"action":"generate","prompt":"画面、风格、文字","size":"1536x1024","n":1}`;改图用 `"action":"edit"` 与 `"images":[{"attachment_id":"…"}]` 或 `{"file_path":"项目内路径"}`;其他参数见 `codiscuss launch --help` 的 image 一条。运行 `image.command`(把 `REQUEST.json` 换成草稿路径),返回的附件 ID 用 `message post --attachment` 附上。能看图时先 `attachment download` 核对效果再交付;看不到图(如 API 成员)就写清画了什么和参数,不描述没看到的细节。API 成员用 `generate_image` / `edit_image` 工具,不走命令。
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
**生图**:任务里有 `image` 字段才能画图或改图;没有时如实说明本房间未开生图,不要找别的办法。按张计费,想清楚再调用,不为试探反复生成。把请求写进 UTF-8 JSON 草稿:`{"action":"generate","prompt":"画面、风格、文字","size":"1536x1024","n":1}`;改图用 `"action":"edit"` 与 `"images":[{"attachment_id":"…"}]` 或 `{"file_path":"项目内路径"}`;其他参数见 `codiscuss launch --help` 的 image 一条。运行 `image.command`(把 `REQUEST.json` 换成草稿路径),返回的附件 ID 用 `message post --attachment` 附上。能看图时先 `attachment download` 核对效果再交付;看不到图(如 API 成员)就写清画了什么和参数,不描述没看到的细节。API 成员用 `generate_image` / `edit_image` 工具,不走命令。
|
|
68
|
+
|
|
69
|
+
成功须核对服务端返回的回执:消息编号、作者和执行或请求关联(`message post` 不回显正文,只给 `text_chars` 字数);回执已足够时不再读一遍,缺少所需证据才按编号补读。答案落库后即可结束,不用旧资格继续写入。只以本人身份提交,不替他人发言。执行结束不等于整个房间的工作结束。
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
每次业务写入都带对应的 `--access-file`:手动成员使用本人的持久凭据,自动讨论使用本次执行文件。房主文件仅用于用户身份和房主管理。CLI 建房须显式指定私有房主文件,先保存建房编号;回执中的 `member_access_files` 给出各本地成员文件路径。讨论名单或主持职责变更仅房主可做,新增或改变能力的成员须提供独立的新凭据;保持未变成员原凭据,不能由成员自行扩权。
|
|
12
12
|
|
|
13
|
-
本地提交用 `
|
|
13
|
+
本地提交用 `--body` / `--body-file` 保存完整正文,摘要可写在正文文件开头(第一行 `---`,第二行 `summary: 摘要`,第三行 `---`,之后是正文;CLI 去掉这三行),也可用 `--summary` / `--summary-file`,二者不能同用;摘要上限 1000 个 Unicode 字符。摘要归提交者本人。摘要与正文一起使用同一提交编号;缺少摘要的旧记录不自动生成摘要。
|
|
14
14
|
|
|
15
15
|
一次写入先确定目标、身份、正文与关联关系,再选择对应命令:
|
|
16
16
|
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
|
|
30
30
|
长正文优先 UTF-8 文件,`--body-file -` 可读 stdin。当前消息正文上限为 32000 个 Unicode 字符,详细讨论状态上限为 4000 字;以目标站点协议为准。完整回答一次提交并完成安排,不能截断或用第一段冒充完整回答。超过上限时保留完整原文并说明限制,先明确完整材料的留档方式。
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
`message post` 成功只返回回执:消息编号、作者、职责、执行或请求关联、提交编号、摘要、正文字数(`text_chars`)与附件数,不回显正文;核对这些即可,需要看正文再 `message view`。其他写入成功后核对服务端返回的持久记录;响应已给出证据时不重复全文查询,缺少的再按编号补读。`duplicate=true` 表示服务确认已有同一提交,不是新回答。讨论暂停或收束后不再提交新回答/安排,保留原文。自动执行失效后不能借此继续写入;不能改消息职责绕过阶段限制。
|
|
33
33
|
|
|
34
34
|
保存摘要后核对服务端返回的正文和截止编号,响应不足时用 `state view` 补读。`--until` 表示实际已读材料范围,不能证明下一安排、外部通知或清理已完成;这些事项在摘要正文中保留各自真实状态。保存结果不明时先比较现存摘要与待保存内容,不直接用旧草稿覆盖更新后的进度。
|
|
35
35
|
|
|
@@ -43,6 +43,6 @@ codiscuss message post ROOM --as 本人 --kind chat --execution 执行编号 --b
|
|
|
43
43
|
codiscuss message post ROOM --as 本人 --kind chat --request 请求编号 --body-file draft.md --access-file FILE
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
|
|
46
|
+
需要摘要时写在正文草稿开头(`---`、`summary: 摘要`、`---` 三行),或用 `--summary` / `--summary-file`。成功提交后当前请求即完成;不要再补一条普通 chat 或状态回执。
|
|
47
47
|
|
|
48
48
|
任务执行失败时,用 `execution fail ROOM 执行编号 --reason 原因 --access-file FILE` 失败本次执行并保留草稿。该操作只处理当前请求,不自动暂停整场讨论;主持人会收到专家请求失败并判断后续安排。不要改用其他成员、请求编号或身份绕过拒绝。
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Entry protection for a hosted instance: only callers holding the instance's key reach it.
|
|
2
|
+
|
|
3
|
+
A hosted instance listens on loopback, where every account's processes can connect and any of them may take the port
|
|
4
|
+
of an instance that is down. So, when protection is on, nothing but public assets is served unless the caller proves
|
|
5
|
+
on the same connection that it holds the instance's key, and the caller only sends its request after the instance has
|
|
6
|
+
proved the same to it:
|
|
7
|
+
|
|
8
|
+
1. The caller sends ``GET /_instance/hello`` with ``X-CoDiscuss-Nonce: n1``.
|
|
9
|
+
2. The instance answers 204 with ``X-CoDiscuss-Proof: HMAC(K, "instance|" + n1)`` and its own ``X-CoDiscuss-Nonce: n2``,
|
|
10
|
+
keeping the connection open.
|
|
11
|
+
3. The caller checks the proof, then sends one request on the same connection with
|
|
12
|
+
``X-CoDiscuss-Entry: HMAC(K, "entry|" + n2)``. The instance accepts it only on that connection and only for the key it
|
|
13
|
+
used in step 2, and closes the connection after answering (a stream keeps it until the stream ends).
|
|
14
|
+
|
|
15
|
+
The key never travels. Protection is on when the environment names a key file (``DISCUSS_ENTRY_KEY_FILE``); a key file
|
|
16
|
+
that is then missing or unreadable refuses every protected request instead of falling back to no protection.
|
|
17
|
+
"""
|
|
18
|
+
import hashlib
|
|
19
|
+
import hmac
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import secrets
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
KEY_FILE_VARIABLE = "DISCUSS_ENTRY_KEY_FILE"
|
|
27
|
+
HELLO_PATH = "/_instance/hello"
|
|
28
|
+
NONCE_HEADER = "X-CoDiscuss-Nonce"
|
|
29
|
+
PROOF_HEADER = "X-CoDiscuss-Proof"
|
|
30
|
+
ENTRY_HEADER = "X-CoDiscuss-Entry"
|
|
31
|
+
NONCE_PATTERN = re.compile(r"^[0-9a-f]{32}$")
|
|
32
|
+
KEY_PATTERN = re.compile(r"^[0-9a-f]{64}$")
|
|
33
|
+
# How long a connection that said hello may wait before its one request arrives.
|
|
34
|
+
HANDSHAKE_SECONDS = 10
|
|
35
|
+
# Paths any caller may read: the health check and the page's static files carry no data.
|
|
36
|
+
PUBLIC_PATHS = ("/api/health", "/robots.txt")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def proof(key, purpose, nonce):
|
|
40
|
+
"""HMAC-SHA256 of ``purpose|nonce`` under the hexadecimal key, as hexadecimal."""
|
|
41
|
+
return hmac.new(bytes.fromhex(key), f"{purpose}|{nonce}".encode("ascii"), hashlib.sha256).hexdigest()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class EntryPolicy:
|
|
45
|
+
"""Whether protection is on, and the instance's current key, read from its file every time it is needed.
|
|
46
|
+
|
|
47
|
+
The file is a few bytes, so it is not cached: a cache keyed on the modification time would keep honouring an old or
|
|
48
|
+
broken key after a change that left the time as it was.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, key_file=None):
|
|
52
|
+
configured = key_file if key_file is not None else os.getenv(KEY_FILE_VARIABLE)
|
|
53
|
+
self.path = Path(configured) if configured else None
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def enabled(self):
|
|
57
|
+
"""Protection is on once a key file is named, whether or not it can be read."""
|
|
58
|
+
return self.path is not None
|
|
59
|
+
|
|
60
|
+
def key(self):
|
|
61
|
+
"""The current key, or None when the named file is missing or malformed (everything protected is refused)."""
|
|
62
|
+
if not self.path:
|
|
63
|
+
return None
|
|
64
|
+
try:
|
|
65
|
+
value = json.loads(self.path.read_text(encoding="utf-8")).get("key")
|
|
66
|
+
except (OSError, ValueError, AttributeError):
|
|
67
|
+
return None
|
|
68
|
+
return value if isinstance(value, str) and KEY_PATTERN.match(value) else None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def answer_hello(handler, policy):
|
|
72
|
+
"""Prove this instance to a caller and open the connection's single authenticated request.
|
|
73
|
+
|
|
74
|
+
Returns True when the hello was answered; a malformed hello or a missing key closes the connection unanswered.
|
|
75
|
+
"""
|
|
76
|
+
nonce = handler.headers.get(NONCE_HEADER, "")
|
|
77
|
+
key = policy.key()
|
|
78
|
+
handler.close_connection = True
|
|
79
|
+
# One hello per connection: a second one ends it instead of keeping the connection open indefinitely.
|
|
80
|
+
if not key or not NONCE_PATTERN.match(nonce) or getattr(handler, "entry_challenge", None) is not None:
|
|
81
|
+
return False
|
|
82
|
+
challenge = secrets.token_hex(16)
|
|
83
|
+
handler.entry_challenge = (challenge, key)
|
|
84
|
+
# Only this answer keeps the connection: HTTP/1.1 with a zero-length body, and a deadline for the request to follow.
|
|
85
|
+
handler.protocol_version = "HTTP/1.1"
|
|
86
|
+
handler.close_connection = False
|
|
87
|
+
handler.connection.settimeout(HANDSHAKE_SECONDS)
|
|
88
|
+
handler.send_response(204)
|
|
89
|
+
handler.send_header(PROOF_HEADER, proof(key, "instance", nonce))
|
|
90
|
+
handler.send_header(NONCE_HEADER, challenge)
|
|
91
|
+
handler.send_header("Content-Length", "0")
|
|
92
|
+
handler.send_header("Cache-Control", "no-store")
|
|
93
|
+
handler.end_headers()
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def request_proven(handler, policy):
|
|
98
|
+
"""The key this request proved, or None.
|
|
99
|
+
|
|
100
|
+
The proof must answer the challenge issued on this request's own connection, under the key that challenge was issued
|
|
101
|
+
with, and that key must still be current. The challenge is used up either way, and the connection closes after this
|
|
102
|
+
request. A stream opened by the request is bound to the returned key, not to whatever is current when it starts.
|
|
103
|
+
"""
|
|
104
|
+
challenge = getattr(handler, "entry_challenge", None)
|
|
105
|
+
handler.entry_challenge = None
|
|
106
|
+
if challenge is None:
|
|
107
|
+
return None
|
|
108
|
+
handler.close_connection = True
|
|
109
|
+
nonce, key = challenge
|
|
110
|
+
given = handler.headers.get(ENTRY_HEADER, "")
|
|
111
|
+
return key if key == policy.key() and hmac.compare_digest(given, proof(key, "entry", nonce)) else None
|
package/backend/free_room.py
CHANGED
|
@@ -763,6 +763,12 @@ def host_event(event):
|
|
|
763
763
|
return {**event, "data": data}
|
|
764
764
|
|
|
765
765
|
|
|
766
|
+
# An execution (aliased `e`) on work the host handed out without waiting for it: a member it detached, or one it named
|
|
767
|
+
# in a dispatch after which it went on working (`keep_working`, its own request on the same message).
|
|
768
|
+
BACKGROUND_SQL = """EXISTS(SELECT 1 FROM member_requests r WHERE r.execution_id=e.id AND r.purpose='ask' AND r.created_by='host'
|
|
769
|
+
AND (r.batch_id=0 OR EXISTS(SELECT 1 FROM member_requests k WHERE k.message_id=r.message_id AND k.purpose='keep_working')))"""
|
|
770
|
+
|
|
771
|
+
|
|
766
772
|
def recent_executions(connection, room_id):
|
|
767
773
|
"""Return bounded public reports, including requests no longer in the recent request list."""
|
|
768
774
|
rows = connection.execute(f"""SELECT e.*,m.name AS member,
|
|
@@ -773,7 +779,8 @@ def recent_executions(connection, room_id):
|
|
|
773
779
|
(SELECT MIN({DISPATCHED_AFTER_SQL}) FROM member_requests r WHERE r.execution_id=e.id) AS dispatched_after,
|
|
774
780
|
(SELECT COUNT(*) FROM execution_notes WHERE execution_id=e.id) AS note_count,
|
|
775
781
|
(SELECT denials FROM execution_denials WHERE execution_id=e.id) AS denials,{CAPABILITY_COLUMNS},
|
|
776
|
-
(SELECT json_object('created_at',created_at) FROM late_answers WHERE execution_id=e.id) AS late_answer
|
|
782
|
+
(SELECT json_object('created_at',created_at) FROM late_answers WHERE execution_id=e.id) AS late_answer,
|
|
783
|
+
{BACKGROUND_SQL} AS background
|
|
777
784
|
FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.room_id=? ORDER BY e.id DESC LIMIT ?""", (room_id, RECENT_EXECUTIONS))
|
|
778
785
|
executions = []
|
|
779
786
|
for row in rows:
|
|
@@ -786,7 +793,7 @@ def recent_executions(connection, room_id):
|
|
|
786
793
|
"anchor_message_id": row["anchor_message_id"], "dispatched_after": row["dispatched_after"], "requests": requests,
|
|
787
794
|
"notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"),
|
|
788
795
|
"capabilities": reported_capabilities(row), "stop_result": row["stop_result"] or "",
|
|
789
|
-
"late_answer": json.loads(row["late_answer"]) if row["late_answer"] else None,
|
|
796
|
+
"late_answer": json.loads(row["late_answer"]) if row["late_answer"] else None, "background": bool(row["background"]),
|
|
790
797
|
"interjections": execution_interjections(connection, row["id"], row["status"]),
|
|
791
798
|
"retry": execution_retry(connection, row["id"])})
|
|
792
799
|
return executions
|
|
@@ -1023,7 +1030,7 @@ def recipients(connection, room_id, payload):
|
|
|
1023
1030
|
|
|
1024
1031
|
|
|
1025
1032
|
# What a proactive post may not carry: it answers no request. Only the host's may also dispatch, as an answer does.
|
|
1026
|
-
PROACTIVE_EXCLUDED = ("execution_id", "request_ids", "next_review", "turn_id")
|
|
1033
|
+
PROACTIVE_EXCLUDED = ("execution_id", "request_ids", "next_review", "turn_id", "keep_working")
|
|
1027
1034
|
HOST_ONLY_PROACTIVE = ("to", "handoff", "no_handoff", "continue", "sequential", "loop", "parallel", "gates", "detach", "need_rounds", "rounds_reason")
|
|
1028
1035
|
|
|
1029
1036
|
|
|
@@ -1119,6 +1126,7 @@ def check_answer(connection, room_id, member, payload):
|
|
|
1119
1126
|
if payload.get("handoff") not in (None, False) and (payload["handoff"] is not True or member["role"] != "host" or not payload.get("to")):
|
|
1120
1127
|
raise ValueError("handoff 只能由主持人与 to 一起使用,值为 true")
|
|
1121
1128
|
check_no_handoff(member, payload)
|
|
1129
|
+
check_keep_working(member, payload)
|
|
1122
1130
|
check_need_rounds(member, payload)
|
|
1123
1131
|
reason = payload.get("continue")
|
|
1124
1132
|
if reason is not None and (member["role"] != "host" or not isinstance(reason, str) or not reason.strip()
|
|
@@ -1150,6 +1158,10 @@ def check_answer(connection, room_id, member, payload):
|
|
|
1150
1158
|
row = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND id=?", (room_id, execution_id)).fetchone()
|
|
1151
1159
|
if not row or row["member_id"] != member["id"]:
|
|
1152
1160
|
raise PermissionError("执行编号不属于本成员")
|
|
1161
|
+
if row["status"] == "completed":
|
|
1162
|
+
# The host dispatched with keep_working and went on in the same turn: its answer belongs to where that turn went.
|
|
1163
|
+
row = live_continuation(connection, row) or row
|
|
1164
|
+
payload["execution_id"] = row["id"]
|
|
1153
1165
|
revived = revive_failed(connection, room_id, row) if row["status"] == "failed" else None
|
|
1154
1166
|
if revived:
|
|
1155
1167
|
row = revived
|
|
@@ -1173,6 +1185,42 @@ def check_dispatch(member, payload, purposes):
|
|
|
1173
1185
|
"""A host answering only its share of an everyone request answers as a member, so it may not dispatch others."""
|
|
1174
1186
|
if member["role"] == "host" and payload.get("to") and purposes and all(purpose == "all" for purpose in purposes):
|
|
1175
1187
|
raise ValueError("这次是请全体成员各自回应,其他成员已收到请求;主持人只回答自己的部分,不能用 --to 派活")
|
|
1188
|
+
if payload.get("keep_working") and any(purpose in ("discuss", "discuss_host") for purpose in purposes):
|
|
1189
|
+
raise ValueError("讨论中的发言不能用 keep_working")
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def check_keep_working(member, payload):
|
|
1193
|
+
"""`keep_working`: the runner-delivered host dispatches and goes on in the same turn instead of ending it."""
|
|
1194
|
+
if payload.get("keep_working") in (None, False):
|
|
1195
|
+
return
|
|
1196
|
+
# A relay checkpoint or a review hands back on the dispatch message itself, where the host's own request now hangs.
|
|
1197
|
+
if (payload["keep_working"] is not True or member["role"] != "host" or member["access"] != "runner" or not payload.get("to")
|
|
1198
|
+
or any(payload.get(field) not in (None, False) for field in ("continue", "sequential", "next_review"))):
|
|
1199
|
+
raise ValueError("keep_working 只能由本机接入的主持人在派活(to)时使用,值为 true,不能与 continue、sequential 或 next_review 同用")
|
|
1200
|
+
|
|
1201
|
+
|
|
1202
|
+
def live_continuation(connection, row):
|
|
1203
|
+
"""The live execution that a host's `keep_working` moved this answered execution's turn onto, or None."""
|
|
1204
|
+
while row and row["status"] == "completed":
|
|
1205
|
+
link = connection.execute("SELECT next_id FROM execution_continuations WHERE execution_id=?", (row["id"],)).fetchone()
|
|
1206
|
+
row = link and connection.execute("SELECT * FROM member_executions WHERE id=?", (link[0],)).fetchone()
|
|
1207
|
+
return row if row and row["status"] in ACTIVE else None
|
|
1208
|
+
|
|
1209
|
+
|
|
1210
|
+
def keep_working(connection, room_id, host, message_id, chain_id, execution_id):
|
|
1211
|
+
"""The host dispatched with `keep_working`: its answered execution ends with this message, and a new one, on a request
|
|
1212
|
+
hanging on it, carries the same software turn on, so that work shows as its own card under the dispatch."""
|
|
1213
|
+
now = int(time.time())
|
|
1214
|
+
previous = connection.execute("SELECT * FROM member_executions WHERE id=?", (execution_id,)).fetchone()
|
|
1215
|
+
next_id = connection.execute("""INSERT INTO member_executions (room_id,member_id,client_id,session_id,lease_until,created_at,cwd)
|
|
1216
|
+
VALUES (?,?,?,?,?,?,?)""", (room_id, host["id"], f"keep-working-{execution_id}", previous["session_id"],
|
|
1217
|
+
now + LEASE_SECONDS, now, previous["cwd"])).lastrowid
|
|
1218
|
+
connection.execute("""INSERT INTO execution_capabilities (execution_id,room_id,stoppable,progress,steer,resume)
|
|
1219
|
+
SELECT ?,room_id,stoppable,progress,steer,resume FROM execution_capabilities WHERE execution_id=?""", (next_id, execution_id))
|
|
1220
|
+
insert_request(connection, room_id, host["id"], message_id, chain_id, "keep_working", "host")
|
|
1221
|
+
connection.execute("UPDATE member_requests SET status='delivering',execution_id=? WHERE message_id=? AND member_id=?",
|
|
1222
|
+
(next_id, message_id, host["id"]))
|
|
1223
|
+
connection.execute("INSERT INTO execution_continuations (execution_id,next_id) VALUES (?,?)", (execution_id, next_id))
|
|
1176
1224
|
|
|
1177
1225
|
|
|
1178
1226
|
def insert_request(connection, room_id, member_id, message_id, chain_id, purpose, created_by, batch_id=0):
|
|
@@ -1530,8 +1578,14 @@ def settle_batches(connection, room_id):
|
|
|
1530
1578
|
continue
|
|
1531
1579
|
# Every other answer and every failure comes back to the host, so it can carry on, retry, reassign or tell the user.
|
|
1532
1580
|
# The hand-back closes the round it belongs to, so it is never held back: the last round still gets its summary.
|
|
1533
|
-
|
|
1581
|
+
own = connection.execute("SELECT purpose FROM member_requests WHERE message_id=? AND member_id=?", (batch["batch_id"], host["id"])).fetchone()
|
|
1582
|
+
if not own:
|
|
1534
1583
|
insert_request(connection, room_id, host["id"], batch["batch_id"], batch["chain_id"], "handoff", "host")
|
|
1584
|
+
elif own["purpose"] == "keep_working":
|
|
1585
|
+
# The host went on working after this dispatch, on a request of its own on the same message: the hand-back
|
|
1586
|
+
# reaches it as a notice, delivered once that work ends.
|
|
1587
|
+
wake_host(connection, room_id, batch["chain_id"], f"#{batch['batch_id']} 派出的工作已结束,请主持人接着处理。",
|
|
1588
|
+
f"handoff:{batch['batch_id']}")
|
|
1535
1589
|
else:
|
|
1536
1590
|
# The batch already came back once (it had failed) and the owner retried it: its new answers reach the host as a notice.
|
|
1537
1591
|
retried = connection.execute("SELECT MAX(id) FROM member_requests WHERE room_id=? AND batch_id=?", (room_id, batch["batch_id"])).fetchone()[0]
|
|
@@ -2079,6 +2133,8 @@ def after_free_message(connection, room_id, message_id, actor, payload):
|
|
|
2079
2133
|
elif actor["role"] == "host" and payload.get("to"):
|
|
2080
2134
|
dispatch(connection, room_id, actor, message_id, payload["to"], chain_id, payload.get("handoff") is True or bool(payload.get("next_review")),
|
|
2081
2135
|
payload.get("no_handoff") is True, {"need": need_plan(payload)}, payload.get("detach"))
|
|
2136
|
+
if payload.get("keep_working") is True:
|
|
2137
|
+
keep_working(connection, room_id, actor, message_id, chain_id, payload["execution_id"])
|
|
2082
2138
|
if actor["role"] == "host":
|
|
2083
2139
|
remember_continue(connection, room_id, actor, message_id, chain_id, payload)
|
|
2084
2140
|
settle_batches(connection, room_id)
|
|
@@ -2309,7 +2365,10 @@ def inbox(connection, room_id, token):
|
|
|
2309
2365
|
pending = [{**request, **review_request_context(connection, request), **sequence_request_context(connection, request)} for request in pending]
|
|
2310
2366
|
(members if row["access"] == "runner" else observers).append({**member_view, "pending": pending})
|
|
2311
2367
|
# Pending interjections ride along so the runner hands them to the running software at its next check.
|
|
2368
|
+
# `continues`: the answered execution whose software turn this one carries on (keep_working); the runner moves it over.
|
|
2312
2369
|
executions = [{**public_execution(row), "member": row["name"], "retry": execution_retry(connection, row["id"]),
|
|
2370
|
+
"continues": (connection.execute("SELECT execution_id FROM execution_continuations WHERE next_id=?",
|
|
2371
|
+
(row["id"],)).fetchone() or [None])[0],
|
|
2313
2372
|
"interjections": [dict(item) for item in connection.execute(
|
|
2314
2373
|
"SELECT id,text FROM execution_interjections WHERE execution_id=? AND status='pending' ORDER BY id", (row["id"],))]}
|
|
2315
2374
|
for row in connection.execute(
|
package/backend/schema.sql
CHANGED
|
@@ -723,6 +723,12 @@ CREATE TABLE IF NOT EXISTS free_direct_batches (
|
|
|
723
723
|
batch_id INTEGER NOT NULL,
|
|
724
724
|
PRIMARY KEY (room_id,batch_id)
|
|
725
725
|
);
|
|
726
|
+
-- A host that dispatched with `keep_working` goes on working in the same software turn: its answered execution is
|
|
727
|
+
-- followed by `next_id`, a new one the runner moves that turn onto; a later answer to the first goes to the live one.
|
|
728
|
+
CREATE TABLE IF NOT EXISTS execution_continuations (
|
|
729
|
+
execution_id INTEGER PRIMARY KEY REFERENCES member_executions(id) ON DELETE CASCADE,
|
|
730
|
+
next_id INTEGER NOT NULL REFERENCES member_executions(id) ON DELETE CASCADE
|
|
731
|
+
);
|
|
726
732
|
-- What the program handed to the host once (a failure, a possible conflict, its own continue): `key` keeps it to one
|
|
727
733
|
-- wake-up per event, `chain_id` counts it as a round of that chain, `message_id` is the notice its request hangs on.
|
|
728
734
|
CREATE TABLE IF NOT EXISTS free_host_wakes (
|
package/backend/server.py
CHANGED
|
@@ -23,6 +23,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
23
23
|
from pathlib import Path
|
|
24
24
|
from urllib.parse import parse_qs, quote, urlsplit
|
|
25
25
|
|
|
26
|
+
from .entry_guard import HELLO_PATH, PUBLIC_PATHS, EntryPolicy, answer_hello, request_proven
|
|
26
27
|
from .admin import (AdminError, admin_status, change_password, list_sessions, login_admin, logout_admin, register_admin,
|
|
27
28
|
revoke_sessions, session_valid, update_profile)
|
|
28
29
|
from .remote_launch import (COMMAND_WAIT_MAX, claim_machine_commands, finish_machine_command, list_machines, machine_command_status,
|
|
@@ -1235,10 +1236,20 @@ def check_message_references(connection, room_id, message):
|
|
|
1235
1236
|
raise ValueError("回复的消息不在当前房间中")
|
|
1236
1237
|
|
|
1237
1238
|
|
|
1239
|
+
CAPTURE_REFUSED_FIELDS = ("to", "handoff", "continue", "sequential", "loop", "parallel", "gates", "detach", "need_rounds",
|
|
1240
|
+
"next_review", "review_scope", "proactive", "request_ids", "reply_to", "attachment_ids", "keep_working")
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
def check_captured_reply(payload):
|
|
1244
|
+
"""A reply the local service captured after the software ended unsubmitted: it answers its execution and nothing more."""
|
|
1245
|
+
if type(payload.get("execution_id")) is not int or any(payload.get(field) for field in CAPTURE_REFUSED_FIELDS):
|
|
1246
|
+
raise ValueError("自动收录的回答只能关联本次执行 execution_id,不能派活、续跑、引用或带附件")
|
|
1247
|
+
|
|
1248
|
+
|
|
1238
1249
|
def append_free_message(connection, room, payload, actor):
|
|
1239
1250
|
"""Append a free-room message: the owner's creates requests, a member's completes its execution."""
|
|
1240
1251
|
if payload.get("kind") == "moderation":
|
|
1241
|
-
if any(payload.get(field) for field in ("next_review", "review_scope", "review_roster", "sequential", "loop", "parallel", "gates", "detach", "need_rounds")):
|
|
1252
|
+
if any(payload.get(field) for field in ("next_review", "review_scope", "review_roster", "sequential", "loop", "parallel", "gates", "detach", "need_rounds", "keep_working")):
|
|
1242
1253
|
raise ValueError("主持说明不能声明评审授权、依次接力或申请轮数;请在派活时提交")
|
|
1243
1254
|
return append_free_moderation(connection, room, payload, actor)
|
|
1244
1255
|
if payload.get("kind") not in (None, "chat"):
|
|
@@ -1251,8 +1262,11 @@ def append_free_message(connection, room, payload, actor):
|
|
|
1251
1262
|
if actor == "用户" and (author != "用户" or payload.get("submitted_by", "用户") != "用户"):
|
|
1252
1263
|
raise PermissionError("房间控制凭据只能以用户身份发言")
|
|
1253
1264
|
submitted_by = author
|
|
1265
|
+
source = payload.get("source") if payload.get("source") in ("api", "auto") else "cli"
|
|
1254
1266
|
expected = {"author": author, "text": text, "reply_to": reply_to, "kind": "chat", "submitted_by": submitted_by,
|
|
1255
|
-
"source": "user" if author == "用户" else
|
|
1267
|
+
"source": "user" if author == "用户" else source}
|
|
1268
|
+
if expected["source"] == "auto":
|
|
1269
|
+
check_captured_reply(payload)
|
|
1256
1270
|
expected.update(message_summary(payload, expected))
|
|
1257
1271
|
identifiers = attachment_ids(payload)
|
|
1258
1272
|
previous = connection.execute(f"{MESSAGE_QUERY} WHERE room_id=? AND submission_id=?", (room_id, submission_id)).fetchone()
|
|
@@ -1283,7 +1297,9 @@ def append_free_message(connection, room, payload, actor):
|
|
|
1283
1297
|
(cursor.lastrowid, expected["summary"], expected["summary_by"]))
|
|
1284
1298
|
for position, identifier in enumerate(identifiers):
|
|
1285
1299
|
connection.execute("UPDATE attachments SET message_id=?,position=? WHERE id=?", (cursor.lastrowid, position, identifier))
|
|
1286
|
-
|
|
1300
|
+
# A captured reply keeps its text, but its mentions wake nobody: only a submitted answer may ask for a host.
|
|
1301
|
+
if expected["source"] != "auto":
|
|
1302
|
+
save_suggestions(connection, room_id, cursor.lastrowid, actor, payload)
|
|
1287
1303
|
save_review_plan(connection, room_id, cursor.lastrowid, review_plan)
|
|
1288
1304
|
if actor != "用户" and payload.get("proactive") is True:
|
|
1289
1305
|
# Spoken on its own: it completes no request; only the host's may dispatch.
|
|
@@ -1679,7 +1695,7 @@ def protocol_text(room):
|
|
|
1679
1695
|
"用户管理和讨论开关使用房主凭据;本地成员使用本人的 --access-file,不借用其他身份。凭据私下交付,不公开 token。API 参与者遵循相同请求与执行约束,source=api;本地 CLI 使用 source=cli。",
|
|
1680
1696
|
"runner 成员等待本机接入程序交付任务,用 execution view 核对本次执行和请求,再以 message post --as 本人 --kind chat --execution 本次编号 --access-file FILE 回答。执行失效后保留草稿,不能去掉编号改作普通发言;认领、续租与后续投递由接入程序处理。",
|
|
1681
1697
|
"manual 本地成员首次用 member register 注册,会话 ID 由 CLI 自动取得;回答用 --request 请求编号,不编造执行编号。讨论不使用原生定时;原会话不能托管时由用户触发。",
|
|
1682
|
-
"房间里的 host 可用 --to 点名成员,route 表示未点名的用户请求,handoff 表示派出任务已结束;链上 AI 派活受房间预算限制。--to 多位并加 --sequential 时按点名顺序依次接力,每棒一轮,最后交回主持人;--with 成员 与紧挨在前的 --to 同一棒同时做,这一组全部结束才交下一棒;--detach 成员
|
|
1698
|
+
"房间里的 host 可用 --to 点名成员,route 表示未点名的用户请求,handoff 表示派出任务已结束;链上 AI 派活受房间预算限制。--to 多位并加 --sequential 时按点名顺序依次接力,每棒一轮,最后交回主持人;--with 成员 与紧挨在前的 --to 同一棒同时做,这一组全部结束才交下一棒;--detach 成员 与这次派活同时开工但不等它(失败时通知主持人);--keep-working 派活后自己不结束这一轮、接着工作:这条回答收为派活卡,后续工作另起一张卡,做完照常回答(同一执行凭据即可),派出的工作结束时以通知交回;不能与 --continue、--sequential、--next-review 同用;再加 --loop 则交回为检查点,用 sequence continue --request 交接请求编号 开始下一圈,不继续即直接验收。普通成员的 --to 或正文 @ 只保存回应建议,不直接唤醒;不点名自己、不扩大授权。",
|
|
1683
1699
|
"讨论中的用户 @ 直接提问独立排队,不计讨论轮次、不与讨论发言合并。initial 阶段先独立判断;服务端按讨论请求的 read_until 限制读取。直接提问和主持任务不继承该阅读限制。",
|
|
1684
1700
|
"主持安排前先 turn roster 读取在场专家、waiting、unregistered 和 revision,再 turn create --roster revision;单项和多项都要带凭据,多项计划须覆盖本轮 waiting。继续排队同样先读 roster,再 turn continue --roster revision。状态或新消息变化后旧凭据被拒绝,重新读取再判断;每个回答保存后由程序推进下一项。",
|
|
1685
1701
|
"局部追问先 turn roster 读取 host_requests 的请求与原消息编号,再 turn ask --request ID --expert NAME --roster revision --submission-id UUID;普通提问不计轮次、不改讨论队列,可问已发言者和主持人,只结束指定请求。",
|
|
@@ -1733,6 +1749,8 @@ class DiscussionServer(ThreadingHTTPServer):
|
|
|
1733
1749
|
self.admin_setup_key = os.getenv("DISCUSS_ADMIN_SETUP_KEY") or secrets.token_urlsafe(18)
|
|
1734
1750
|
service_home = os.getenv("DISCUSS_SERVICE_HOME")
|
|
1735
1751
|
self.connections_file = Path(service_home) / "site-connections.json" if service_home else None
|
|
1752
|
+
# A hosted instance serves only callers that prove they hold its key (backend/entry_guard.py).
|
|
1753
|
+
self.entry_policy = EntryPolicy()
|
|
1736
1754
|
super().__init__(address, DiscussionHandler)
|
|
1737
1755
|
|
|
1738
1756
|
def server_bind(self):
|
|
@@ -1870,9 +1888,35 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
1870
1888
|
if self.deferred_response:
|
|
1871
1889
|
self.send_payload(*self.deferred_response)
|
|
1872
1890
|
|
|
1891
|
+
def entry_refused(self, method, parsed):
|
|
1892
|
+
"""Under entry protection: answer a hello, or refuse a request that is neither public nor proven on its connection."""
|
|
1893
|
+
policy = self.server.entry_policy
|
|
1894
|
+
if not policy.enabled:
|
|
1895
|
+
return False
|
|
1896
|
+
if method == "GET" and parsed.path == HELLO_PATH:
|
|
1897
|
+
answer_hello(self, policy)
|
|
1898
|
+
return True
|
|
1899
|
+
self.entry_key = request_proven(self, policy)
|
|
1900
|
+
if self.entry_key:
|
|
1901
|
+
return False
|
|
1902
|
+
if method == "GET" and (parsed.path in ASSETS or parsed.path in PUBLIC_PATHS):
|
|
1903
|
+
return False
|
|
1904
|
+
self.close_connection = True
|
|
1905
|
+
# Sent directly, not through respond(): a refused caller leaves nothing in any room's event log.
|
|
1906
|
+
self.send_payload(403, "application/json", json.dumps({"error": "这个工作台只接受经入口的访问"}, ensure_ascii=False).encode("utf-8"))
|
|
1907
|
+
return True
|
|
1908
|
+
|
|
1909
|
+
def end_headers(self):
|
|
1910
|
+
"""Say so when an HTTP/1.1 connection (one opened by an entry hello) closes after this response."""
|
|
1911
|
+
if self.request_version == "HTTP/1.1" and self.protocol_version == "HTTP/1.1" and self.close_connection:
|
|
1912
|
+
self.send_header("Connection", "close")
|
|
1913
|
+
super().end_headers()
|
|
1914
|
+
|
|
1873
1915
|
def dispatch_routes(self, method, parsed, params, parts, text_mode):
|
|
1874
1916
|
"""Route one request and map validation, permission and lookup errors to their status codes."""
|
|
1875
1917
|
try:
|
|
1918
|
+
if self.entry_refused(method, parsed):
|
|
1919
|
+
return None
|
|
1876
1920
|
self.bridged = self.relay_bridge(parts)
|
|
1877
1921
|
if parts[:3] == ["api", "local", "media"] and len(parts) == 4 and method == "GET":
|
|
1878
1922
|
return self.serve_media_ticket(parts[3])
|
|
@@ -1919,6 +1963,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
1919
1963
|
self.close_connection = True
|
|
1920
1964
|
self.connection.settimeout(5)
|
|
1921
1965
|
hub = self.server.hub
|
|
1966
|
+
# Under entry protection a stream ends when the key changes or goes, even if nothing else happens meanwhile.
|
|
1967
|
+
policy = self.server.entry_policy
|
|
1968
|
+
opened_key = getattr(self, "entry_key", None) if policy.enabled else None
|
|
1922
1969
|
with hub.updates:
|
|
1923
1970
|
version = hub.update_version
|
|
1924
1971
|
self.send_response(200)
|
|
@@ -1939,6 +1986,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
1939
1986
|
changed = hub.update_version != version
|
|
1940
1987
|
rooms = hub.changed_rooms(version) if changed else None
|
|
1941
1988
|
version = hub.update_version
|
|
1989
|
+
if policy.enabled and policy.key() != opened_key:
|
|
1990
|
+
return
|
|
1942
1991
|
self.wfile.write(update_frame(rooms) if changed else b": keepalive\n\n")
|
|
1943
1992
|
self.wfile.flush()
|
|
1944
1993
|
except OSError:
|
|
@@ -2158,13 +2207,28 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
2158
2207
|
return value
|
|
2159
2208
|
return self.headers.get("X-Discussion-Admin", "")
|
|
2160
2209
|
|
|
2210
|
+
def entry_member_request(self):
|
|
2211
|
+
"""Under entry protection, whether the request names a room credential: it then acts only as that credential.
|
|
2212
|
+
|
|
2213
|
+
Passing the entry proves access to this instance, not a role in a room: a member's credential must not be lifted
|
|
2214
|
+
to the owner's because the request also looks like the loopback page.
|
|
2215
|
+
"""
|
|
2216
|
+
return self.server.entry_policy.enabled and bool(self.headers.get("X-Discussion-Token"))
|
|
2217
|
+
|
|
2218
|
+
def require_entry_owner(self, connection, room_id, token):
|
|
2219
|
+
"""Under entry protection, room management needs the owner's credential or the credential-less page itself."""
|
|
2220
|
+
if self.entry_member_request():
|
|
2221
|
+
require_owner(connection, room_id, token)
|
|
2222
|
+
elif self.server.entry_policy.enabled and not self.local_visitor():
|
|
2223
|
+
raise PermissionError("需要本房间的控制凭据")
|
|
2224
|
+
|
|
2161
2225
|
def local_visitor(self):
|
|
2162
2226
|
"""Whether this request may act as the loopback-only site's implicit administrator.
|
|
2163
2227
|
|
|
2164
2228
|
The Host must name this loopback port, which defeats DNS rebinding, and a browser request must come from the site
|
|
2165
2229
|
itself rather than another page. Programs on this computer can still send these headers; this guards browsers only.
|
|
2166
2230
|
"""
|
|
2167
|
-
if not self.server.local_site:
|
|
2231
|
+
if not self.server.local_site or self.entry_member_request():
|
|
2168
2232
|
return False
|
|
2169
2233
|
host = self.headers.get("Host", "")
|
|
2170
2234
|
if host not in (f"127.0.0.1:{self.server.server_port}", f"localhost:{self.server.server_port}"):
|
|
@@ -2485,6 +2549,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
2485
2549
|
pass
|
|
2486
2550
|
elif method == "POST":
|
|
2487
2551
|
free_actor = authorize_free_write(connection, room_id, token, parts[3] if len(parts) > 3 else "", self.read_payload())
|
|
2552
|
+
if (parts[3:] == ["backup"] and method == "GET") or (len(parts) == 4 and parts[3] in DIRECTORY_OPERATIONS and method == "POST"):
|
|
2553
|
+
self.require_entry_owner(connection, room_id, token)
|
|
2488
2554
|
if parts[3:] == ["backup"] and method == "GET":
|
|
2489
2555
|
if session_read_boundary(connection, room_id, token) is not None:
|
|
2490
2556
|
raise PermissionError("独立观点阶段需房主凭据导出")
|
|
@@ -2852,9 +2918,6 @@ def main():
|
|
|
2852
2918
|
except KeyboardInterrupt:
|
|
2853
2919
|
logging.info("Server stopped")
|
|
2854
2920
|
finally:
|
|
2855
|
-
if remote:
|
|
2856
|
-
remote.shutdown()
|
|
2857
|
-
remote.server_close()
|
|
2858
2921
|
server.server_close()
|
|
2859
2922
|
|
|
2860
2923
|
|