ai_co_discuss 0.5.59 → 0.5.60

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.
@@ -152,18 +152,12 @@ def distribution(values, histogram=None):
152
152
  REQUESTS = """
153
153
  WITH prior AS (SELECT rr.request_id,min(e.created_at) AS dispatched
154
154
  FROM retried_requests rr JOIN member_executions e ON e.id=rr.execution_id GROUP BY rr.request_id)
155
- SELECT r.room_id,r.message_id,r.chain_id,r.created_at,r.status,mbr.name,mbr.adapter,
155
+ SELECT r.id,r.room_id,r.message_id,r.chain_id,r.created_at,r.status,mbr.name,mbr.adapter,
156
156
  coalesce(l.label,mbr.name) AS label,coalesce(e.model,'') AS model,coalesce(e.effort,'') AS effort,
157
157
  (m.author='用户' AND NOT EXISTS(SELECT 1 FROM message_relays l WHERE l.message_id=m.id)
158
158
  AND NOT EXISTS(SELECT 1 FROM internal_task_messages i WHERE i.message_id=m.id)) AS initiated,
159
159
  CAST(strftime('%s',m.created_at) AS INTEGER) AS sent,CAST(strftime('%s',a.created_at) AS INTEGER) AS answered,
160
- coalesce(w.kind,aw.kind) AS withdrawal,e.result,c.reason,coalesce(prior.dispatched,e.created_at) AS dispatched,
161
- CASE WHEN c.reason='user_stop' AND e.id IS NULL THEN EXISTS(
162
- SELECT 1 FROM room_events stop JOIN room_events cancelled ON cancelled.room_id=stop.room_id
163
- AND cancelled.kind='request.cancel_reason'
164
- AND cancelled.at BETWEEN stop.at AND stop.at+json_extract(stop.data,'$.elapsed_ms')+1
165
- WHERE stop.room_id=r.room_id AND stop.kind='api.write' AND json_extract(stop.data,'$.path')='/stop'
166
- AND json_extract(cancelled.data,'$.request_id')=r.id) END AS stopped_pending
160
+ coalesce(w.kind,aw.kind) AS withdrawal,e.result,c.reason,coalesce(prior.dispatched,e.created_at) AS dispatched
167
161
  FROM member_requests r LEFT JOIN prior ON prior.request_id=r.id JOIN messages m ON m.id=r.message_id
168
162
  JOIN room_directory d ON d.room_id=r.room_id AND d.system_kind=''
169
163
  JOIN room_members mbr ON mbr.id=r.member_id LEFT JOIN member_labels l ON l.room_id=r.room_id AND l.name=mbr.name
@@ -173,12 +167,30 @@ LEFT JOIN message_withdrawals w ON w.message_id=m.id LEFT JOIN message_withdrawa
173
167
  """
174
168
 
175
169
 
176
- def user_stopped(row):
170
+ def stopped_pending(connection, room_id=None):
171
+ """Match owner stop calls to pending requests by the cancellation event's time."""
172
+ query = """SELECT DISTINCT r.id FROM room_events stop INDEXED BY room_events_owner_stop
173
+ CROSS JOIN room_events cancelled ON cancelled.room_id=stop.room_id
174
+ AND cancelled.kind='request.cancel_reason'
175
+ AND cancelled.at BETWEEN stop.at AND stop.at+CASE WHEN json_valid(stop.data)
176
+ THEN json_extract(stop.data,'$.elapsed_ms') END+1
177
+ JOIN member_requests r ON r.id=CASE WHEN json_valid(cancelled.data)
178
+ THEN json_extract(cancelled.data,'$.request_id') END AND r.room_id=stop.room_id
179
+ JOIN request_cancel_reasons c ON c.request_id=r.id AND c.reason='user_stop'
180
+ LEFT JOIN member_executions e ON e.id=r.execution_id
181
+ WHERE stop.kind='api.write' AND CASE WHEN json_valid(stop.data)
182
+ THEN json_extract(stop.data,'$.path') END='/stop' AND e.id IS NULL"""
183
+ if room_id is not None:
184
+ query += " AND stop.room_id=?"
185
+ return {row[0] for row in connection.execute(query, () if room_id is None else (room_id,))}
186
+
187
+
188
+ def user_stopped(row, pending):
177
189
  """Separate owner interventions from host cancellations and send-now follow-ups."""
178
- return row["reason"] == "user_stop" and (row["stopped_pending"] or row["result"] in ("用户打断", "用户停止全部", "用户回退了对话"))
190
+ return row["reason"] == "user_stop" and (row["id"] in pending or row["result"] in ("用户打断", "用户停止全部", "用户回退了对话"))
179
191
 
180
192
 
181
- def overview_facts(rows):
193
+ def overview_facts(rows, pending):
182
194
  """Yield additive facts with their original message or chain cohort timestamp."""
183
195
  messages, chains = defaultdict(list), defaultdict(list)
184
196
  for row in rows:
@@ -195,7 +207,7 @@ def overview_facts(rows):
195
207
  continue
196
208
  first = min(row["created_at"] for row in group)
197
209
  yield first, "ended", 1
198
- if not any(r["withdrawal"] or user_stopped(r) for r in group):
210
+ if not any(r["withdrawal"] or user_stopped(r, pending) for r in group):
199
211
  yield first, "unassisted", 1
200
212
  answers = [r["answered"] for r in group if r["answered"] is not None]
201
213
  if answers and all(r["status"] == "completed" for r in group):
@@ -431,12 +443,14 @@ def actions(connection, start, end):
431
443
  retract = count("""SELECT count(*) FROM message_withdrawals w JOIN messages m ON m.id=w.message_id
432
444
  JOIN room_directory d ON d.room_id=m.room_id AND d.system_kind=''
433
445
  WHERE w.kind='retracted' AND w.created_at>=? AND w.created_at<?""")
434
- stops = count("""SELECT count(*) FROM room_events e JOIN room_directory d ON d.room_id=e.room_id AND d.system_kind=''
446
+ stops = count("""SELECT count(*) FROM room_events e INDEXED BY room_events_owner_stop
447
+ JOIN room_directory d ON d.room_id=e.room_id AND d.system_kind=''
435
448
  WHERE at>=?*1000 AND at<?*1000 AND kind='api.write'
436
- AND json_extract(data,'$.path')='/stop'""")
449
+ AND CASE WHEN json_valid(e.data) THEN json_extract(e.data,'$.path') END='/stop'""")
437
450
  stops += count("""SELECT count(*) FROM room_events e JOIN room_directory d ON d.room_id=e.room_id AND d.system_kind=''
438
451
  WHERE at>=?*1000 AND at<?*1000 AND kind='execution.changed'
439
- AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断'""")
452
+ AND CASE WHEN json_valid(e.data) THEN
453
+ json_extract(e.data,'$.status')='cancelled' AND json_extract(e.data,'$.result')='用户打断' END""")
440
454
  extra = count("""SELECT count(*) FROM execution_interjections i LEFT JOIN interjection_authors a ON a.interjection_id=i.id
441
455
  JOIN room_directory d ON d.room_id=i.room_id AND d.system_kind=''
442
456
  WHERE a.interjection_id IS NULL AND i.created_at>=? AND i.created_at<?""")
@@ -481,8 +495,9 @@ UNION ALL SELECT w.created_at,'withdrawals',1 FROM message_withdrawals w JOIN me
481
495
  UNION ALL SELECT i.created_at,'interjections',1 FROM execution_interjections i
482
496
  LEFT JOIN interjection_authors a ON a.interjection_id=i.id WHERE i.room_id=:room AND a.interjection_id IS NULL
483
497
  UNION ALL SELECT at/1000,'stops',1 FROM room_events WHERE room_id=:room AND
484
- ((kind='api.write' AND json_extract(data,'$.path')='/stop') OR (kind='execution.changed'
485
- AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断'))
498
+ CASE WHEN json_valid(data) THEN
499
+ (kind='api.write' AND json_extract(data,'$.path')='/stop') OR (kind='execution.changed'
500
+ AND json_extract(data,'$.status')='cancelled' AND json_extract(data,'$.result')='用户打断') END
486
501
  """
487
502
 
488
503
 
@@ -493,7 +508,7 @@ def seal_room(connection, room_id, now):
493
508
  key = archive_key(room_id, secret)
494
509
  rows = connection.execute(REQUESTS + " WHERE r.room_id=?", (room_id,)).fetchall()
495
510
  days = defaultdict(lambda: (Counter(), defaultdict(Counter)))
496
- for facts in (overview_facts(rows), room_time_facts(connection, room_id, rows, now),
511
+ for facts in (overview_facts(rows, stopped_pending(connection, room_id)), room_time_facts(connection, room_id, rows, now),
497
512
  connection.execute(ARCHIVE_ACTIONS, {"room": room_id})):
498
513
  for stamp, metric, value in facts:
499
514
  if stamp is None:
@@ -672,22 +687,24 @@ def snapshot(connection, params, cache, now):
672
687
  connection.execute("BEGIN")
673
688
  rooms = tuple(r[0] for r in connection.execute("SELECT room_id FROM room_directory WHERE system_kind='' ORDER BY room_id"))
674
689
  revision = connection.execute("SELECT value FROM site_preferences WHERE key='analytics_revision'").fetchone()
690
+ compact = params.get("compact") == "1"
675
691
  date_key = ("24h", dates["tz"], int(now) // CACHE_SECONDS) if "start_at" in dates else tuple(dates.values())
676
- key = (date_key, rooms, mode, revision[0] if revision else None)
692
+ key = (date_key, rooms, mode, compact, revision[0] if revision else None)
677
693
  hit = cache.get(key)
678
694
  if hit and monotonic() < hit[0]:
679
695
  return hit[1]
680
696
  requests = connection.execute(REQUESTS).fetchall()
681
697
  executions = connection.execute(EXECUTIONS, (end, start, start)).fetchall()
682
698
  revived = {r[0] for r in connection.execute("""SELECT DISTINCT json_extract(data,'$.execution_id') FROM room_events
683
- WHERE kind='execution.changed' AND json_extract(data,'$.from_status')='failed' AND json_extract(data,'$.status')='started'""")}
699
+ WHERE kind='execution.changed' AND CASE WHEN json_valid(data) THEN
700
+ json_extract(data,'$.from_status')='failed' AND json_extract(data,'$.status')='started' END""")}
684
701
  attempts = [r for r in executions if r["created_at"] >= start]
685
702
  earlier_attempts = [r for r in connection.execute(EXECUTIONS, (start, previous, previous)) if r["created_at"] >= previous]
686
703
  assigned = [r for r in requests if start <= r["created_at"] < end]
687
- members = member_stats(attempts, assigned, revived)
704
+ members = [] if compact else member_stats(attempts, assigned, revived)
688
705
  models = member_stats(attempts, assigned, revived, by_model=True)
689
706
  (prior, sealed), retained, sealed_days = sealed_periods(connection, mode, rooms, dates)
690
- facts = list(overview_facts(requests))
707
+ facts = list(overview_facts(requests, stopped_pending(connection)))
691
708
  activity = actions(connection, start, end)
692
709
  for group in activity.values():
693
710
  for name in group:
@@ -703,7 +720,7 @@ def snapshot(connection, params, cache, now):
703
720
  members=members, models=models, workflows=workflow_stats(connection, attempts),
704
721
  scheduler=scheduler,
705
722
  issues=attention_issues(connection, attempts, earlier_attempts, revived, (previous, start, end, now), scheduler["summary"]),
706
- insights=insights(connection, members, start, end))
723
+ insights=[] if compact else insights(connection, members, start, end))
707
724
  result["overview"]["daily"] = daily_overview(dates, facts, executions, sealed_days, now, (start, end))
708
725
  result["time"]["concurrency"]["unfinished"] = unfinished_series(attempts, start, end)
709
726
  result["previous"].update(previous_work(earlier_attempts, previous, start, now))
@@ -70,9 +70,12 @@ SUSPECTED_STALLS = """
70
70
  WHERE q.room_id=g.room_id AND q.created_at<g.end AND (
71
71
  q.created_at>g.start OR q.status IN ('pending','delivering') OR
72
72
  coalesce(CAST(strftime('%s',a.created_at) AS INTEGER),
73
- (SELECT max(v.at)/1000 FROM room_events v WHERE v.room_id=q.room_id AND v.kind='request.changed'
74
- AND json_extract(v.data,'$.request_id')=q.id AND json_extract(v.data,'$.status') IN
75
- ('completed','failed','cancelled')),nullif(e.finished_at,0),g.end)>g.start))
73
+ (SELECT v.at/1000 FROM room_events v
74
+ WHERE v.room_id=q.room_id AND v.kind='request.changed'
75
+ AND CAST(CASE WHEN json_valid(v.data) THEN json_extract(v.data,'$.request_id') END AS NUMERIC)=q.id
76
+ AND CASE WHEN json_valid(v.data) THEN json_extract(v.data,'$.request_id') END=q.id
77
+ AND CASE WHEN json_valid(v.data) THEN json_extract(v.data,'$.status') END IN
78
+ ('completed','failed','cancelled') ORDER BY v.at DESC LIMIT 1),nullif(e.finished_at,0),g.end)>g.start))
76
79
  """
77
80
 
78
81
 
@@ -1994,6 +1994,14 @@ CREATE TABLE IF NOT EXISTS stored_texts (
1994
1994
  PRIMARY KEY (owner, owner_id, field)
1995
1995
  );
1996
1996
  CREATE INDEX IF NOT EXISTS room_events_room ON room_events(room_id,id);
1997
+ CREATE INDEX IF NOT EXISTS room_events_kind_at ON room_events(kind,at);
1998
+ -- Stop analytics names this index so it does not scan every api.write event.
1999
+ CREATE INDEX IF NOT EXISTS room_events_owner_stop ON room_events(at,room_id)
2000
+ WHERE kind='api.write' AND CASE WHEN json_valid(data) THEN json_extract(data,'$.path') END='/stop';
2001
+ CREATE INDEX IF NOT EXISTS room_events_request_terminal ON room_events(
2002
+ room_id,CAST(CASE WHEN json_valid(data) THEN json_extract(data,'$.request_id') END AS NUMERIC),at)
2003
+ WHERE kind='request.changed' AND CASE WHEN json_valid(data) THEN json_extract(data,'$.status') END
2004
+ IN ('completed','failed','cancelled');
1997
2005
  -- Anonymous UTC-day contributions; the key is site-private and never returned by an API.
1998
2006
  CREATE TABLE IF NOT EXISTS analytics_sealed_days (
1999
2007
  archive_key TEXT NOT NULL, day TEXT NOT NULL, counts TEXT NOT NULL, histograms TEXT NOT NULL,
@@ -141,14 +141,14 @@
141
141
  "没有留下说明": "no note left",
142
142
  "涉及 {members}": "Affects {members}",
143
143
  "占相关 {total} 次运行的 {share}": "{share} of {total} related runs",
144
- "同时在跑的专家": "Experts running at once",
144
+ "同时在跑的专家": "Experts at once",
145
145
  "峰值 {count} 位": "Peak {count}",
146
146
  "同时推进": "Rooms at once",
147
147
  "涉及 {members} 等 {count} 组": "Affects {members} and others ({count} groups)",
148
148
  "「{reason}」:{count} 次运行出错": "“{reason}”: {count} runs errored",
149
- "出错的运行": "Runs that errored",
149
+ "出错的运行": "Errored runs",
150
150
  "{when}:{experts} 位专家在 {rooms} 个房间里跑,{count} 次出错": "{when}: {experts} experts running in {rooms} rooms, {count} runs errored",
151
- "同时在跑的房间": "Rooms running at once",
151
+ "同时在跑的房间": "Rooms at once",
152
152
  "点击固定,可打开房间": "Click to pin and open a room",
153
153
  "已固定,点击图表外或按 Esc 取消": "Pinned. Click outside the chart or press Esc to release",
154
154
  "按固定规则从这段时间的运行里挑出:出错的运行(失败,或被系统中途取消;你或主持人主动停止的不算)按原因合并,同一原因影响几个模型也只算一条。占相关运行 5% 以上或比上期翻倍才列出,占 10% 以上或翻倍的标红。只写发生了什么,不判断哪个模型更好。点开可以看到具体是哪几次,并跳到房间里对应的消息。": "Picked from this period's runs by fixed rules. Runs that errored (failed, or cancelled by the system part-way; stops by you or the host do not count) are grouped by reason, so one cause across several models is one item. An item is listed at 5% or more of the related runs or when it doubled, and marked red at 10% or more or when it doubled. Items state what happened and do not judge which model is better. Expand one to see the runs and jump to the message in its room.",
@@ -612,7 +612,8 @@
612
612
  "单文件 HTML": "Single-file HTML",
613
613
  "多文件 HTML": "Multi-file HTML",
614
614
  "线上预览可能缺少部分资源。请在电脑本机打开或部署为网站。": "The online preview may be missing resources. Open it on the host computer or deploy it as a website.",
615
- "旧待部署记录缺少目录归属,请重新登记后再预览或部署": "This older staged site has no recorded project location. Stage it again before previewing or deploying.",
615
+ "原网页不在项目目录内,无法预览,但可点右侧火箭部署为网站": "This page is outside the project folders and cannot be previewed. Use the rocket button to deploy it.",
616
+ "{reason}。请重新登记后再试。": "{reason}. Stage it again and retry.",
616
617
  "多文件网页含外部资源,请在“文件”页下载整个文件夹": "This page uses external files. Download the whole folder from the Files tab.",
617
618
  "此待部署记录没有可预览的项目入口": "This staged site has no project entry to preview.",
618
619
  "请把多文件 HTML 和资源放在独立子目录,再部署为网站": "Move the multi-file HTML and its resources into a dedicated subfolder before deploying.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.5.59",
3
+ "version": "0.5.60",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -1054,6 +1054,7 @@ export default {
1054
1054
  "站点服务返回错误(HTTP {status})": "Site hosting service returned an error (HTTP {status})",
1055
1055
  "待部署记录不存在或已失效,请重新生成": "Staged site record does not exist or has expired; stage it again",
1056
1056
  "待部署记录不属于当前房间": "Staged site record does not belong to this room",
1057
+ "待部署的网页入口已不存在": "The staged website entry no longer exists",
1057
1058
  "待部署的本地目录或文件已不存在": "Staged local directory or file no longer exists",
1058
1059
  "目录为空,没有可发布的静态文件": "Directory is empty; there are no static files to publish",
1059
1060
  "包含不允许发布的文件类型或敏感文件,请排除后再发布": "Contains disallowed file types or sensitive files; exclude them before publishing",
@@ -1065,7 +1066,7 @@ export default {
1065
1066
  "本机尚未注册发布身份,无法操作该站点": "This computer has not registered a publishing identity yet and cannot manage this site",
1066
1067
  "未知的站点命令:{command}": "Unknown site command: {command}",
1067
1068
  "站点不属于当前房间": "This site does not belong to the current room",
1068
- "站点诊断须使用凭据绑定的房间和网站": "Site diagnostics must use the room and server bound to the credential",
1069
+ "网站部署命令须使用凭据绑定的房间和网站": "Website deployment commands must use the room and server bound to the credential",
1069
1070
  "AI CoDiscuss 网站部署\n\n注意:发布到公网须有用户在本房间的明确授权;未经用户明确要求发布时,仅使用 stage 在本机预检登记。\n\n用法:\n codiscuss site stage (--dir 目录 | --file 文件.html) [--room 房间] [--title 标题] [--exclude 路径]\n codiscuss site publish (--dir 目录 | --file 文件.html | --stage 编号) [--site 站点编号] [--room 房间] [--title 标题] [--exclude 路径]\n codiscuss site list [--room 房间]\n codiscuss site diagnose <站点编号> [--room 房间]\n codiscuss site renew <站点编号> [--days 1|3|7] [--room 房间]\n codiscuss site rollback <站点编号> [--version 版本号] [--room 房间]\n codiscuss site revoke <站点编号> [--room 房间]\n\n选项:\n --access-file FILE 任务凭据文件(默认读取 DISCUSS_ACCESS_FILE)\n --room ROOM 房间编号(凭据绑定时自动补齐)\n --url SITE 本机/房间网站地址(凭据绑定时自动补齐)\n --dir PATH 要发布的本机构建目录\n --file PATH 要发布的单个 HTML 文件\n --stage ID 对已预检的待部署编号执行发布\n --site ID 更新已有 10 位站点编号\n --title TEXT 站点标题\n --exclude PATH 排除的相对文件路径(可重复传多次)\n --version N 回滚目标版本号(省略则回滚到上一版)\n --days N 续期天数,从现在起算(1、3 或 7,默认 7)\n --json 以 JSON 输出(默认)\n -h, --help 显示帮助\n": "AI CoDiscuss Website Deployment\n\nNotice: publishing to the public internet requires explicit user authorization in this room; without it, only run `stage` for local preflight.\n\nUsage:\n codiscuss site stage (--dir DIR | --file FILE.html) [--room ROOM] [--title TITLE] [--exclude PATH]\n codiscuss site publish (--dir DIR | --file FILE.html | --stage ID) [--site SITE_ID] [--room ROOM] [--title TITLE] [--exclude PATH]\n codiscuss site list [--room ROOM]\n codiscuss site diagnose <SITE_ID> [--room ROOM]\n codiscuss site renew <SITE_ID> [--days 1|3|7] [--room ROOM]\n codiscuss site rollback <SITE_ID> [--version N] [--room ROOM]\n codiscuss site revoke <SITE_ID> [--room ROOM]\n\nOptions:\n --access-file FILE Task credential file (defaults to DISCUSS_ACCESS_FILE)\n --room ROOM Room ID (auto-filled when bound by credential)\n --url SITE Local/room site URL (auto-filled when bound by credential)\n --dir PATH Local build directory to deploy\n --file PATH Single HTML file to deploy\n --stage ID Publish a previously staged record\n --site ID Update an existing 10-character site ID\n --title TEXT Site title\n --exclude PATH Relative file path to exclude (repeatable)\n --version N Target version for rollback (defaults to previous version)\n --days N Days to renew for, counted from now (1, 3 or 7; default 7)\n --json Output JSON (default)\n -h, --help Show help\n",
1070
1071
  "未知子命令:{sub};运行 codiscuss site --help 查看用法": "Unknown subcommand: {sub}; run `codiscuss site --help` for usage",
1071
1072
  "本次运行已收窄,不能使用 share-card 命令": "This run is restricted and cannot use the share-card command",
@@ -224,11 +224,30 @@ function room_allowed_roots(config, home) {
224
224
  for (const directory of site_project_roots(config)) add(directory);
225
225
  // Not `config.directory`: that is the launch's runtime folder, holding task files and member credentials.
226
226
  }
227
- // Draft directory for member-generated HTML files
228
- add(drafts_root(home));
227
+ // Only this room's member drafts, not the whole account's draft tree.
228
+ add(config ? config.draft_directory || (config.directory ? config.directory + '-drafts' : '') : drafts_root(home));
229
229
  return roots;
230
230
  }
231
231
 
232
+ /** The authenticated member acting on this request, or empty for owner browser operations. */
233
+ function site_actor(input) {
234
+ // Browser requests are owner operations; their member is only the answer's byline. Older
235
+ // in-process callers used member as their identity, so keep that behavior outside web mode.
236
+ return input.actor || (input.entry !== 'web' ? input.member : '');
237
+ }
238
+
239
+ /** Apply the same project access check before either resolving a direct path or restoring a stage. */
240
+ function check_site_actor(config, input) {
241
+ const actor = site_actor(input);
242
+ if (!actor) return;
243
+ const participants = config?.participants || {};
244
+ const profile = Object.hasOwn(participants, actor) ? participants[actor]
245
+ : !input.actor ? Object.values(participants).find(item => item?.label === actor) : null;
246
+ if (profile?.project_access === 'none' || (input.actor && !profile)) {
247
+ throw new SiteCommandError(t('成员 {member} 无权读取该项目目录', { member: actor }), { code: 'auth', http_status: 403 });
248
+ }
249
+ }
250
+
232
251
  function resolve_target_path(home, config, input) {
233
252
  const raw = input.dir || input.file || input.path || '';
234
253
  if (!raw || typeof raw !== 'string') {
@@ -256,19 +275,8 @@ function resolve_target_path(home, config, input) {
256
275
  throw new SiteCommandError(t('目标目录或文件不存在:{path}', { path: raw }), { code: 'missing', http_status: 404 });
257
276
  }
258
277
 
259
- // Enforce room directory boundary when a room config is present (and verify member read permission).
260
- if (config) {
261
- if (input.member) {
262
- // `participants` is an object keyed by member name in launch configs.
263
- const member_cfg = Object.entries(config.participants || {})
264
- .find(([name, p]) => name === input.member || p?.label === input.member)?.[1];
265
- if (member_cfg && member_cfg.project_access === 'none') {
266
- throw new SiteCommandError(t('成员 {member} 无权读取该项目目录', { member: input.member }), { code: 'auth', http_status: 403 });
267
- }
268
- }
269
- if (!roots.some((root) => inside_directory(root, real_target))) {
270
- throw new SiteCommandError(t('目标路径超出本房间允许的项目目录范围'), { code: 'auth', http_status: 403 });
271
- }
278
+ if (config && !roots.some(root => inside_directory(root, real_target))) {
279
+ throw new SiteCommandError(t('目标路径超出本房间允许的项目目录范围'), { code: 'auth', http_status: 403 });
272
280
  }
273
281
 
274
282
  const stat = statSync(real_target);
@@ -451,7 +459,7 @@ function save_local_stage(home, stage_id, record) {
451
459
 
452
460
  function load_local_stage(home, stage_id) {
453
461
  const store = read_json_file(join(home, STAGES_FILE), {});
454
- return store[stage_id] || null;
462
+ return Object.hasOwn(store, stage_id) ? store[stage_id] : null;
455
463
  }
456
464
 
457
465
  async function room_api_request(site, path, { method = 'GET', token = '', body = undefined, fetcher = fetch, signal } = {}) {
@@ -666,7 +674,7 @@ async function diagnose_site(home, conn, site_id, { origin, token, fetcher }) {
666
674
  * that cannot be read refuses too; a site without guest support (404) has no external users.
667
675
  */
668
676
  async function refuse_publish_with_guest(conn, input, fetcher) {
669
- const by_member = Boolean(input.member) || Boolean(input.token && input.token !== conn.config?.token);
677
+ const by_member = Boolean(site_actor(input)) || Boolean(input.token && input.token !== conn.config?.token);
670
678
  if (!by_member || !conn.room_id || !conn.site) return;
671
679
  let state;
672
680
  try {
@@ -701,12 +709,65 @@ function site_entry_name(target, name) {
701
709
  return actual_name;
702
710
  }
703
711
 
712
+ /** Recover a stage from its actual path, using the room's current project and drafts boundaries. */
713
+ function resolve_local_stage(home, conn, stage_id) {
714
+ const staged = load_local_stage(home, stage_id);
715
+ if (!staged) throw new SiteCommandError(t('待部署记录不存在或已失效,请重新生成'), { code: 'missing', http_status: 404 });
716
+ if ((staged.room_id || '') !== conn.room_id) {
717
+ throw new SiteCommandError(t('待部署记录不属于当前房间'), { code: 'auth', http_status: 403 });
718
+ }
719
+ if (typeof staged.local_path !== 'string' || !isAbsolute(staged.local_path)) {
720
+ throw new SiteCommandError(t('待部署记录不存在或已失效,请重新生成'), { code: 'missing', http_status: 404 });
721
+ }
722
+ let target;
723
+ try {
724
+ target = resolve_target_path(home, conn.config, { path: staged.local_path, root: staged.root });
725
+ } catch (error) {
726
+ if (error.code !== 'missing') throw error;
727
+ throw new SiteCommandError(t('待部署的本地目录或文件已不存在'), { code: 'missing', http_status: 404 });
728
+ }
729
+ if (!conn.config && !room_allowed_roots(null, home).some(root => inside_directory(root, target.real_target))) {
730
+ throw new SiteCommandError(t('目标路径超出本房间允许的项目目录范围'), { code: 'auth', http_status: 403 });
731
+ }
732
+ if (target.kind !== staged.kind) {
733
+ throw new SiteCommandError(t('待部署记录不存在或已失效,请重新生成'), { code: 'missing', http_status: 404 });
734
+ }
735
+ if (target.kind === 'directory' && !staged.default_entry) target.entry_name = site_entry_name(target, staged.entry_name);
736
+ return { staged, target };
737
+ }
738
+
739
+ /** Resolve just the recorded entry, without scanning the directory or contacting the site service. */
740
+ function resolve_stage_preview(home, conn, stage_id) {
741
+ const { staged, target } = resolve_local_stage(home, conn, stage_id);
742
+ const { root, kind, real_target, display_dir, entry_name } = target;
743
+ if (root === null) return { stage_id, previewable: false, entry: null, reason: 'outside_project' };
744
+ const name = entry_name || 'index.html';
745
+ const path = kind === 'file' ? display_dir : (display_dir === '.' ? name : display_dir + '/' + name);
746
+ let file;
747
+ try {
748
+ file = kind === 'file' ? real_target : realpathSync.native(join(real_target, name));
749
+ if (!/\.html?$/i.test(path) || !inside_directory(real_target, file) || !statSync(file).isFile()) throw new Error();
750
+ if (kind === 'directory' && !entry_name && !readdirSync(real_target).includes(name)) throw new Error();
751
+ } catch {
752
+ throw new SiteCommandError(t('待部署的网页入口已不存在'), { code: 'missing', http_status: 404 });
753
+ }
754
+ const recorded_name = kind === 'file' ? basename(real_target) : name;
755
+ const default_entry = kind === 'directory' && !entry_name;
756
+ if (staged.root !== root || staged.entry_name !== recorded_name || staged.default_entry !== default_entry) {
757
+ // Keep the default entry distinct from an explicitly selected homepage when publishing later.
758
+ save_local_stage(home, stage_id, { ...staged, root, entry_name: recorded_name, default_entry });
759
+ }
760
+ return { stage_id, previewable: true, entry: { root, path, html_kind: kind === 'directory' ? 'multi' : project_html_kind(file) } };
761
+ }
762
+
704
763
  /** Execute a local site command. */
705
764
  export async function site_command(home, command, input = {}, { fetcher = fetch, sites_origin: origin_override = '' } = {}) {
706
765
  const origin = sites_origin(origin_override || input.sites_origin || '');
707
766
  const conn = resolve_room_connection(home, input);
767
+ if (command === 'site-stage' || command === 'site-publish') check_site_actor(conn.config, input);
708
768
 
709
769
  if (command === 'site-stage') {
770
+ if (input.resolve === true) return resolve_stage_preview(home, conn, input.stage_id);
710
771
  const target = resolve_target_path(home, conn.config, input);
711
772
  target.entry_name = site_entry_name(target, input.entry_name);
712
773
  const scan = scan_site_source(target.real_target, target.kind, input.exclude, target.entry_name);
@@ -719,16 +780,9 @@ export async function site_command(home, command, input = {}, { fetcher = fetch,
719
780
  let effective_exclude = Array.isArray(input.exclude) ? input.exclude : [];
720
781
  let effective_title = input.title || '';
721
782
  if (input.stage_id) {
722
- const staged = load_local_stage(home, input.stage_id);
723
- if (!staged || !Object.hasOwn(staged, 'root')) throw new SiteCommandError(t('待部署记录不存在或已失效,请重新生成'), { code: 'missing', http_status: 404 });
724
- if (conn.room_id && staged.room_id && staged.room_id !== conn.room_id) {
725
- throw new SiteCommandError(t('待部署记录不属于当前房间'), { code: 'auth', http_status: 403 });
726
- }
727
- if (!existsSync(staged.local_path)) {
728
- throw new SiteCommandError(t('待部署的本地目录或文件已不存在'), { code: 'missing', http_status: 404 });
729
- }
730
- target = { real_target: staged.local_path, kind: staged.kind, display_dir: staged.directory, root: staged.root };
731
- target.entry_name = site_entry_name(target, staged.entry_name);
783
+ const resolved = resolve_local_stage(home, conn, input.stage_id);
784
+ const { staged } = resolved;
785
+ target = resolved.target;
732
786
  if (!effective_exclude.length && Array.isArray(staged.exclude)) effective_exclude = staged.exclude;
733
787
  if (!effective_title) effective_title = staged.title;
734
788
  } else {
@@ -1088,6 +1142,7 @@ export async function site_cli(args, { home = service_home(), fetcher = fetch }
1088
1142
  room_id: values.room || access.room || '',
1089
1143
  site: values.url || access.site || process.env.DISCUSS_URL || '',
1090
1144
  token: access.token || '',
1145
+ actor: access.member || '',
1091
1146
  member: access.member || '',
1092
1147
  execution_id: access.execution_id ?? null,
1093
1148
  dir: values.dir || undefined,
@@ -1101,9 +1156,9 @@ export async function site_cli(args, { home = service_home(), fetcher = fetch }
1101
1156
  sites_origin: values['sites-origin'] || undefined,
1102
1157
  };
1103
1158
  try {
1104
- if (sub === 'diagnose' && access.room && (input.room_id !== access.room
1105
- || (values.url && values.url.replace(/\/+$/, '') !== access.site?.replace(/\/+$/, '')))) {
1106
- throw new SiteCommandError(t('站点诊断须使用凭据绑定的房间和网站'), { code: 'auth', http_status: 403 });
1159
+ if ((access.room && values.room !== undefined && values.room !== access.room)
1160
+ || (access.site && values.url !== undefined && values.url.replace(/\/+$/, '') !== access.site.replace(/\/+$/, ''))) {
1161
+ throw new SiteCommandError(t('网站部署命令须使用凭据绑定的房间和网站'), { code: 'auth', http_status: 403 });
1107
1162
  }
1108
1163
  const result = await site_command(home, command, input, { fetcher });
1109
1164
  process.stdout.write(`${JSON.stringify({ ok: true, data: result }, null, 2)}\n`);
@@ -1113,6 +1168,7 @@ export async function site_cli(args, { home = service_home(), fetcher = fetch }
1113
1168
  error: {
1114
1169
  message: error.message,
1115
1170
  code: error.code || 'error',
1171
+ ...(Number.isInteger(error.http_status) ? { http_status: error.http_status } : {}),
1116
1172
  ...(error.details || {}),
1117
1173
  },
1118
1174
  };