ai_co_discuss 0.4.63 → 0.4.65

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.
@@ -30,6 +30,6 @@ description: "AI CoDiscuss 的主持技能,仅主持人调用,且须同时
30
30
 
31
31
  怎么规划由你判断;只在会改变方向的关键歧义处向用户确认。派活写清谁做什么、做到什么程度,怎么拆、按什么步骤做交给成员——他们背后的软件自己会规划。执行性工作(读长文、写汇总、核对证据、跑测试)派给成员,你做判断、裁定与汇总,上下文与额度留给整个房间的推进。用户的倾向、成员意见一致都不等于已验证事实。
32
32
 
33
- 分派时参考 `room view` 的 `descriptions`(用户写的各成员擅长与分工)。出图、改图优先派给能看图的本机软件成员,它能下载附件自查效果;没有 `image` 字段时请用户在“协作设置”添加生图卡片。
33
+ 分派时参考 `room view` 的 `descriptions`(用户写的各成员擅长与分工)。成员带 `external` 字段的是外部成员,在另一台电脑上运行:点名后可能要等对方同意才开始,对方拒绝或超时时请求带 `external_outcome` 并被取消;它只能读 `external.directories` 里的目录、提交自己的回答,不能派活。出图、改图优先派给能看图的本机软件成员,它能下载附件自查效果;没有 `image` 字段时请用户在“协作设置”添加生图卡片。
34
34
 
35
35
  任务带 `scheduler_suggestions` 时,那是智能调度说明某条消息或交接为何交给你(附置信度),不是用户指令,也未核实:按其中的 `request_id`、`message_id` 先读原文再决定是否采纳,需要依据时 `state decision ROOM DECISION_ID`。`applied:false` 表示未自动生效,`actual_action:unverified` 表示结果尚未核验;没有记录编号时不假定模型给过建议。
@@ -34,6 +34,7 @@ description: "AI CoDiscuss 的通用参与技能,所有参与者(包括主
34
34
  - 用 `codiscuss room …`、`codiscuss message …` 等;任务或用户指定了 CLI 路径就沿用,未安装时用 `python 路径/runner/discuss.py …`。裸 `codiscuss` 会启动服务,不要单独运行。用法查 `codiscuss --help` 或 `codiscuss schema 命令`。
35
35
  - 任务凭据已绑定站点、房间、身份与本次执行:命令省略房间、`--as`、`--execution`、`--submission-id`,由 CLI 补齐。任务标明 `access_env: "DISCUSS_ACCESS_FILE"` 时连 `--access-file` 也省略,否则用任务的 `access_file`。下文命令里的 `ROOM`、`--as`、执行编号只在没有绑定凭据时填写。站点、房间和身份以任务或用户指定值为准,不从网页或聊天推测;文件权限以任务的项目与 `cwd` 为准,CLI 所在仓库不是讨论项目。
36
36
  - 回答正文写成 UTF-8 草稿文件,用 `message post --body-file 草稿.md` 提交(需要摘要时草稿开头写 `---`、`summary: 摘要`、`---`)。
37
+ - **外部成员**(任务带 `external: true`):房间和项目都在另一台电脑上,本机 `cwd` 不是讨论项目。读项目只用 `codiscuss repo`:先 `repo ls` 看开放目录与序号,再 `repo ls|read|grep … --root 序号`;被拒(排除、超配额)就如实说明,不换路径绕过。房间命令只有读房间、读消息、提交回答,附件不可用;收窄运行时文件参数只能指向草稿目录、不能用标准输入。(对方只开放了这些,读取逐条记录在对方电脑。)
37
38
  - 称呼与点名成员用显示名(`room view` 的 `members[].label`),`@`、`--to`、`--expert` 都写它;`name` 是成员 ID,不写进正文。引用他人观点写“显示名 + 编号”(如 `Codex #3262`)。普通成员的 `@` 只是引用,不唤醒、不派活;确实需要主持人处理(超出你的权限或职责)时 `@` 主持人,程序会在房间空闲后唤醒它。
38
39
 
39
40
  ## 阅读
package/README.md CHANGED
@@ -110,6 +110,7 @@ Details: [Architecture](docs/en/architecture.md) · [Setup](docs/en/runner.md)
110
110
  - **From a phone or tablet** — after connecting once and saving your usual projects on that computer, pair a phone or tablet with it once by scanning a QR code at the computer, then use the same site to create rooms whose agents that computer wakes. Folder paths stay on the computer. See [From other devices](docs/en/runner.md#from-other-devices).
111
111
  - **From an AI chat** — ask a local agent to use the `discuss-host` and `discuss-participant` skills to create and host a room. See [From an AI chat](docs/en/runner.md#from-an-ai-chat).
112
112
  - **Model APIs** — configure provider, base URL, protocol and model per member. See [API access](docs/en/runner.md#api-access).
113
+ - **Borrow an AI from another computer** — invite an agent running on someone else's computer (or another of yours) into your room as an external member: it reads only the project folders you open, answers in the room, and you can see every file it read and revoke it at any time. Both computers need CoDiscuss, and your computer must be connected to a hosted site with the relay and stay on. What it reads reaches that computer's model provider. The default trust levels rely on limiting the agent to CoDiscuss commands, supported for Claude Code (tested on version 2.1.325) and model APIs (backed by unit tests); Codex and Antigravity do not support it. See [External members](docs/en/runner.md#external-members-borrowing-an-ai-from-another-computer).
113
114
 
114
115
  ## Deployment
115
116
 
package/README.zh-CN.md CHANGED
@@ -104,6 +104,7 @@ flowchart LR
104
104
  - **手机或平板建房**:在电脑上连接一次并保存常用项目后,在电脑前扫码配对一次手机或平板,之后用同一网站即可新建房间,由那台电脑唤醒 AI,项目路径只留在电脑上。见 [其他设备经已配对电脑建房](docs/runner.md#其他设备经已配对电脑建房)。
105
105
  - **从 AI 对话发起**:让本地 AI 使用 `discuss-host` 和 `discuss-participant` 技能建房并主持。见 [从 AI 对话发起](docs/runner.md#从-ai-对话发起)。
106
106
  - **模型 API**:按成员配置供应商、Base URL、请求协议与模型。见 [API 接入](docs/runner.md#api-接入)。
107
+ - **借用另一台电脑上的 AI**:邀请别人电脑(或你自己另一台电脑)上的 AI 作为外部成员进入你的房间,它只读你开放的项目目录、在房间里回答,你能看到它读过的每个文件并随时撤销。两台电脑都要安装共议,你的电脑须连接带中转的线上网站并保持开机;它读到的内容会发送给对方的模型服务商。默认的信任等级依赖把对方 AI 限制为只用共议命令,目前支持 Claude Code(已在 2.1.325 版实测)与模型 API(以单元测试为据),Codex 与 Antigravity 不支持。见 [外部成员](docs/runner.md#外部成员借用另一台电脑上的-ai)。
107
108
 
108
109
  ## 部署
109
110
 
@@ -0,0 +1,529 @@
1
+ """External members: AIs that run on another computer and reach this room only through the runner's gateway.
2
+
3
+ An external member is a `room_members` row with `access='external'` plus one `external_members` row holding where it
4
+ runs, what it may read, until when, and its read quota. This module is the room-side authority (DESIGN D4): it decides
5
+ validity, expiry and revocation, keeps the read audit and quota counts, and serves the only routes an external
6
+ credential may use (`/api/external/rooms/{room}/...`). Every other route refuses an external credential or a request
7
+ the gateway marked as external; see `guard_route`. Contract: .dev/plans/远程协作与多人房间/子Task1_B侧后端/CONTRACT.md.
8
+ """
9
+
10
+ import hashlib
11
+ import json
12
+ import posixpath
13
+ import time
14
+ from datetime import datetime, timezone
15
+
16
+ from . import free_room
17
+ from .identity import MAX_ROOM_AGENTS, is_ai
18
+ from .runtime import begin_write, require_owner, token_hash
19
+ from .texts import Text, text_payload
20
+
21
+ EXTERNAL_HEADER = "X-CoDiscuss-External"
22
+ BRIDGE_HEADER = "X-CoDiscuss-Bridge"
23
+ EXTERNAL_PREFIX = ["api", "external", "rooms"]
24
+ SCOPES = ("discuss", "read")
25
+ QUOTA_KEYS = ("hourly_bytes", "total_bytes", "hourly_reads")
26
+ DEFAULT_QUOTA = {"hourly_bytes": 4 * 1024 * 1024, "total_bytes": 64 * 1024 * 1024, "hourly_reads": 600}
27
+ MAX_QUOTA = {"hourly_bytes": 1024 ** 3, "total_bytes": 100 * 1024 ** 3, "hourly_reads": 100000}
28
+ MAX_EXTERNAL_SECONDS = 365 * 86400
29
+ MAX_DIRECTORIES = 20
30
+ MAX_DIRECTORY_LENGTH = 500
31
+ MAX_MACHINE = 200
32
+ MAX_MACHINE_LABEL = 80
33
+ MAX_ADAPTER = 40
34
+ HOUR_SECONDS = 3600
35
+ READ_OPS = ("ls", "read", "grep")
36
+ READ_OUTCOMES = ("ok", "denied")
37
+ MAX_READ_PATH = 1000
38
+ MAX_READ_BYTES = 64 * 1024 * 1024
39
+ MAX_READ_REASON = 300
40
+ READ_PAGE = 100
41
+ MAX_READ_PAGE = 500
42
+ END_REASONS = ("revoked", "expired", "left")
43
+ DECLINE_OUTCOMES = ("declined", "timeout")
44
+ MAX_DECLINES = 100
45
+ EXECUTION_ACTIONS = ("renew", "segments", "delivery", "fail", "release", "quiet")
46
+ MESSAGE_PARAMS = ("after", "limit", "page", "q", "author", "mention", "execution_id", "request_id", "max_output_chars")
47
+ ANSWER_FIELDS = ("text", "text_text", "execution_id", "submission_id", "reply_to")
48
+ ENDED_TEXTS = {"revoked": Text("外部成员已被撤销"), "expired": Text("外部成员已到期"), "left": Text("外部成员已退出")}
49
+ EXTERNAL_SQL = """SELECT m.id,m.room_id,m.name,m.adapter,m.role,m.status,m.access,m.session_mode,m.read_until,m.token_hash,
50
+ x.machine,x.machine_label,x.scope,x.directories,x.expires_at,x.hourly_bytes,x.total_bytes,x.hourly_reads,
51
+ x.created_at,x.updated_at,x.ended_at,x.end_reason
52
+ FROM external_members x JOIN room_members m ON m.id=x.member_id"""
53
+
54
+
55
+ def classified(error_class, message, code, **details):
56
+ """Build an error whose response body carries a machine-readable `code` beside the message."""
57
+ error = error_class(message)
58
+ error.details = {"code": code, **details}
59
+ return error
60
+
61
+
62
+ def is_external_path(parts):
63
+ """Whether a split URL path is one of the member-scope routes for external members."""
64
+ return parts[:3] == EXTERNAL_PREFIX and len(parts) >= 5
65
+
66
+
67
+ def guard_route(connect, headers, parts):
68
+ """Refuse every route outside `/api/external/` for a request marked external or carrying an external credential.
69
+
70
+ Runs before the device bridge and all routing, because the local site treats a credential-less loopback request as
71
+ the administrator: the gateway's marker header, not the credential alone, is what keeps such a request out.
72
+ """
73
+ marked = headers.get(EXTERNAL_HEADER) is not None
74
+ if marked and headers.get(BRIDGE_HEADER) is not None:
75
+ raise classified(PermissionError, Text("外部成员请求不能经设备中转"), "external_route_forbidden")
76
+ if parts[:3] == EXTERNAL_PREFIX:
77
+ return
78
+ hashed = token_hash(headers.get("X-Discussion-Token", ""))
79
+ if not marked and hashed:
80
+ connection = connect()
81
+ try:
82
+ marked = connection.execute("SELECT 1 FROM external_members WHERE token_hash=?", (hashed,)).fetchone() is not None
83
+ finally:
84
+ connection.close()
85
+ if marked:
86
+ raise classified(PermissionError, Text("外部成员只能使用成员范围接口"), "external_route_forbidden")
87
+
88
+
89
+ def quota_of(row):
90
+ """The member's three quota limits."""
91
+ return {key: row[key] for key in QUOTA_KEYS}
92
+
93
+
94
+ def usage_of(connection, member_id, now=None):
95
+ """Read counts from the persisted audit: allowed bytes and reads in the last hour, allowed bytes in total, denials."""
96
+ since = ((now or int(time.time())) - HOUR_SECONDS) * 1000
97
+ row = connection.execute("""SELECT COALESCE(SUM(CASE WHEN allowed=1 AND at>? THEN bytes END),0),
98
+ COALESCE(SUM(CASE WHEN allowed=1 AND at>? THEN 1 END),0),COALESCE(SUM(CASE WHEN allowed=1 THEN bytes END),0),
99
+ COALESCE(SUM(CASE WHEN allowed=0 THEN 1 END),0) FROM external_reads WHERE member_id=?""", (since, since, member_id)).fetchone()
100
+ return {"hour_bytes": row[0], "hour_reads": row[1], "total_bytes": row[2], "denied": row[3]}
101
+
102
+
103
+ def directory_names(directories):
104
+ """Directory roots by number with only their last segment, for views that must not show local paths."""
105
+ return [{"root": index, "name": posixpath.basename(path.replace("\\", "/").rstrip("/")) or path}
106
+ for index, path in enumerate(directories)]
107
+
108
+
109
+ def owner_view(connection, row):
110
+ """Describe one external member for the owner, with full directory paths and current usage."""
111
+ labels = free_room.member_display_names(connection, row["room_id"])
112
+ return {"member_id": row["id"], "name": row["name"], "label": labels.get(row["name"], row["name"]), "adapter": row["adapter"],
113
+ "status": row["status"], "machine": row["machine"], "machine_label": row["machine_label"], "scope": row["scope"],
114
+ "directories": json.loads(row["directories"]), "expires_at": row["expires_at"], "quota": quota_of(row),
115
+ "usage": usage_of(connection, row["id"]), "created_at": row["created_at"], "updated_at": row["updated_at"],
116
+ "ended_at": row["ended_at"], "end_reason": row["end_reason"]}
117
+
118
+
119
+ def room_view_field(connection, member_id):
120
+ """The `external` field of a member in the room view, or None for a local member; no local paths."""
121
+ row = connection.execute("SELECT scope,expires_at,machine_label,directories FROM external_members WHERE member_id=?",
122
+ (member_id,)).fetchone()
123
+ if not row:
124
+ return None
125
+ return {"scope": row["scope"], "expires_at": row["expires_at"], "machine_label": row["machine_label"],
126
+ "directories": directory_names(json.loads(row["directories"]))}
127
+
128
+
129
+ def external_row(connection, room_id, member_id):
130
+ """One external member of a room, or LookupError."""
131
+ row = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND x.member_id=?", (room_id, member_id)).fetchone()
132
+ if not row:
133
+ raise LookupError(Text("外部成员不存在"))
134
+ return row
135
+
136
+
137
+ def end_member(connection, row, reason):
138
+ """End an external member: void its live work, cancel its open requests, and refuse its credential from now on."""
139
+ now = int(time.time())
140
+ free_room.discussion.session_member_change(connection, row["room_id"], row, "remove")
141
+ free_room.stop_member_work(connection, row["id"], ENDED_TEXTS[reason], "member_removed")
142
+ connection.execute("UPDATE room_members SET status='removed',role='member' WHERE id=?", (row["id"],))
143
+ connection.execute("UPDATE external_members SET ended_at=?,end_reason=?,updated_at=? WHERE member_id=? AND ended_at=0",
144
+ (now, reason, now, row["id"]))
145
+ free_room.settle_batches(connection, row["room_id"])
146
+ free_room.sync_participants(connection, row["room_id"])
147
+
148
+
149
+ def expire_room(connection, room_id):
150
+ """End every external member of the room whose time is up; returns whether any ended."""
151
+ rows = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.status='active' AND x.ended_at=0 AND x.expires_at<=?",
152
+ (room_id, int(time.time()))).fetchall()
153
+ for row in rows:
154
+ end_member(connection, row, "expired")
155
+ return bool(rows)
156
+
157
+
158
+ def roster_revision(connection, room_id):
159
+ """Version of the room's roster and external settings that a new external member is checked against (red line 1)."""
160
+ members = connection.execute("SELECT id,name,status,access FROM room_members WHERE room_id=? ORDER BY id", (room_id,)).fetchall()
161
+ externals = connection.execute("""SELECT member_id,scope,directories,expires_at,hourly_bytes,total_bytes,hourly_reads,ended_at
162
+ FROM external_members WHERE room_id=? ORDER BY member_id""", (room_id,)).fetchall()
163
+ state = json.dumps([[list(row) for row in members], [list(row) for row in externals]], ensure_ascii=False)
164
+ return hashlib.sha256(state.encode()).hexdigest()
165
+
166
+
167
+ def checked_scope(scope, directories):
168
+ """Validate the opening level and directories together; reading needs at least one directory, discussion none."""
169
+ if scope not in SCOPES:
170
+ raise ValueError(Text("scope 须为 discuss 或 read"))
171
+ if not isinstance(directories, list) or len(directories) > MAX_DIRECTORIES or any(
172
+ not isinstance(item, str) or not item.strip() or len(item) > MAX_DIRECTORY_LENGTH for item in directories):
173
+ raise ValueError(Text("directories 须为最多 {count} 个目录,每个不超过 {length} 字", count=MAX_DIRECTORIES, length=MAX_DIRECTORY_LENGTH))
174
+ if len(set(directories)) != len(directories):
175
+ raise ValueError(Text("开放目录不能重复"))
176
+ if scope == "read" and not directories:
177
+ raise ValueError(Text("只读项目须至少开放一个目录"))
178
+ if scope == "discuss" and directories:
179
+ raise ValueError(Text("只讨论时不开放目录"))
180
+ return directories
181
+
182
+
183
+ def checked_expiry(value, now):
184
+ """Validate an expiry in epoch seconds: later than now and within the longest allowed span."""
185
+ if type(value) is not int or not now < value <= now + MAX_EXTERNAL_SECONDS:
186
+ raise ValueError(Text("expires_at 须为晚于现在、不超过 {days} 天的秒级时间", days=MAX_EXTERNAL_SECONDS // 86400))
187
+ return value
188
+
189
+
190
+ def checked_quota(value, current):
191
+ """Merge given quota limits over `current`; each is a positive integer within its maximum."""
192
+ if value is None:
193
+ return dict(current)
194
+ if not isinstance(value, dict) or set(value) - set(QUOTA_KEYS):
195
+ raise ValueError(Text("quota 只能包含 hourly_bytes、total_bytes、hourly_reads"))
196
+ merged = dict(current)
197
+ for key, item in value.items():
198
+ if type(item) is not int or not 0 < item <= MAX_QUOTA[key]:
199
+ raise ValueError(Text("配额 {key} 须为 1–{limit} 的整数", key=key, limit=MAX_QUOTA[key]))
200
+ merged[key] = item
201
+ return merged
202
+
203
+
204
+ def checked_text(value, limit, field, required=False):
205
+ """Validate a bounded single-line text field."""
206
+ if value is None and not required:
207
+ return ""
208
+ if not isinstance(value, str) or (required and not value.strip()) or len(value) > limit:
209
+ raise ValueError(Text("{field} 须为不超过 {limit} 字的文本", field=field, limit=limit))
210
+ return value
211
+
212
+
213
+ def list_external(connection, room_id, token):
214
+ """The owner's read entry before adding an external member: every external member and the roster revision."""
215
+ require_owner(connection, room_id, token)
216
+ begin_write(connection)
217
+ expire_room(connection, room_id)
218
+ rows = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? ORDER BY m.id", (room_id,)).fetchall()
219
+ return {"revision": roster_revision(connection, room_id), "members": [owner_view(connection, row) for row in rows]}
220
+
221
+
222
+ def get_external(connection, room_id, member_id, token):
223
+ """One external member for the owner or the gateway, expired ones ended first."""
224
+ require_owner(connection, room_id, token)
225
+ begin_write(connection)
226
+ expire_room(connection, room_id)
227
+ return owner_view(connection, external_row(connection, room_id, member_id))
228
+
229
+
230
+ def create_external(connection, room_id, token, payload, now):
231
+ """Add an external member on redemption; the owner credential and a fresh roster revision are required.
232
+
233
+ Returns:
234
+ (body, status): 201 for a new member, 200 when the same redemption is repeated.
235
+ """
236
+ require_owner(connection, room_id, token)
237
+ begin_write(connection)
238
+ expire_room(connection, room_id)
239
+ name, member_token = payload.get("name"), payload.get("token")
240
+ machine = checked_text(payload.get("machine"), MAX_MACHINE, "machine", required=True)
241
+ hashed = token_hash(member_token)
242
+ repeated = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND m.name=? AND x.token_hash=? AND x.machine=? AND m.status='active'",
243
+ (room_id, name, hashed, machine)).fetchone() if hashed else None
244
+ if repeated:
245
+ return {"member": owner_view(connection, repeated), "revision": roster_revision(connection, room_id)}, 200
246
+ if not isinstance(payload.get("revision"), str) or not payload["revision"]:
247
+ raise ValueError(Text("建立外部成员须先读取外部成员名单,并带上其中的 revision"))
248
+ if payload["revision"] != roster_revision(connection, room_id):
249
+ raise classified(FileExistsError, Text("房间成员已变化,请重新读取外部成员名单后再提交"), "stale_revision")
250
+ if not is_ai(name):
251
+ raise ValueError(Text("成员须为有效 AI 身份"))
252
+ if not hashed:
253
+ raise ValueError(Text("每位成员须提供 32–256 字符的成员凭证"))
254
+ adapter = checked_text(payload.get("adapter", ""), MAX_ADAPTER, "adapter")
255
+ label = checked_text(payload.get("machine_label"), MAX_MACHINE_LABEL, "machine_label")
256
+ directories = checked_scope(payload.get("scope"), payload.get("directories", []))
257
+ expires_at = checked_expiry(payload.get("expires_at"), now)
258
+ quota = checked_quota(payload.get("quota"), DEFAULT_QUOTA)
259
+ if connection.execute("SELECT 1 FROM room_members WHERE room_id=? AND name=? AND status<>'removed'", (room_id, name)).fetchone():
260
+ raise FileExistsError(Text("{name} 已是本房间成员", name=name))
261
+ if connection.execute("SELECT COUNT(*) FROM room_members WHERE room_id=? AND status<>'removed'", (room_id,)).fetchone()[0] >= MAX_ROOM_AGENTS:
262
+ raise FileExistsError(Text("房间成员已满"))
263
+ free_room.require_fresh_member_token(connection, room_id, member_token)
264
+ cursor = connection.execute("""INSERT INTO room_members (room_id,name,adapter,token_hash,access,session_mode,created_at)
265
+ VALUES (?,?,?,?,'external','new',?)""", (room_id, name, adapter, hashed, free_room_now()))
266
+ connection.execute("""INSERT INTO external_members (member_id,room_id,token_hash,machine,machine_label,scope,directories,expires_at,
267
+ hourly_bytes,total_bytes,hourly_reads,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
268
+ (cursor.lastrowid, room_id, hashed, machine, label, payload["scope"], json.dumps(directories, ensure_ascii=False),
269
+ expires_at, quota["hourly_bytes"], quota["total_bytes"], quota["hourly_reads"], now, now))
270
+ free_room.queue_invited_expert(connection, room_id, name, now)
271
+ free_room.sync_participants(connection, room_id)
272
+ row = external_row(connection, room_id, cursor.lastrowid)
273
+ return {"member": owner_view(connection, row), "revision": roster_revision(connection, room_id)}, 201
274
+
275
+
276
+ def free_room_now():
277
+ """The member creation time in the same ISO form other members use (server.utc_now)."""
278
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
279
+
280
+
281
+ def update_external(connection, room_id, member_id, token, payload, now):
282
+ """The owner adjusts or revokes one external member; bound to that member, so no roster revision (red line 1 exception)."""
283
+ require_owner(connection, room_id, token)
284
+ begin_write(connection)
285
+ expire_room(connection, room_id)
286
+ row = external_row(connection, room_id, member_id)
287
+ action = payload.get("action")
288
+ if action == "revoke":
289
+ if row["status"] == "active":
290
+ end_member(connection, row, "revoked")
291
+ return owner_view(connection, external_row(connection, room_id, member_id))
292
+ if action != "update":
293
+ raise ValueError(Text("action 须为 update 或 revoke"))
294
+ if row["status"] != "active":
295
+ raise classified(FileExistsError, Text("外部成员已结束,不能再调整;需要时重新邀请"), "external_ended", reason=row["end_reason"])
296
+ scope = payload.get("scope", row["scope"])
297
+ directories = payload.get("directories", [] if scope == "discuss" and "directories" not in payload else json.loads(row["directories"]))
298
+ directories = checked_scope(scope, directories)
299
+ expires_at = checked_expiry(payload["expires_at"], now) if "expires_at" in payload else row["expires_at"]
300
+ quota = checked_quota(payload.get("quota"), quota_of(row))
301
+ label = checked_text(payload["machine_label"], MAX_MACHINE_LABEL, "machine_label") if "machine_label" in payload else row["machine_label"]
302
+ connection.execute("""UPDATE external_members SET scope=?,directories=?,expires_at=?,hourly_bytes=?,total_bytes=?,hourly_reads=?,
303
+ machine_label=?,updated_at=? WHERE member_id=?""", (scope, json.dumps(directories, ensure_ascii=False), expires_at,
304
+ quota["hourly_bytes"], quota["total_bytes"], quota["hourly_reads"], label, now, member_id))
305
+ return owner_view(connection, external_row(connection, room_id, member_id))
306
+
307
+
308
+ def list_reads(connection, room_id, member_id, token, params):
309
+ """The owner reads one external member's read records in order."""
310
+ require_owner(connection, room_id, token)
311
+ external_row(connection, room_id, member_id)
312
+ after = int(params.get("after", 0) or 0)
313
+ limit = min(MAX_READ_PAGE, max(1, int(params.get("limit", READ_PAGE) or READ_PAGE)))
314
+ rows = connection.execute("""SELECT id,at,op,root,directory,path,bytes,allowed,code,reason FROM external_reads
315
+ WHERE member_id=? AND id>? ORDER BY id LIMIT ?""", (member_id, after, limit + 1)).fetchall()
316
+ reads = [{**dict(row), "allowed": bool(row["allowed"])} for row in rows[:limit]]
317
+ return {"reads": reads, "next_after": reads[-1]["id"] if reads else after, "has_more": len(rows) > limit}
318
+
319
+
320
+ def checked_read(payload):
321
+ """Validate one read report from the gateway."""
322
+ op, root, path, size = payload.get("op"), payload.get("root"), payload.get("path", ""), payload.get("bytes")
323
+ outcome, reason = payload.get("outcome"), payload.get("reason", "")
324
+ if op not in READ_OPS or outcome not in READ_OUTCOMES:
325
+ raise ValueError(Text("op 须为 ls、read 或 grep,outcome 须为 ok 或 denied"))
326
+ if type(root) is not int or root < 0 or not isinstance(path, str) or len(path) > MAX_READ_PATH:
327
+ raise ValueError(Text("root 须为非负整数,path 不超过 {limit} 字", limit=MAX_READ_PATH))
328
+ if type(size) is not int or not 0 <= size <= MAX_READ_BYTES:
329
+ raise ValueError(Text("bytes 须为 0–{limit} 的整数", limit=MAX_READ_BYTES))
330
+ if not isinstance(reason, str) or len(reason) > MAX_READ_REASON or (outcome == "denied" and not reason.strip()):
331
+ raise ValueError(Text("reason 不超过 {limit} 字,outcome 为 denied 时必填", limit=MAX_READ_REASON))
332
+ return op, root, path, size, outcome, reason
333
+
334
+
335
+ def read_decision(row, root, size, outcome, reason, usage):
336
+ """Decide one read: (allowed, code, reason). Only reads the engine served count toward the quota."""
337
+ if row["status"] != "active":
338
+ return False, "member_ended", ENDED_TEXTS.get(row["end_reason"], ENDED_TEXTS["revoked"])
339
+ if outcome == "denied":
340
+ return False, "engine_denied", reason
341
+ if row["scope"] != "read":
342
+ return False, "not_readable", Text("该外部成员只讨论,未开放读取项目")
343
+ if root >= len(json.loads(row["directories"])):
344
+ return False, "bad_root", Text("该目录未对外部成员开放")
345
+ if usage["hour_reads"] + 1 > row["hourly_reads"]:
346
+ return False, "quota_hour_reads", Text("本小时读取次数已达上限")
347
+ if usage["hour_bytes"] + size > row["hourly_bytes"]:
348
+ return False, "quota_hour_bytes", Text("本小时读取量已达上限")
349
+ if usage["total_bytes"] + size > row["total_bytes"]:
350
+ return False, "quota_total_bytes", Text("读取总量已达上限")
351
+ return True, "ok", ""
352
+
353
+
354
+ def record_read(connection, room_id, member_id, token, payload):
355
+ """Audit one read, then judge it against the persisted quota, and commit before the gateway may return content.
356
+
357
+ The audit row and the room event are written first (as not allowed), the decision updates them in the same
358
+ transaction, and the transaction commits here: a failure anywhere raises, so the gateway returns nothing.
359
+ """
360
+ require_owner(connection, room_id, token)
361
+ begin_write(connection)
362
+ op, root, path, size, outcome, reason = checked_read(payload)
363
+ expire_room(connection, room_id)
364
+ row = external_row(connection, room_id, member_id)
365
+ directories = json.loads(row["directories"])
366
+ directory = directories[root] if root < len(directories) else ""
367
+ at = int(time.time() * 1000)
368
+ cursor = connection.execute("""INSERT INTO external_reads (member_id,room_id,at,op,root,directory,path,bytes,allowed,code,reason)
369
+ VALUES (?,?,?,?,?,?,?,?,0,'pending','')""", (member_id, room_id, at, op, root, directory, path, size))
370
+ read_id = cursor.lastrowid
371
+ event = connection.execute("INSERT INTO room_events (room_id,at,kind,data) VALUES (?,?,'external.read',?)",
372
+ (room_id, at, json.dumps({"member_id": member_id, "read_id": read_id}))).lastrowid
373
+ allowed, code, why = read_decision(row, root, size, outcome, reason, usage_of(connection, member_id))
374
+ connection.execute("UPDATE external_reads SET allowed=?,code=?,reason=? WHERE id=?", (int(allowed), code, str(why), read_id))
375
+ data = {"member_id": member_id, "member": row["name"], "read_id": read_id, "op": op, "root": root, "directory": directory,
376
+ "path": path, "bytes": size, "allowed": allowed, "code": code, "reason": str(why)}
377
+ connection.execute("UPDATE room_events SET data=? WHERE id=?", (json.dumps(data, ensure_ascii=False), event))
378
+ connection.commit()
379
+ return {"allowed": allowed, "code": code, "reason": why, "reason_text": text_payload(why), "read_id": read_id, "recorded": True,
380
+ "usage": usage_of(connection, member_id)}
381
+
382
+
383
+ def require_external(connection, room_id, token):
384
+ """Resolve the external member of this room from its own credential; an ended one is refused with its reason."""
385
+ begin_write(connection)
386
+ hashed = token_hash(token)
387
+ row = connection.execute(f"{EXTERNAL_SQL} WHERE x.room_id=? AND x.token_hash=?", (room_id, hashed)).fetchone() if hashed else None
388
+ if not row:
389
+ raise classified(PermissionError, Text("需要本房间外部成员的凭证"), "external_credential_required")
390
+ if row["status"] == "active" and row["expires_at"] <= int(time.time()):
391
+ end_member(connection, row, "expired")
392
+ # Kept although the request is refused: the error rolls the request back otherwise.
393
+ connection.commit()
394
+ begin_write(connection)
395
+ row = external_row(connection, room_id, row["id"])
396
+ if row["status"] != "active":
397
+ raise classified(PermissionError, ENDED_TEXTS.get(row["end_reason"], ENDED_TEXTS["revoked"]), "external_ended",
398
+ reason=row["end_reason"] or "revoked")
399
+ return dict(row)
400
+
401
+
402
+ def member_room_view(connection, room_id, member):
403
+ """What an external member sees of the room: title and goal, the roster by name, its own grant; no paths or credentials."""
404
+ room = connection.execute("SELECT r.id,r.title,r.goal,d.archived FROM rooms r JOIN room_directory d ON d.room_id=r.id WHERE r.id=?",
405
+ (room_id,)).fetchone()
406
+ labels = free_room.member_display_names(connection, room_id)
407
+ members = [{"name": row["name"], "label": labels.get(row["name"], row["name"]), "role": row["role"], "status": row["status"],
408
+ "external": row["access"] == "external"}
409
+ for row in connection.execute("SELECT name,role,status,access FROM room_members WHERE room_id=? AND status<>'removed' ORDER BY id",
410
+ (room_id,))]
411
+ latest = connection.execute("""SELECT COALESCE(MAX(id),0) FROM messages m WHERE room_id=?
412
+ AND NOT EXISTS (SELECT 1 FROM internal_task_messages t WHERE t.message_id=m.id)""", (room_id,)).fetchone()[0]
413
+ me = {"member_id": member["id"], "name": member["name"], "label": labels.get(member["name"], member["name"]), "scope": member["scope"],
414
+ "expires_at": member["expires_at"], "directories": directory_names(json.loads(member["directories"])),
415
+ "quota": quota_of(member), "usage": usage_of(connection, member["id"])}
416
+ return {"room": {"id": room["id"], "title": room["title"], "goal": room["goal"], "archived": bool(room["archived"])},
417
+ "me": me, "members": members, "latest_message_id": latest}
418
+
419
+
420
+ def member_inbox(connection, room_id, member):
421
+ """The external member's own open requests, with the same context fields the runner's inbox gives, and its live execution."""
422
+ pending = free_room.pending_requests(connection, member["id"])
423
+ executions = [free_room.public_execution(row) for row in connection.execute(
424
+ "SELECT * FROM member_executions WHERE member_id=? AND status IN ('dispatched','started') ORDER BY id", (member["id"],))]
425
+ return {"member": {"member_id": member["id"], "name": member["name"], "status": member["status"], "expires_at": member["expires_at"]},
426
+ "pending": pending, "executions": executions}
427
+
428
+
429
+ def decline_requests(connection, room_id, member, payload):
430
+ """A declines or lets time out its own pending requests; B then shows them as not agreed to."""
431
+ request_ids, outcome = payload.get("request_ids"), payload.get("outcome")
432
+ if outcome not in DECLINE_OUTCOMES:
433
+ raise ValueError(Text("outcome 须为 declined 或 timeout"))
434
+ if (not isinstance(request_ids, list) or not 0 < len(request_ids) <= MAX_DECLINES
435
+ or any(type(item) is not int for item in request_ids) or len(set(request_ids)) != len(request_ids)):
436
+ raise ValueError(Text("request_ids 须为 1–{limit} 个不重复的请求编号", limit=MAX_DECLINES))
437
+ for request_id in request_ids:
438
+ row = connection.execute("SELECT member_id,status FROM member_requests WHERE room_id=? AND id=?", (room_id, request_id)).fetchone()
439
+ if not row or row["member_id"] != member["id"] or row["status"] != "pending":
440
+ raise FileExistsError(Text("请求 {request_id} 不属于本成员或已处理", request_id=request_id))
441
+ now = int(time.time())
442
+ marks = ",".join("?" * len(request_ids))
443
+ for request_id in request_ids:
444
+ connection.execute("INSERT OR REPLACE INTO external_declines (request_id,member_id,outcome,at) VALUES (?,?,?,?)",
445
+ (request_id, member["id"], outcome, now))
446
+ free_room.record_cancel_reasons(connection, f"id IN ({marks})", tuple(request_ids), "no_reply")
447
+ connection.execute(f"UPDATE member_requests SET status='cancelled' WHERE id IN ({marks})", tuple(request_ids))
448
+ free_room.discussion.after_member_stopped(connection, member["id"])
449
+ free_room.settle_batches(connection, room_id)
450
+ return {"declined": request_ids, "outcome": outcome}
451
+
452
+
453
+ def answer_payload(member, payload):
454
+ """Keep only what an external answer may carry; the author is always the member itself and an execution is required."""
455
+ extra = set(payload) - set(ANSWER_FIELDS) - {"author"}
456
+ if extra:
457
+ raise ValueError(Text("外部成员的回答不能带这些字段:{fields}", fields="、".join(sorted(extra))))
458
+ if payload.get("author", member["name"]) != member["name"]:
459
+ raise PermissionError(Text("成员只能以本人身份发言"))
460
+ if type(payload.get("execution_id")) is not int:
461
+ raise ValueError(Text("成员回答须关联本次执行编号 execution_id"))
462
+ return {**{key: payload[key] for key in ANSWER_FIELDS if key in payload}, "author": member["name"], "source": "cli"}
463
+
464
+
465
+ def leave_room(connection, member):
466
+ """The external member leaves on its own; its credential stops working at once."""
467
+ end_member(connection, member, "left")
468
+ return {"left": True}
469
+
470
+
471
+ def external_api(connection, parts, params, method, token, read_payload, hooks):
472
+ """Serve one member-scope route for an external member.
473
+
474
+ Args:
475
+ parts: The split path, starting `api/external/rooms/{room}`.
476
+ read_payload: Callable returning the JSON body of a POST.
477
+ hooks: Server functions this module cannot import: `messages(connection, room_id, params, token)`,
478
+ `message(connection, room_id, message_id, params, token)` and `answer(connection, room_id, payload, member)`.
479
+
480
+ Returns:
481
+ (body, status)
482
+ """
483
+ room_id, route = parts[3], parts[4:]
484
+ member = require_external(connection, room_id, token)
485
+ reading = {key: params[key] for key in MESSAGE_PARAMS if key in params}
486
+ if method == "GET" and route == ["view"]:
487
+ return member_room_view(connection, room_id, member), 200
488
+ if method == "GET" and route == ["messages"]:
489
+ return hooks["messages"](connection, room_id, reading, token), 200
490
+ if method == "GET" and len(route) == 2 and route[0] == "messages" and route[1].isdigit():
491
+ return hooks["message"](connection, room_id, int(route[1]), reading, token), 200
492
+ if method == "GET" and route == ["inbox"]:
493
+ return member_inbox(connection, room_id, member), 200
494
+ if method != "POST":
495
+ raise LookupError(Text("地址不存在"))
496
+ payload = read_payload()
497
+ if route == ["claim"]:
498
+ return free_room.claim_execution(connection, room_id, member, payload), 200
499
+ if route == ["decline"]:
500
+ return decline_requests(connection, room_id, member, payload), 200
501
+ if len(route) == 2 and route[0] == "executions" and route[1].isdigit():
502
+ if payload.get("action") not in EXECUTION_ACTIONS:
503
+ raise ValueError(Text("外部成员的执行只能 renew、segments、delivery、fail、release 或 quiet"))
504
+ return free_room.execution_action(connection, room_id, int(route[1]), token, payload, member=member), 200
505
+ if route == ["answer"]:
506
+ return hooks["answer"](connection, room_id, answer_payload(member, payload), member), 201
507
+ if route == ["leave"]:
508
+ return leave_room(connection, member), 200
509
+ raise LookupError(Text("地址不存在"))
510
+
511
+
512
+ def owner_api(connection, room_id, route, params, method, token, read_payload):
513
+ """Serve the owner's `/api/rooms/{room}/external-members...` routes; returns (body, status)."""
514
+ now = int(time.time())
515
+ if route == [] and method == "GET":
516
+ return list_external(connection, room_id, token), 200
517
+ if route == [] and method == "POST":
518
+ return create_external(connection, room_id, token, read_payload(), now)
519
+ if len(route) >= 1 and route[0].isdigit():
520
+ member_id = int(route[0])
521
+ if route[1:] == [] and method == "GET":
522
+ return get_external(connection, room_id, member_id, token), 200
523
+ if route[1:] == [] and method == "POST":
524
+ return update_external(connection, room_id, member_id, token, read_payload(), now), 200
525
+ if route[1:] == ["reads"] and method == "GET":
526
+ return list_reads(connection, room_id, member_id, token, params), 200
527
+ if route[1:] == ["reads"] and method == "POST":
528
+ return record_read(connection, room_id, member_id, token, read_payload()), 200
529
+ raise LookupError(Text("地址不存在"))