ai_co_discuss 0.4.63 → 0.4.64

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.
@@ -116,6 +116,8 @@ MAX_DENIALS = 20
116
116
  MAX_DENIAL_FIELD = 300
117
117
  # A manual member's delivery is retried at most this often before the execution fails.
118
118
  MAX_RETRIES = 3
119
+ # Requests one external member may claim by number at once (backend/external_members.py).
120
+ MAX_CLAIM_REQUESTS = 100
119
121
  MAX_RETRY_REASON = 500
120
122
  # One interjection the owner adds to a running execution, and how many one execution keeps.
121
123
  MAX_INTERJECTION_LENGTH = 2000
@@ -144,7 +146,7 @@ MAX_CONTINUE_REASON = 300
144
146
  # A host that left gives up the role; the first active runner member (else manual) then takes it.
145
147
  RELEASE_HOST = "UPDATE room_members SET role='member' WHERE room_id=? AND role='host' AND status<>'active'"
146
148
  ASSIGN_HOST = """UPDATE room_members SET role='host' WHERE id=(SELECT id FROM room_members WHERE room_id=? AND status='active'
147
- ORDER BY access='runner' DESC, id LIMIT 1)
149
+ AND access<>'external' ORDER BY access='runner' DESC, id LIMIT 1)
148
150
  AND NOT EXISTS (SELECT 1 FROM room_members WHERE room_id=? AND role='host' AND status='active')"""
149
151
  TERMINAL = ("completed", "cancelled", "failed")
150
152
  # A queued member has been asked once its request for that message exists.
@@ -1073,6 +1075,8 @@ def free_view(connection, room_id):
1073
1075
  (row["id"],)).fetchone()[0]
1074
1076
  member["held_until"] = held_until(connection, row["id"])
1075
1077
  member["quota_until"] = quota_held_until(connection, row["id"])
1078
+ if row["access"] == "external":
1079
+ member["external"] = external_members.room_view_field(connection, row["id"])
1076
1080
  members.append(member)
1077
1081
  names = {row["id"]: row["name"] for row in connection.execute("SELECT id,name FROM room_members WHERE room_id=?", (room_id,))}
1078
1082
  requests = [{**dict(row), "member": names.get(row["member_id"], ""),
@@ -1080,6 +1084,7 @@ def free_view(connection, room_id):
1080
1084
  } for row in connection.execute(
1081
1085
  """SELECT id,member_id,message_id,status,execution_id,answer_id,chain_id,batch_id,purpose,created_by,created_at,
1082
1086
  (SELECT reason FROM request_cancel_reasons c WHERE c.request_id=member_requests.id) AS cancel_reason,
1087
+ (SELECT outcome FROM external_declines x WHERE x.request_id=member_requests.id) AS external_outcome,
1083
1088
  (SELECT after_message_id FROM request_layout l WHERE l.request_id=member_requests.id) AS layout_after FROM member_requests
1084
1089
  WHERE room_id=? ORDER BY id DESC LIMIT ?""", (room_id, RECENT_REQUESTS))]
1085
1090
  chains = [dict(row) for row in connection.execute(
@@ -2801,6 +2806,7 @@ def inbox(connection, room_id, token):
2801
2806
  require_owner(connection, room_id, token)
2802
2807
  begin_write(connection)
2803
2808
  enforce_session_limits(connection, room_id)
2809
+ external_members.expire_room(connection, room_id)
2804
2810
  expire_executions(connection, room_id)
2805
2811
  notice_stalled_executions(connection, room_id)
2806
2812
  fire_host_checkin(connection, room_id)
@@ -2810,13 +2816,6 @@ def inbox(connection, room_id, token):
2810
2816
  shown = member_display_names(connection, room_id)
2811
2817
  # Manual members are never delivered to; the runner only reads them so smart scheduling can route to them too.
2812
2818
  for row in connection.execute(f"SELECT * FROM room_members WHERE room_id=? AND status='active' AND {REGISTERED_MEMBER} ORDER BY id", (room_id,)):
2813
- pending = [dict(item) for item in connection.execute("""SELECT r.id,r.message_id,r.purpose,r.batch_id,
2814
- sr.id AS session_request_id,sr.session_id,sr.round,sr.position,sr.read_until,sr.question AS source_question,
2815
- t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id,
2816
- (SELECT action FROM group_routes WHERE message_id=r.message_id) AS group_action
2817
- FROM member_requests r LEFT JOIN session_requests sr ON sr.member_request_id=r.id
2818
- LEFT JOIN task_message_sources t ON t.session_request_id=sr.id
2819
- WHERE r.member_id=? AND r.status='pending' ORDER BY r.id""", (row["id"],))]
2820
2819
  member_view = {key: row[key] for key in MEMBER_FIELDS}
2821
2820
  member_view["label"] = shown.get(row["name"], row["name"])
2822
2821
  member_view["review_capability"] = review_capability(connection, room_id, row["id"], token)
@@ -2828,8 +2827,7 @@ def inbox(connection, room_id, token):
2828
2827
  # Private chat lines the runner still has to run in this member's session (backend/private_chat.py).
2829
2828
  member_view["chats"] = [dict(item) for item in connection.execute(
2830
2829
  "SELECT id,text,status FROM private_chats WHERE member_id=? AND status IN ('pending','running') ORDER BY id", (row["id"],))]
2831
- pending = [{**request, **review_request_context(connection, request), **sequence_request_context(connection, request), **handoff_outcome(connection, request),
2832
- **questions.request_context(connection, request)} for request in pending]
2830
+ pending = pending_requests(connection, row["id"])
2833
2831
  (members if row["access"] == "runner" else observers).append({**member_view, "pending": pending})
2834
2832
  # Pending interjections ride along so the runner hands them to the running software at its next check.
2835
2833
  # `continues`: the answered execution whose software turn this one carries on (keep_working); the runner moves it over.
@@ -2846,6 +2844,19 @@ def inbox(connection, room_id, token):
2846
2844
  return {"room_id": room_id, "archived": bool(archived), "members": members, "observers": observers, "executions": executions}
2847
2845
 
2848
2846
 
2847
+ def pending_requests(connection, member_id):
2848
+ """A member's pending requests with the context its software needs: discussion turn, review, relay, hand-back, question."""
2849
+ pending = [dict(item) for item in connection.execute("""SELECT r.id,r.message_id,r.purpose,r.batch_id,
2850
+ sr.id AS session_request_id,sr.session_id,sr.round,sr.position,sr.read_until,sr.question AS source_question,
2851
+ t.cause_kind,t.cause_message_id AS source_message_id,t.cause_request_id,
2852
+ (SELECT action FROM group_routes WHERE message_id=r.message_id) AS group_action
2853
+ FROM member_requests r LEFT JOIN session_requests sr ON sr.member_request_id=r.id
2854
+ LEFT JOIN task_message_sources t ON t.session_request_id=sr.id
2855
+ WHERE r.member_id=? AND r.status='pending' ORDER BY r.id""", (member_id,))]
2856
+ return [{**request, **review_request_context(connection, request), **sequence_request_context(connection, request), **handoff_outcome(connection, request),
2857
+ **questions.request_context(connection, request)} for request in pending]
2858
+
2859
+
2849
2860
  def host_route_request(connection, message_id):
2850
2861
  """The host's request for one unnamed owner message, if the message was routed."""
2851
2862
  return connection.execute("SELECT * FROM member_requests WHERE message_id=? AND purpose='route'", (message_id,)).fetchone()
@@ -3063,6 +3074,33 @@ def reserve_execution(connection, room_id, token, payload):
3063
3074
  (room_id, payload.get("member_id"))).fetchone()
3064
3075
  if not member:
3065
3076
  raise LookupError(Text("成员不存在、已离开或为手动接入"))
3077
+ return open_execution(connection, room_id, member, payload)
3078
+
3079
+
3080
+ def claim_execution(connection, room_id, member, payload):
3081
+ """An external member claims its own open requests as one execution; a retried client_id returns the same one."""
3082
+ begin_write(connection)
3083
+ client_id = str(payload.get("client_id", ""))
3084
+ if not 8 <= len(client_id) <= 100:
3085
+ raise ValueError(Text("client_id 须为 8–100 字符的本地投递编号"))
3086
+ previous = connection.execute("SELECT * FROM member_executions WHERE room_id=? AND client_id=?", (room_id, client_id)).fetchone()
3087
+ if previous:
3088
+ if previous["member_id"] != member["id"]:
3089
+ raise FileExistsError(Text("client_id 已被使用"))
3090
+ return execution_detail(connection, previous)
3091
+ request_ids = payload.get("request_ids")
3092
+ if request_ids is not None and (not isinstance(request_ids, list) or not 0 < len(request_ids) <= MAX_CLAIM_REQUESTS
3093
+ or any(type(item) is not int for item in request_ids) or len(set(request_ids)) != len(request_ids)):
3094
+ raise ValueError(Text("request_ids 须为 1–{limit} 个不重复的请求编号", limit=MAX_CLAIM_REQUESTS))
3095
+ expire_executions(connection, room_id)
3096
+ if connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0]:
3097
+ raise FileExistsError(Text("房间已存档,不再投递"))
3098
+ return open_execution(connection, room_id, member, payload, request_ids)
3099
+
3100
+
3101
+ def open_execution(connection, room_id, member, payload, request_ids=None):
3102
+ """Open one execution over a checked member's pending requests, or only over `request_ids` among them."""
3103
+ client_id = str(payload.get("client_id", ""))
3066
3104
  if connection.execute("SELECT 1 FROM member_executions WHERE member_id=? AND status IN ('dispatched','started')",
3067
3105
  (member["id"],)).fetchone():
3068
3106
  raise FileExistsError(Text("该成员已有进行中的执行;同一会话不并发续接"))
@@ -3073,6 +3111,12 @@ def reserve_execution(connection, room_id, token, payload):
3073
3111
  # A group request waits for the runner to choose how everyone answers; it is never delivered itself.
3074
3112
  pending = connection.execute("""SELECT id,purpose,EXISTS(SELECT 1 FROM review_plans WHERE review_batch_id=member_requests.message_id AND reviewer_id=member_requests.member_id) AS review FROM member_requests
3075
3113
  WHERE member_id=? AND status='pending' AND purpose<>'group' ORDER BY id""", (member["id"],)).fetchall()
3114
+ if request_ids is not None:
3115
+ # An external member's computer agreed to these requests only; the others stay pending for its owner to decide.
3116
+ missing = sorted(set(request_ids) - {row["id"] for row in pending})
3117
+ if missing:
3118
+ raise FileExistsError(Text("请求 {request_id} 不属于本成员或已处理", request_id=missing[0]))
3119
+ pending = [row for row in pending if row["id"] in request_ids]
3076
3120
  session_purpose = next((row["purpose"] for row in pending if row["purpose"] == "discuss"), None)
3077
3121
  if not pending:
3078
3122
  raise FileExistsError(Text("该成员没有待投递的请求"))
@@ -3084,6 +3128,9 @@ def reserve_execution(connection, room_id, token, payload):
3084
3128
  else:
3085
3129
  request_filter = "purpose<>'group' AND NOT EXISTS(SELECT 1 FROM review_plans WHERE review_batch_id=member_requests.message_id AND reviewer_id=member_requests.member_id)"
3086
3130
  request_values = ()
3131
+ if request_ids is not None:
3132
+ request_filter += f" AND id IN ({','.join('?' * len(request_ids))})"
3133
+ request_values = (*request_values, *request_ids)
3087
3134
  now = int(time.time())
3088
3135
  cursor = connection.execute("""INSERT INTO member_executions (room_id,member_id,client_id,lease_until,created_at,cwd)
3089
3136
  VALUES (?,?,?,?,?,?)""", (room_id, member["id"], client_id, now + LEASE_SECONDS, now, str(payload.get("cwd") or "")[:MAX_PATH_LENGTH]))
@@ -3303,13 +3350,15 @@ def execution_interjections(connection, execution_id, execution_status):
3303
3350
  return items
3304
3351
 
3305
3352
 
3306
- def execution_action(connection, room_id, execution_id, token, payload):
3353
+ def execution_action(connection, room_id, execution_id, token, payload, member=None):
3307
3354
  """Runner-side lifecycle: renew, fail, release undelivered work, report how the software was reached, whether a voided one stopped, or observed file changes."""
3308
3355
  begin_write(connection)
3309
3356
  action = payload.get("action")
3310
3357
  duplicate = False
3311
- member = None
3312
- if action == "fail":
3358
+ if member:
3359
+ # An external member already authenticated by backend/external_members.py, acting on its own execution.
3360
+ pass
3361
+ elif action == "fail":
3313
3362
  try:
3314
3363
  require_owner(connection, room_id, token)
3315
3364
  except PermissionError:
@@ -3322,7 +3371,7 @@ def execution_action(connection, room_id, execution_id, token, payload):
3322
3371
  if not row:
3323
3372
  raise LookupError(Text("执行不存在"))
3324
3373
  if member and member["id"] != row["member_id"]:
3325
- raise PermissionError(Text("只能报告自己执行的失败"))
3374
+ raise PermissionError(Text("只能报告自己执行的失败") if action == "fail" else Text("执行编号不属于本成员"))
3326
3375
  now = int(time.time())
3327
3376
  if action == "report":
3328
3377
  # Observed after the process ends, so the execution may already be complete; recorded once.
@@ -3857,6 +3906,8 @@ def member_action(connection, room_id, member_id, token, payload):
3857
3906
  """
3858
3907
  member = owned_member(connection, room_id, member_id, token)
3859
3908
  action = payload.get("action")
3909
+ if member["access"] == "external" and action in ("role", "active", "adopt"):
3910
+ raise ValueError(Text("外部成员不能担任主持人或被请回;需要时重新邀请"))
3860
3911
  routed = []
3861
3912
  if action in ("away", "remove"):
3862
3913
  if member["role"] == "host":
@@ -3918,3 +3969,4 @@ def member_action(connection, room_id, member_id, token, payload):
3918
3969
  # Imported last: session_room imports helpers from this module, so both load in either order.
3919
3970
  from . import session_room as discussion # noqa: E402
3920
3971
  from . import questions # noqa: E402
3972
+ from . import external_members # noqa: E402
@@ -548,6 +548,52 @@ CREATE TABLE IF NOT EXISTS request_cancel_reasons (
548
548
  request_id INTEGER PRIMARY KEY REFERENCES member_requests(id) ON DELETE CASCADE,
549
549
  reason TEXT NOT NULL CHECK(reason IN ('user_stop','member_away','member_removed','rerouted','no_reply','archived'))
550
550
  );
551
+ -- External members (backend/external_members.py): a room_members row with access='external' runs on another computer and
552
+ -- reaches this room only through the runner's gateway. Its grant, expiry and quota live here; `token_hash` repeats the
553
+ -- member's credential hash so every route can refuse that credential outside the member-scope routes. Ended members stay.
554
+ CREATE TABLE IF NOT EXISTS external_members (
555
+ member_id INTEGER PRIMARY KEY REFERENCES room_members(id) ON DELETE CASCADE,
556
+ room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
557
+ token_hash TEXT NOT NULL,
558
+ machine TEXT NOT NULL,
559
+ machine_label TEXT NOT NULL DEFAULT '',
560
+ scope TEXT NOT NULL CHECK(scope IN ('discuss','read')),
561
+ directories TEXT NOT NULL DEFAULT '[]',
562
+ expires_at INTEGER NOT NULL,
563
+ hourly_bytes INTEGER NOT NULL,
564
+ total_bytes INTEGER NOT NULL,
565
+ hourly_reads INTEGER NOT NULL,
566
+ created_at INTEGER NOT NULL,
567
+ updated_at INTEGER NOT NULL,
568
+ ended_at INTEGER NOT NULL DEFAULT 0,
569
+ end_reason TEXT NOT NULL DEFAULT '' CHECK(end_reason IN ('','revoked','expired','left'))
570
+ );
571
+ CREATE INDEX IF NOT EXISTS external_member_credential ON external_members(token_hash);
572
+ -- Every read an external member asked for, allowed or not; quota counts come from here, so they survive restarts.
573
+ -- `at` is epoch milliseconds; `directory` is the opened directory's path at the time, shown to the owner only.
574
+ CREATE TABLE IF NOT EXISTS external_reads (
575
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
576
+ member_id INTEGER NOT NULL REFERENCES room_members(id) ON DELETE CASCADE,
577
+ room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
578
+ at INTEGER NOT NULL,
579
+ op TEXT NOT NULL CHECK(op IN ('ls','read','grep')),
580
+ root INTEGER NOT NULL,
581
+ directory TEXT NOT NULL,
582
+ path TEXT NOT NULL,
583
+ bytes INTEGER NOT NULL,
584
+ allowed INTEGER NOT NULL,
585
+ code TEXT NOT NULL,
586
+ reason TEXT NOT NULL DEFAULT ''
587
+ );
588
+ CREATE INDEX IF NOT EXISTS external_reads_member ON external_reads(member_id,at);
589
+ -- A request the external member's computer declined or let time out; it is cancelled with reason 'no_reply' and the
590
+ -- page shows it as not agreed to.
591
+ CREATE TABLE IF NOT EXISTS external_declines (
592
+ request_id INTEGER PRIMARY KEY REFERENCES member_requests(id) ON DELETE CASCADE,
593
+ member_id INTEGER NOT NULL REFERENCES room_members(id) ON DELETE CASCADE,
594
+ outcome TEXT NOT NULL CHECK(outcome IN ('declined','timeout')),
595
+ at INTEGER NOT NULL
596
+ );
551
597
  -- Messages the owner took back: a retracted one no member began to handle, or the history a rewind returned to before.
552
598
  -- AI readers no longer see them; the page keeps each in place. No room column, so it never clashes with messages.room_id in joins.
553
599
  CREATE TABLE IF NOT EXISTS message_withdrawals (
package/backend/server.py CHANGED
@@ -38,6 +38,7 @@ from .free_room import (add_member, after_free_message, after_proactive, authori
38
38
  from .free_room import convert_suggestion, message_suggestions, save_suggestions, sync_participants
39
39
  from .free_room import adopt_recommendation, recommend_member, register_member, require_member
40
40
  from .private_chat import chat_action, member_chat
41
+ from .external_members import external_api, guard_route as guard_external_route, is_external_path, owner_api as external_owner_api
41
42
  from .free_room import describe_members, execution_notes, label_members, set_host_checkin, withdraw_dispatch, member_descriptions, member_display_names, member_handles, member_labels, reorder_speakers, resolve_member_fields, set_chain_rounds, speaking_order, stop_room, stop_room_work
42
43
  from .free_room import (ADAPTER_VALUE, LAYOUT_AFTER_SQL, LAYOUT_AT_SQL, continue_chain, execution_timeline, group_route_plan, retract_message, rewind_plan, rewind_room,
43
44
  room_event_log, withdrawals)
@@ -75,6 +76,10 @@ LOCAL_LAUNCH_TIMEOUT = 60
75
76
  MACHINE_COMMAND_POLL_SECONDS = 0.5
76
77
  # Ordering and filing a channel only rearrange the shared directory, like folder edits, so they need no room credential.
77
78
  DIRECTORY_OPERATIONS = ("move", "folder")
79
+ # Local entry commands for external members: the owner's invites (room credential) and this computer's invited records.
80
+ INVITE_COMMANDS = ("room-invite", "room-invites", "room-invite-revoke")
81
+ INVITED_COMMANDS = ("invited-list", "invited-join", "invited-trust", "invited-ai", "invited-pause", "invited-approve", "invited-refuse",
82
+ "invited-leave", "invited-room")
78
83
  ADMIN_OPERATIONS = ("rename", "archive", "restore", "delete")
79
84
  DIRECTORY_PICKER_TIMEOUT = 600 # the folder dialog waits for the person at the computer
80
85
  # Files are streamed to players in pieces of this size.
@@ -2475,6 +2480,13 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2475
2480
  try:
2476
2481
  if self.entry_refused(method, parsed):
2477
2482
  return None
2483
+ try:
2484
+ guard_external_route(lambda: connect_db(self.server.database), self.headers, parts)
2485
+ except PermissionError:
2486
+ # Read the unread body first, or the refusal can reach the gateway as a reset connection.
2487
+ self.rfile.read(min(int(self.headers.get("Content-Length") or 0), MAX_BODY_BYTES))
2488
+ self.close_connection = True
2489
+ raise
2478
2490
  self.bridged = self.relay_bridge(parts)
2479
2491
  if parts[:3] == ["api", "local", "media"] and len(parts) == 4 and method == "GET":
2480
2492
  return self.serve_media_ticket(parts[3])
@@ -2488,6 +2500,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2488
2500
  if method == "GET" and parsed.path == "/robots.txt":
2489
2501
  return self.respond("User-agent: *\nAllow: /\n", content_type="text/plain")
2490
2502
  with closing(connect_db(self.server.database)) as connection, connection:
2503
+ if is_external_path(parts):
2504
+ return self.handle_external_api(connection, parts, params, method)
2491
2505
  if text_mode and method == "GET":
2492
2506
  return self.handle_text(connection, parts, params)
2493
2507
  return self.handle_api(connection, parts, params, method)
@@ -2609,7 +2623,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2609
2623
  site = self.local_request_site(method)
2610
2624
  route = parts[2:]
2611
2625
  if method == "OPTIONS" and route in (["settings"], ["launch"], ["room-models"], ["room-skills"], ["room-files"], ["room-page"], ["room-media"], ["execution-details"], ["room-member"], ["room-member-access"], ["room-member-allow"], ["room-member-adapter"], ["room-member-model"], ["room-profiles"], ["room-restore"], ["room-fork"], ["models"], ["sessions"], ["api-key"], ["api-check"],
2612
- ["scheduler-check"], ["image-settings"], ["tts-settings"], ["tts"], ["tts-release"], ["local-speech"], ["stt"], ["weixin"], ["pick-directory"], ["browse-directory"], ["projects"], ["presets"], ["workflows"], ["room-workflow"], ["room-settings"], ["machine-link"], ["device-pairing"], ["devices"]):
2626
+ ["scheduler-check"], ["image-settings"], ["tts-settings"], ["tts"], ["tts-release"], ["local-speech"], ["stt"], ["weixin"], ["pick-directory"], ["browse-directory"], ["projects"], ["presets"], ["workflows"], ["room-workflow"], ["room-settings"], ["machine-link"], ["device-pairing"], ["devices"]) or (method == "OPTIONS" and len(route) == 1 and route[0] in INVITE_COMMANDS + INVITED_COMMANDS):
2613
2627
  return self.respond({"ok": True})
2614
2628
  if route == ["settings"] and method in ("GET", "POST"):
2615
2629
  command = "settings"
@@ -2652,6 +2666,10 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2652
2666
  command = route[0]
2653
2667
  elif route == ["machine-link"] and method == "POST":
2654
2668
  command = "machine-link"
2669
+ elif len(route) == 1 and route[0] in INVITE_COMMANDS + INVITED_COMMANDS and method == "POST":
2670
+ # Invites for members on other computers (runner/external_gateway.mjs) and the rooms this computer was invited to
2671
+ # (runner/external_client.mjs); the latter are this computer's own records and need no room credential.
2672
+ command = route[0]
2655
2673
  else:
2656
2674
  raise LookupError(Text('本机入口不存在'))
2657
2675
  payload = None
@@ -2667,6 +2685,10 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2667
2685
  self.admin_as_owner(connection, payload.get("room_id", ""))
2668
2686
  payload["token"] = self.headers.get("X-Discussion-Token", "")
2669
2687
  # A fork from a browser without the source room's credential acts as its owner, as the commands above do.
2688
+ if command in INVITE_COMMANDS and not payload.get("token") and not self.bridge_origin:
2689
+ with closing(connect_db(self.server.database)) as connection:
2690
+ self.admin_as_owner(connection, payload.get("room_id", ""))
2691
+ payload["token"] = self.headers.get("X-Discussion-Token", "")
2670
2692
  if command == "room-fork" and not payload.get("source_token") and not self.bridge_origin:
2671
2693
  with closing(connect_db(self.server.database)) as connection:
2672
2694
  self.admin_as_owner(connection, payload.get("source_room_id", ""))
@@ -2986,6 +3008,10 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2986
3008
  record_reported_session(connection, room_id, token, {"session_id": self.headers.get("X-Discussion-Session"),
2987
3009
  "session_client": self.headers.get("X-Discussion-Session-Client")})
2988
3010
  connection.commit()
3011
+ if parts[3:4] == ["external-members"]:
3012
+ result, status = external_owner_api(connection, room_id, parts[4:], params, method, token, self.read_payload)
3013
+ connection.commit()
3014
+ return self.respond(result, status)
2989
3015
  if parts[3:] == ["discussion"]:
2990
3016
  if method == "GET":
2991
3017
  return self.respond(session_room(connection, room_id))
@@ -3364,6 +3390,19 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3364
3390
  raise LookupError(Text('地址不存在'))
3365
3391
  return result
3366
3392
 
3393
+ def handle_external_api(self, connection, parts, params, method):
3394
+ """Member-scope routes for an external member (backend/external_members.py); its only way into the room."""
3395
+ def answer(connection, room_id, payload, member):
3396
+ result = append_message(connection, room_id, payload, member)
3397
+ receipt = message_receipt(connection, room_id, result)
3398
+ return {**result, "receipt": receipt} if receipt else result
3399
+ hooks = {"messages": query_messages, "message": get_message, "answer": answer}
3400
+ result, status = external_api(connection, parts, params, method, self.headers.get("X-Discussion-Token", ""),
3401
+ self.read_payload, hooks)
3402
+ drain_room_queue(connection, parts[3])
3403
+ connection.commit()
3404
+ return self.respond(result, status)
3405
+
3367
3406
  def handle_free_api(self, connection, parts, method):
3368
3407
  """Runner inbox, per-member executions and the owner's interrupt for free rooms."""
3369
3408
  room_id = parts[2]
@@ -772,5 +772,42 @@
772
772
  "answers 须为 [{id, selected, custom?}],每道题最多一项": "answers must be [{id, selected, custom?}], at most one entry per question",
773
773
  "answers 的 selected 须为选项列表": "selected in answers must be a list of options",
774
774
  "第 {item} 题不接受自由回答": "Question {item} does not take a free answer",
775
- "第 {item} 题是单选:选一个选项,或填写自由回答": "Question {item} takes one choice: choose an option or write a free answer"
775
+ "第 {item} 题是单选:选一个选项,或填写自由回答": "Question {item} takes one choice: choose an option or write a free answer",
776
+ "action 须为 update 或 revoke": "action must be update or revoke",
777
+ "bytes 须为 0–{limit} 的整数": "bytes must be an integer from 0 to {limit}",
778
+ "client_id 已被使用": "This client_id is already in use",
779
+ "directories 须为最多 {count} 个目录,每个不超过 {length} 字": "directories must list at most {count} directories of up to {length} characters each",
780
+ "expires_at 须为晚于现在、不超过 {days} 天的秒级时间": "expires_at must be a time in seconds later than now and within {days} days",
781
+ "op 须为 ls、read 或 grep,outcome 须为 ok 或 denied": "op must be ls, read or grep, and outcome must be ok or denied",
782
+ "outcome 须为 declined 或 timeout": "outcome must be declined or timeout",
783
+ "quota 只能包含 hourly_bytes、total_bytes、hourly_reads": "quota may only contain hourly_bytes, total_bytes and hourly_reads",
784
+ "reason 不超过 {limit} 字,outcome 为 denied 时必填": "reason must be at most {limit} characters and is required when outcome is denied",
785
+ "request_ids 须为 1–{limit} 个不重复的请求编号": "request_ids must be 1 to {limit} distinct request IDs",
786
+ "root 须为非负整数,path 不超过 {limit} 字": "root must be a non-negative integer and path at most {limit} characters",
787
+ "scope 须为 discuss 或 read": "scope must be discuss or read",
788
+ "{field} 须为不超过 {limit} 字的文本": "{field} must be text of at most {limit} characters",
789
+ "{name} 已是本房间成员": "{name} is already a member of this room",
790
+ "只讨论时不开放目录": "Discussion-only access opens no directories",
791
+ "只读项目须至少开放一个目录": "Read-only project access needs at least one directory",
792
+ "外部成员不存在": "External member not found",
793
+ "外部成员不能担任主持人或被请回;需要时重新邀请": "An external member cannot be the host or be brought back; invite it again if needed",
794
+ "外部成员只能使用成员范围接口": "External members can only use member-scope routes",
795
+ "外部成员已到期": "The external member has expired",
796
+ "外部成员已结束,不能再调整;需要时重新邀请": "The external member has ended and can no longer be changed; invite it again if needed",
797
+ "外部成员已被撤销": "The external member has been revoked",
798
+ "外部成员已退出": "The external member has left",
799
+ "外部成员的回答不能带这些字段:{fields}": "An external member's answer cannot carry these fields: {fields}",
800
+ "外部成员的执行只能 renew、segments、delivery、fail、release 或 quiet": "An external member's execution only accepts renew, segments, delivery, fail, release or quiet",
801
+ "外部成员请求不能经设备中转": "External member requests cannot go through the device relay",
802
+ "建立外部成员须先读取外部成员名单,并带上其中的 revision": "Read the external member list first and include its revision to add an external member",
803
+ "开放目录不能重复": "Opened directories cannot repeat",
804
+ "房间成员已变化,请重新读取外部成员名单后再提交": "The room's members have changed; read the external member list again before submitting",
805
+ "房间成员已满": "The room is full",
806
+ "本小时读取次数已达上限": "The hourly read count limit has been reached",
807
+ "本小时读取量已达上限": "The hourly read volume limit has been reached",
808
+ "该外部成员只讨论,未开放读取项目": "This external member is discussion-only and cannot read the project",
809
+ "该目录未对外部成员开放": "This directory is not open to the external member",
810
+ "读取总量已达上限": "The total read volume limit has been reached",
811
+ "配额 {key} 须为 1–{limit} 的整数": "Quota {key} must be an integer from 1 to {limit}",
812
+ "需要本房间外部成员的凭证": "This room's external member credential is required"
776
813
  }
@@ -0,0 +1,162 @@
1
+ {
2
+ "对方未同意": "Not accepted by the other side",
3
+ "被邀请的房间": "Invited rooms",
4
+ "只讨论": "Discussion only",
5
+ "只看房间里点名给它的请求并回答,不读项目文件": "Sees only the requests that name it and answers them; reads no project files",
6
+ "讨论 + 只读项目": "Discussion + read-only project",
7
+ "另可列目录、读文件、搜索所选目录;不能写入或执行": "Can also list, read and search the chosen directories; cannot write or run anything",
8
+ "只读项目": "Read-only project",
9
+ "1 小时": "1 hour",
10
+ "今天": "Today",
11
+ "3 天": "3 days",
12
+ "对方点名后先问你,同意才唤醒;AI 只能用共议命令": "When named, you are asked first and the AI starts only if you agree; it can only use CoDiscuss commands",
13
+ "完全借用": "Full loan",
14
+ "点名即唤醒,受下面的次数与期限上限;AI 只能用共议命令": "Starts as soon as it is named, within the limits below; the AI can only use CoDiscuss commands",
15
+ "信任设备": "Trusted computer",
16
+ "点名即唤醒,不设上限,按普通只读成员运行;这台电脑之后的邀请直接接受": "Starts as soon as it is named, without limits, as an ordinary read-only member; later invitations from this computer are accepted directly",
17
+ "1 天": "1 day",
18
+ "7 天": "7 days",
19
+ "已到期": "Expired",
20
+ "剩余 {count} 天": "{count} d left",
21
+ "剩余 {count} 小时": "{count} h left",
22
+ "剩余 {count} 分钟": "{count} min left",
23
+ "外部 · 已结束": "External · ended",
24
+ "外部": "External",
25
+ "「{room}」点名了你的 AI,等你同意": "\"{room}\" named your AI and is waiting for your approval",
26
+ "已恢复": "Resumed",
27
+ "已同意,正在唤醒": "Approved, starting the AI",
28
+ "已拒绝,对方会看到“对方未同意”": "Declined; the other side will see \"Not accepted\"",
29
+ "已在这台电脑上退出;对方电脑不在线,它那边要等撤销或到期才会移除": "Left on this computer; the other computer is offline, so it removes you only when it revokes or the membership expires",
30
+ "已退出该房间": "Left the room",
31
+ "邀请已撤销": "Invitation revoked",
32
+ "邀请另一台电脑上的 AI": "Invite an AI on another computer",
33
+ "另一台电脑": "Another computer",
34
+ "移除这张卡片": "Remove this card",
35
+ "能做什么": "What it may do",
36
+ "开放目录": "Open directories",
37
+ "本房间还没有项目目录,只能选“只讨论”。": "This room has no project directory yet, so only \"Discussion only\" is available.",
38
+ "只读:已跟踪与未忽略的文件,固定排除 .env、密钥、凭据、data/ 与 .git。": "Read-only: tracked and non-ignored files; .env, keys, credentials, data/ and .git are always excluded.",
39
+ "有效期": "Valid for",
40
+ "项目内容会经对方的 AI 发送给其模型服务商;读出去的内容收不回,撤销只阻止以后的读取。": "Project content reaches the other side's model provider through their AI; what was read cannot be taken back, and revoking only stops later reads.",
41
+ "房间里发给它的内容会经对方的 AI 发送给其模型服务商。": "What the room sends it reaches the other side's model provider through their AI.",
42
+ "生成邀请": "Create invitation",
43
+ "生成邀请需要本机服务,请在这台电脑打开本机网站。": "Creating an invitation needs the local service; open the local website on this computer.",
44
+ "邀请二维码": "Invitation QR code",
45
+ "把链接或二维码发给对方;对方也可以在自己的共议里输入配对码:": "Send the link or QR code to the other person; they can also enter the pairing code in their own CoDiscuss:",
46
+ "复制配对码": "Copy pairing code",
47
+ "{time} 前兑换有效,只能用一次。对方兑换后直接成为成员,你会收到提示,可随时撤销。": "Redeem before {time}, once only. Whoever redeems it becomes a member at once; you get a notice and can revoke at any time.",
48
+ "配对码不含这台电脑的公钥指纹,优先发链接或二维码。": "The pairing code does not carry this computer's key fingerprint; prefer sending the link or QR code.",
49
+ "再生成一个": "Create another",
50
+ "待兑换的邀请": "Pending invitations",
51
+ "{level} · 成员 {duration} · {left}内兑换": "{level} · member for {duration} · redeem within {left}",
52
+ "立即生效:之后的请求与读取一律被拒,未完成的执行作废。": "Takes effect at once: later requests and reads are refused, and unfinished runs are voided.",
53
+ "已经读出去的内容收不回,会留在对方 AI 的会话里。": "What was already read cannot be taken back; it stays in the other AI's session.",
54
+ "{count} KiB": "{count} KiB",
55
+ "{count} 字节": "{count} bytes",
56
+ "外部成员 · {name}": "External member · {name}",
57
+ "开放目录:{list}": "Open directories: {list}",
58
+ "已读 {used} / {limit},本小时 {hour} / {hour_limit};被拒 {denied} 次": "Read {used} / {limit}, this hour {hour} / {hour_limit}; {denied} refused",
59
+ "调整": "Adjust",
60
+ "延长": "Extend",
61
+ "已延长": "Extended",
62
+ "降为只讨论": "Downgrade to discussion only",
63
+ "已降为只讨论,之后不能再读项目文件": "Downgraded to discussion only; it can no longer read project files",
64
+ "读取记录": "Read log",
65
+ "还没有读取记录": "No reads yet",
66
+ "拒绝:{reason}": "Refused: {reason}",
67
+ "超出范围": "out of scope",
68
+ "记录由这台电脑保存,不采用对方上报的内容。": "Recorded by this computer, not reported by the other side.",
69
+ "撤销外部成员": "Revoke external member",
70
+ "已撤销,对方之后的请求都会被拒绝": "Revoked; its later requests will all be refused",
71
+ "已结束:不能再领取请求或读取文件": "Ended: can no longer take requests or read files",
72
+ "已到期:不能再领取请求或读取文件": "Expired: can no longer take requests or read files",
73
+ "{name} 经邀请加入了房间(外部 · {level});不是你邀请的就在成员菜单里撤销": "{name} joined the room by invitation ({level}); if you did not invite it, revoke it from its member menu",
74
+ "邀请另一台电脑上的 AI 只读本房间项目": "Invite an AI on another computer to read this room's project",
75
+ "等你同意": "Waiting for you",
76
+ "已唤醒": "Started",
77
+ "你未同意": "You declined",
78
+ "超时未确认": "Timed out",
79
+ "已达借用上限,改为等你同意": "Loan limit reached; waiting for your approval instead",
80
+ "这个软件不能限制为只用共议命令,未启动": "This software cannot be limited to CoDiscuss commands; not started",
81
+ "对方房主": "Room owner",
82
+ "对方主持人": "Room host",
83
+ "这里只显示房间「{room}」里点名给你的 AI 的请求和它的回答。": "Only the requests in \"{room}\" that name your AI, and its answers, are shown here.",
84
+ "暂时读不到对方房间:{reason}。下面是这台电脑记下的处理结果。": "Cannot read the other room right now: {reason}. Below is what this computer recorded.",
85
+ "还没有人点名你的 AI。": "No one has named your AI yet.",
86
+ "对方": "The other side",
87
+ "你的 AI": "Your AI",
88
+ "信任等级已更新": "Trust level updated",
89
+ "已唤醒 {count}{limit} 次": "Started {count}{limit} times",
90
+ "在线": "Online",
91
+ "对方电脑不在线": "The other computer is offline",
92
+ "通信出错": "Connection error",
93
+ "未知": "Unknown",
94
+ "对方房间里的成员身份立即结束,之后点名不再唤醒你的 AI。": "Your membership in that room ends at once; being named there no longer starts your AI.",
95
+ "你的 AI 已经读到的内容仍留在它的会话里。": "What your AI already read stays in its session.",
96
+ "待确认的请求": "Requests awaiting approval",
97
+ "{by}点名了你的 AI({messages})": "{by} named your AI ({messages})",
98
+ "{time} 前不确认视为拒绝": "Counts as declined if not approved before {time}",
99
+ "同意并唤醒": "Approve and start",
100
+ "拒绝": "Decline",
101
+ "对方开放": "Opened by them",
102
+ "信任等级": "Trust level",
103
+ "(已暂停)": " (paused)",
104
+ "借用至": "Loan ends",
105
+ "剩余时间": "Time left",
106
+ "连接": "Connection",
107
+ "用配对码加入,未核对对方电脑的公钥指纹。": "Joined with a pairing code; the other computer's key fingerprint was not checked.",
108
+ "信任等级按对方电脑记录:这台电脑邀请的所有房间一起生效。": "Trust is recorded per inviting computer: it applies to every room from that computer.",
109
+ "调整信任等级": "Change trust level",
110
+ "恢复后,对方点名按信任等级处理": "Once resumed, being named is handled by the trust level",
111
+ "暂停期间不领取也不唤醒;已在等你确认的请求到时照常算作未同意": "While paused nothing is taken or started; requests already awaiting you still count as declined when they time out",
112
+ "退出房间": "Leave room",
113
+ "退出「{room}」": "Leave \"{room}\"",
114
+ "用链接或配对码加入": "Join with a link or pairing code",
115
+ "被邀请的房间列表": "Invited room list",
116
+ "{computer} · {trust}": "{computer} · {trust}",
117
+ "未命名房间": "Untitled room",
118
+ "{count} 待确认": "{count} awaiting you",
119
+ "连接本机服务后查看": "Connect the local service to see them",
120
+ "别人邀请你的 AI 加入他的房间后显示在这里": "Rooms you are invited to appear here",
121
+ "只讨论:只看点名给它的请求并回答": "Discussion only: sees only the requests that name it and answers them",
122
+ "讨论 + 只读项目:另可读对方开放的目录,不能写入或执行": "Discussion + read-only project: can also read the opened directories; cannot write or run anything",
123
+ "加入共议房间 · AI CoDiscuss": "Join a CoDiscuss room · AI CoDiscuss",
124
+ "没有邀请内容": "No invitation here",
125
+ "请打开对方发来的完整链接,或在自己的共议里输入配对码。": "Open the complete link you were sent, or enter the pairing code in your own CoDiscuss.",
126
+ "邀请人的电脑": "Inviting computer",
127
+ "开放": "Opens",
128
+ "链接须在此前兑换": "Redeem the link before",
129
+ "复制邀请链接": "Copy invitation link",
130
+ "复制失败,请手动复制地址栏": "Copy failed; copy the address bar manually",
131
+ "你被邀请让自己的 AI 加入一个共议房间": "You are invited to bring your own AI into a CoDiscuss room",
132
+ "你的 AI 在你自己的电脑上运行,用你自己的账号与额度;对方点名后,默认先问你同意才唤醒。": "Your AI runs on your own computer with your own account and quota; by default you are asked before it starts each time it is named.",
133
+ "对方开放的项目内容会经你的 AI 发送给它的模型服务商。": "Project content they open reaches your AI's model provider.",
134
+ "用本机共议加入": "Join with CoDiscuss on this computer",
135
+ "按钮打开这台电脑上的共议(需已安装并运行 codiscuss)。也可以复制链接,在共议左栏“被邀请的房间”里粘贴,或运行 codiscuss join。": "The button opens CoDiscuss on this computer (codiscuss must be installed and running). You can also copy the link and paste it under \"Invited rooms\" in the left sidebar, or run codiscuss join.",
136
+ "邀请内容只在地址的 # 之后,浏览器不会把它发给网站。": "The invitation lives only after the # in the address; browsers never send it to the website.",
137
+ "派 {name} 加入": "Send {name}",
138
+ "已加入「{room}」": "Joined \"{room}\"",
139
+ "加入另一台电脑的房间": "Join a room on another computer",
140
+ "你的 AI 在这台电脑上运行,只读对方开放的目录,在对方房间里回答。": "Your AI runs on this computer, reads only the directories they open, and answers in their room.",
141
+ "邀请链接或配对码": "Invitation link or pairing code",
142
+ "粘贴对方发来的链接,或输入配对码": "Paste the link you were sent, or enter the pairing code",
143
+ "对方的线上站点": "Their online site",
144
+ "配对码不含对方电脑的公钥指纹,无法核对连到的是不是对方;能用链接或扫码时优先用。": "A pairing code carries no key fingerprint of their computer, so it cannot be checked; use the link or QR code when you can.",
145
+ "派哪个 AI": "Which AI to send",
146
+ "加入需要本机服务,请在运行 AI 的电脑打开本机网站。": "Joining needs the local service; open the local website on the computer that runs the AI.",
147
+ "加入": "Join",
148
+ "读取记录与权限": "Read log and access",
149
+ "最多唤醒": "Start at most",
150
+ "最多唤醒次数": "Maximum starts",
151
+ "次,期限": "times, for",
152
+ "期限": "Duration",
153
+ "信任设备下 AI 不再受限,可用本机文件与联网工具;对方房间的内容可能诱导它读这台电脑上的文件。": "As a trusted computer the AI is no longer limited and can use local files and network tools; content in their room could lead it to read files on this computer.",
154
+ "沙箱只读档仍可读整个磁盘、运行任意只读命令,无法只放行 codiscuss 命令": "its read-only sandbox can still read the whole disk and run any read-only command, so it cannot be limited to codiscuss commands",
155
+ "权限由 App 决定,接入程序无法逐次收窄": "the App decides its permissions, so the runner cannot narrow them per task",
156
+ "文件读取、网页读取与搜索工具是否全部受权限规则约束尚未核实,无法保证只放行 codiscuss 命令": "it is not yet verified that its file, web-fetch and search tools all obey permission rules, so only codiscuss commands cannot be guaranteed",
157
+ "不支持的软件适配器": "unsupported software adapter",
158
+ "托管的已有会话沿用它自己的权限,无法收窄": "a taken-over existing session keeps its own permissions and cannot be narrowed",
159
+ "不能收窄": "cannot be narrowed",
160
+ "这个 AI 软件无法限制为只用共议命令({reason}),只能在“信任设备”等级下服务。": "This AI software cannot be limited to CoDiscuss commands ({reason}), so it can serve only at the \"Trusted computer\" level.",
161
+ "这个软件不能限制为只用共议命令({reason}),只能在“信任设备”等级下服务;其他等级下被点名时不会启动。": "This software cannot be limited to CoDiscuss commands ({reason}), so it can serve only at the \"Trusted computer\" level; at other levels it will not start when named."
162
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.63",
3
+ "version": "0.4.64",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },