ai_co_discuss 0.4.13 → 0.4.16

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.
Files changed (44) hide show
  1. package/.agents/skills/discuss-host/SKILL.md +42 -42
  2. package/.agents/skills/workflow-creator/SKILL.md +155 -155
  3. package/.agents/skills/workflow-creator/references/model-selection.md +24 -23
  4. package/backend/free_room.py +15 -8
  5. package/backend/schema.sql +3 -1
  6. package/backend/server.py +146 -17
  7. package/docs/THIRD_PARTY_NOTICES.md +721 -1
  8. package/docs/runner.md +4 -2
  9. package/docs/workflow.md +1 -1
  10. package/package.json +10 -3
  11. package/runner/adapters/api.mjs +33 -7
  12. package/runner/adapters/api_files.mjs +21 -0
  13. package/runner/adapters/api_images.mjs +245 -0
  14. package/runner/adapters/index.mjs +186 -186
  15. package/runner/adapters/profiles.mjs +152 -139
  16. package/runner/discussion_launch.mjs +49 -11
  17. package/runner/free_runner.mjs +1286 -1281
  18. package/runner/project_files.mjs +390 -330
  19. package/runner/relay_channel.mjs +326 -325
  20. package/runner/remote_launch.mjs +2 -2
  21. package/runner/stt.mjs +135 -111
  22. package/runner/tts.mjs +180 -172
  23. package/runner/tts_providers.mjs +479 -435
  24. package/runner/workflows.mjs +606 -606
  25. package/web/app.js +82 -12
  26. package/web/backup.js +1 -1
  27. package/web/markdown.css +1 -1
  28. package/web/modern.css +1 -1
  29. package/web/modern.js +663 -40
  30. package/web/office/assets/pptx-source-worker-559Vl2R3.mjs +446 -0
  31. package/web/office/assets/pptx_parser_bg-DON650C_.wasm +0 -0
  32. package/web/office/assets/render-worker-Ck21oePL-D_L2C4am.js +16 -0
  33. package/web/office/chunks/comment-ui-runtime-Bp37ytDC-CEDIeFBy.js +125 -0
  34. package/web/office/chunks/emf--QWY-UlT-D7lCNost.js +1 -0
  35. package/web/office/chunks/font-preload-demand-NqcVKIpX-_QhVEaPJ.js +1 -0
  36. package/web/office/chunks/plot-area-frame-DNYMd9Pf-B0ScWz_J.js +2 -0
  37. package/web/office/chunks/pptx-DbjWegUB-CU8ZIJEP.js +4 -0
  38. package/web/office/chunks/presentation-model-source-DLNioq7T-Demo5cCW.js +1 -0
  39. package/web/office/chunks/render-worker-host-CVr53kg0-DUcW76F6.js +1 -0
  40. package/web/office/chunks/slide-pull-client-3g6TxaKa-BohMnKOC.js +12 -0
  41. package/web/office/chunks/worker-source-ZQE9C1j6-B31UTbq3.js +1 -0
  42. package/web/office/docx.js +21 -0
  43. package/web/office/pptx.js +1 -0
  44. package/web/office/xlsx.js +64 -0
package/backend/server.py CHANGED
@@ -72,6 +72,11 @@ MACHINE_COMMAND_POLL_SECONDS = 0.5
72
72
  DIRECTORY_OPERATIONS = ("move", "folder")
73
73
  ADMIN_OPERATIONS = ("rename", "archive", "restore", "delete")
74
74
  DIRECTORY_PICKER_TIMEOUT = 600 # the folder dialog waits for the person at the computer
75
+ # Files are streamed to players in pieces of this size.
76
+ FILE_CHUNK_BYTES = 1024 * 1024
77
+ # A project media file the local page plays is served by a random ticket for this long after the runner checked access.
78
+ MEDIA_TICKET_SECONDS = 600
79
+ MAX_MEDIA_TICKETS = 64
75
80
  MAX_TEXT_LENGTH = 32000
76
81
  SESSION_ID_PATTERN = re.compile(r"[0-9A-Za-z_-]{8,128}")
77
82
  MAX_STATE_LENGTH = 4000
@@ -102,6 +107,12 @@ ASSETS.update({"/pdfjs/" + file.relative_to(WEB_ROOT / "pdfjs").as_posix():
102
107
  (file.relative_to(WEB_ROOT).as_posix(),
103
108
  {".mjs": "text/javascript", ".js": "text/javascript", ".wasm": "application/wasm"}.get(file.suffix, "application/octet-stream"))
104
109
  for file in (WEB_ROOT / "pdfjs").rglob("*") if file.is_file()})
110
+ # Office previews the page imports only when such a file is opened, with their WebAssembly and workers.
111
+ if (WEB_ROOT / "office").is_dir():
112
+ ASSETS.update({"/office/" + file.relative_to(WEB_ROOT / "office").as_posix():
113
+ (file.relative_to(WEB_ROOT).as_posix(),
114
+ {".mjs": "text/javascript", ".js": "text/javascript", ".wasm": "application/wasm", ".css": "text/css"}.get(file.suffix, "application/octet-stream"))
115
+ for file in (WEB_ROOT / "office").rglob("*") if file.is_file()})
105
116
  # KaTeX's stylesheet and the fonts it loads only when a formula is shown.
106
117
  ASSETS.update({"/katex/" + file.relative_to(WEB_ROOT / "katex").as_posix():
107
118
  (file.relative_to(WEB_ROOT).as_posix(),
@@ -407,9 +418,10 @@ def require_room(connection, room_id):
407
418
  room["round_groups"] = merge_round_groups(connection, room_id)
408
419
  room["members"] = [dict(row) for row in connection.execute(
409
420
  """SELECT m.id,m.name,m.adapter,m.role,m.status,m.access,m.session_mode,COALESCE(s.session_id,'') AS reported_session,COALESCE(s.client,'') AS reported_client,
410
- COALESCE(r.registered_at,'') AS registered_at
421
+ COALESCE(r.registered_at,'') AS registered_at,COALESCE(c.image_model,'') AS image_model
411
422
  FROM room_members AS m LEFT JOIN member_sessions AS s ON s.member_id=m.id
412
423
  LEFT JOIN member_registrations AS r ON r.member_id=m.id AND r.token_hash=m.token_hash
424
+ LEFT JOIN member_capabilities AS c ON c.member_id=m.id
413
425
  WHERE m.room_id=? AND m.status<>'removed' ORDER BY m.id""", (room_id,))]
414
426
  # Members are called by label in text and in @; the ID (name) is part of the full record, like the description.
415
427
  shown = member_display_names(connection, room_id)
@@ -1065,8 +1077,18 @@ def attachment_metadata(params):
1065
1077
  return {"file_name": name, "actor": actor, "submission_id": submission_value(params.get("submission_id"))}
1066
1078
 
1067
1079
 
1080
+ # An SVG document: optional BOM, XML declaration, comments and doctype, then the <svg> root element.
1081
+ SVG_START = re.compile(rb"^(?:\xef\xbb\xbf)?\s*(?:<\?xml[^>]*>\s*)?(?:<!--.*?-->\s*)*(?:<!DOCTYPE\s+svg[^>]*>\s*)?(?:<!--.*?-->\s*)*<svg[\s>/]",
1082
+ re.IGNORECASE | re.DOTALL)
1083
+ SVG_SNIFF_BYTES = 4096
1084
+
1085
+
1068
1086
  def attachment_content_type(data):
1069
- """Allow inline preview only for recognized raster images and PDF bytes."""
1087
+ """Allow inline preview only for recognized images and PDF bytes.
1088
+
1089
+ SVG is shown only as an <img>, where its scripts and external loads never run; opened directly it is still served
1090
+ with a sandboxing Content-Security-Policy (see respond_attachment).
1091
+ """
1070
1092
  signatures = ((b"\x89PNG\r\n\x1a\n", "image/png"), (b"\xff\xd8\xff", "image/jpeg"),
1071
1093
  (b"GIF87a", "image/gif"), (b"GIF89a", "image/gif"), (b"%PDF-", "application/pdf"))
1072
1094
  for signature, content_type in signatures:
@@ -1074,6 +1096,32 @@ def attachment_content_type(data):
1074
1096
  return content_type
1075
1097
  if data.startswith(b"RIFF") and data[8:12] == b"WEBP":
1076
1098
  return "image/webp"
1099
+ if SVG_START.match(data[:SVG_SNIFF_BYTES]):
1100
+ return "image/svg+xml"
1101
+ return media_content_type(data)
1102
+
1103
+
1104
+ def media_content_type(data):
1105
+ """Audio and video by their container signature, for the page's players; unknown bytes stay a download."""
1106
+ if data[4:8] == b"ftyp":
1107
+ brand = data[8:12]
1108
+ return "audio/mp4" if brand in (b"M4A ", b"M4B ") else "video/quicktime" if brand == b"qt " else "video/mp4"
1109
+ if data.startswith(b"\x1a\x45\xdf\xa3"):
1110
+ return "video/webm" if b"webm" in data[:64] else "video/x-matroska"
1111
+ if data.startswith(b"OggS"):
1112
+ return "video/ogg" if b"theora" in data[:128] else "audio/ogg"
1113
+ if data.startswith(b"RIFF") and data[8:12] == b"WAVE":
1114
+ return "audio/wav"
1115
+ if data.startswith(b"fLaC"):
1116
+ return "audio/flac"
1117
+ if data.startswith(b"ID3"):
1118
+ return "audio/mpeg"
1119
+ if len(data) > 1 and data[0] == 0xFF:
1120
+ # ADTS AAC frames have layer bits 00; MPEG audio frames (MP3) have a non-zero layer.
1121
+ if data[1] & 0xF6 == 0xF0:
1122
+ return "audio/aac"
1123
+ if data[1] & 0xE0 == 0xE0 and data[1] & 0x06:
1124
+ return "audio/mpeg"
1077
1125
  return "application/octet-stream"
1078
1126
 
1079
1127
 
@@ -1675,6 +1723,9 @@ class DiscussionServer(ThreadingHTTPServer):
1675
1723
  if local_launch and (address[0] != "127.0.0.1" or hub):
1676
1724
  raise ValueError("本机启动入口须绑定 127.0.0.1")
1677
1725
  self.local_launch = local_launch
1726
+ # Project media the local page may play: ticket -> (path, size, mtime_ns, content_type, name, expires).
1727
+ self.media_tickets = {}
1728
+ self.media_lock = threading.Lock()
1678
1729
  self.local_site = not hub and address[0] in ("127.0.0.1", "::1", "localhost")
1679
1730
  self.admin_setup_key = os.getenv("DISCUSS_ADMIN_SETUP_KEY") or secrets.token_urlsafe(18)
1680
1731
  service_home = os.getenv("DISCUSS_SERVICE_HOME")
@@ -1757,7 +1808,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
1757
1808
  def send_payload(self, status, content_type, data):
1758
1809
  """Write the status line, headers and encoded body."""
1759
1810
  self.send_response(status)
1760
- self.send_header("Content-Type", f"{content_type}; charset=utf-8")
1811
+ # Binary assets (WebAssembly, fonts, images) carry no charset; `application/wasm` must stay exact for streaming compile.
1812
+ textual = content_type.startswith("text/") or content_type == "application/json"
1813
+ self.send_header("Content-Type", f"{content_type}; charset=utf-8" if textual else content_type)
1761
1814
  self.send_header("Content-Length", str(len(data)))
1762
1815
  self.send_header("Cache-Control", "no-store")
1763
1816
  if getattr(self, "etag", None):
@@ -1818,6 +1871,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
1818
1871
  """Route one request and map validation, permission and lookup errors to their status codes."""
1819
1872
  try:
1820
1873
  self.bridged = self.relay_bridge(parts)
1874
+ if parts[:3] == ["api", "local", "media"] and len(parts) == 4 and method == "GET":
1875
+ return self.serve_media_ticket(parts[3])
1821
1876
  if parts[:2] == ["api", "local"]:
1822
1877
  return self.handle_local_launch(parts, method)
1823
1878
  if parts == ["api", "updates"] and method == "GET":
@@ -1938,7 +1993,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
1938
1993
  """Forward authenticated browser requests to the shared Node entrypoint and pin their website."""
1939
1994
  site = self.local_request_site(method)
1940
1995
  route = parts[2:]
1941
- if method == "OPTIONS" and route in (["settings"], ["launch"], ["room-models"], ["room-files"], ["room-page"], ["execution-details"], ["room-member"], ["room-member-access"], ["room-member-allow"], ["room-member-adapter"], ["room-member-model"], ["room-profiles"], ["room-restore"], ["room-fork"], ["models"], ["api-key"], ["api-check"],
1996
+ if method == "OPTIONS" and route in (["settings"], ["launch"], ["room-models"], ["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"], ["api-key"], ["api-check"],
1942
1997
  ["scheduler-check"], ["tts-settings"], ["tts"], ["tts-release"], ["stt"], ["weixin"], ["pick-directory"], ["browse-directory"], ["projects"], ["presets"], ["workflows"], ["room-workflow"], ["room-settings"], ["machine-link"], ["device-pairing"], ["devices"]):
1943
1998
  return self.respond({"ok": True})
1944
1999
  if route == ["settings"] and method in ("GET", "POST"):
@@ -1961,7 +2016,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
1961
2016
  command = route[0]
1962
2017
  elif route in (["room-member"], ["room-member-access"], ["room-member-allow"], ["room-member-adapter"], ["room-member-model"]) and method == "POST":
1963
2018
  command = route[0]
1964
- elif route in (["room-profiles"], ["room-files"], ["room-page"], ["execution-details"], ["room-restore"], ["room-fork"]) and method == "POST":
2019
+ elif route in (["room-profiles"], ["room-files"], ["room-page"], ["room-media"], ["execution-details"], ["room-restore"], ["room-fork"]) and method == "POST":
1965
2020
  command = route[0]
1966
2021
  elif route == ["pick-directory"] and method == "POST":
1967
2022
  command = "pick-directory"
@@ -1987,10 +2042,10 @@ class DiscussionHandler(BaseHTTPRequestHandler):
1987
2042
  if self.headers.get_content_type() != "application/json":
1988
2043
  raise ValueError("本机操作须使用 application/json")
1989
2044
  payload = self.read_payload()
1990
- if command in ("start", "room-config", "room-models", "room-files", "room-page", "execution-details", "room-member", "room-member-access", "room-member-allow", "room-member-adapter", "room-member-model", "room-profiles", "room-restore", "room-fork", "room-workflow", "room-settings", "workflows"):
2045
+ if command in ("start", "room-config", "room-models", "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", "room-workflow", "room-settings", "workflows"):
1991
2046
  payload.pop("access_file", None)
1992
2047
  payload.update(site=site, entry="web")
1993
- if command in ("room-files", "room-page", "execution-details", "room-workflow", "room-settings", "room-member", "room-member-access", "room-member-allow", "room-member-model", "room-member-adapter") and not payload.get("token") and not self.bridge_origin:
2048
+ if command in ("room-files", "room-page", "room-media", "execution-details", "room-workflow", "room-settings", "room-member", "room-member-access", "room-member-allow", "room-member-model", "room-member-adapter") and not payload.get("token") and not self.bridge_origin:
1994
2049
  with closing(connect_db(self.server.database)) as connection:
1995
2050
  self.admin_as_owner(connection, payload.get("room_id", ""))
1996
2051
  payload["token"] = self.headers.get("X-Discussion-Token", "")
@@ -2003,9 +2058,48 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2003
2058
  payload = {"site": site}
2004
2059
  if command == "room-config" and "participants" in payload:
2005
2060
  return self.save_local_room_configuration(command, payload)
2061
+ # The computer's own page plays a project media file straight from disk by a ticket, with ranges for seeking.
2062
+ if command == "room-media" and not self.bridge_origin:
2063
+ return self.issue_media_ticket(payload)
2006
2064
  # A connected website's page is another device's entry: it gets the same limits as the relay.
2007
2065
  return self.run_local_command(command, payload, remote=bool(self.bridge_origin) and command != "machine-link")
2008
2066
 
2067
+ def issue_media_ticket(self, payload):
2068
+ """Let the runner check the member's access to one project media file, then hand the page a ticket URL for it.
2069
+
2070
+ The page never learns the file's path; the ticket names one file as it was checked and expires.
2071
+ """
2072
+ status, result = self.local_command_result("room-media", payload)
2073
+ if status != 200:
2074
+ return self.respond(result, status)
2075
+ path = Path(result.pop("file"))
2076
+ info = path.stat()
2077
+ ticket = secrets.token_urlsafe(32)
2078
+ now = time.time()
2079
+ with self.server.media_lock:
2080
+ tickets = self.server.media_tickets
2081
+ for key in [key for key, item in tickets.items() if item[5] <= now]:
2082
+ del tickets[key]
2083
+ while len(tickets) >= MAX_MEDIA_TICKETS:
2084
+ del tickets[next(iter(tickets))]
2085
+ tickets[ticket] = (path, info.st_size, info.st_mtime_ns, result["content_type"], path.name, now + MEDIA_TICKET_SECONDS)
2086
+ return self.respond({**result, "url": f"/api/local/media/{ticket}"})
2087
+
2088
+ def serve_media_ticket(self, ticket):
2089
+ """Stream the project media file a ticket names, refusing it once expired or changed since it was checked."""
2090
+ with self.server.media_lock:
2091
+ item = self.server.media_tickets.get(ticket)
2092
+ if not item or item[5] <= time.time():
2093
+ raise LookupError("播放地址已过期,请重新打开文件")
2094
+ path, size, mtime_ns, content_type, name, _ = item
2095
+ try:
2096
+ info = path.stat()
2097
+ except OSError:
2098
+ raise LookupError("文件已不存在") from None
2099
+ if (info.st_size, info.st_mtime_ns) != (size, mtime_ns):
2100
+ raise FileExistsError("文件已变化,请重新打开")
2101
+ self.send_file(path, content_type, name, "inline")
2102
+
2009
2103
  def save_local_room_configuration(self, command, payload):
2010
2104
  """Keep session pause/revision validation and local file replacement in one boundary."""
2011
2105
  with closing(connect_db(self.server.database)) as connection, connection:
@@ -2020,7 +2114,12 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2020
2114
  return self.run_local_command(command, payload, configuration_locked=True)
2021
2115
 
2022
2116
  def run_local_command(self, command, payload, configuration_locked=False, remote=False):
2023
- """Run the fixed local Node entrypoint after the same-origin request checks."""
2117
+ """Run the fixed local Node entrypoint after the same-origin request checks, and answer with its result."""
2118
+ status, result = self.local_command_result(command, payload, configuration_locked, remote)
2119
+ return self.respond(result, status)
2120
+
2121
+ def local_command_result(self, command, payload, configuration_locked=False, remote=False):
2122
+ """Run the fixed local Node entrypoint; returns `(status, result)`, 400 with its error when it fails."""
2024
2123
  arguments = ["node", str(ROOT / "runner" / "discussion_launch.mjs"), command]
2025
2124
  if remote:
2026
2125
  arguments.append("--remote")
@@ -2045,8 +2144,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2045
2144
  failure = json.loads(result.stderr.strip())
2046
2145
  except ValueError:
2047
2146
  raise ValueError(result.stderr.strip())
2048
- return self.respond(failure, 400)
2049
- return self.respond(json.loads(result.stdout))
2147
+ return 400, failure
2148
+ return 200, json.loads(result.stdout)
2050
2149
 
2051
2150
  def admin_token(self):
2052
2151
  """The administrator login from its HttpOnly cookie, or from the header scripts and tests use."""
@@ -2505,19 +2604,49 @@ class DiscussionHandler(BaseHTTPRequestHandler):
2505
2604
  path = attachment_path(self.server.database, attachment)
2506
2605
  if not path.is_file():
2507
2606
  raise LookupError("附件原文件缺失")
2508
- data = path.read_bytes()
2509
2607
  disposition = "attachment" if download or attachment["content_type"] == "application/octet-stream" else "inline"
2510
- self.send_response(200)
2511
- self.send_header("Content-Type", attachment["content_type"])
2512
- self.send_header("Content-Length", str(len(data)))
2513
- self.send_header("Content-Disposition", f"{disposition}; filename*=UTF-8''{quote(attachment['file_name'], safe='')}")
2514
- self.send_header("X-Content-SHA256", attachment["sha256"])
2608
+ self.send_file(path, attachment["content_type"], attachment["file_name"], disposition, {"X-Content-SHA256": attachment["sha256"]})
2609
+
2610
+ def send_file(self, path, content_type, file_name, disposition, extra=None):
2611
+ """Send one stored file, or the single byte range a player asks for, never as executable content."""
2612
+ size = path.stat().st_size
2613
+ start, end, status = 0, size - 1, 200
2614
+ match = re.fullmatch(r"bytes=(\d*)-(\d*)", self.headers.get("Range", "").strip())
2615
+ if match and (match[1] or match[2]):
2616
+ if match[1]:
2617
+ start, end = int(match[1]), min(int(match[2]), size - 1) if match[2] else size - 1
2618
+ else:
2619
+ start = max(0, size - int(match[2]))
2620
+ if start > end or start >= size:
2621
+ self.send_response(416)
2622
+ self.send_header("Content-Range", f"bytes */{size}")
2623
+ self.send_header("Content-Length", "0")
2624
+ self.end_headers()
2625
+ return
2626
+ status = 206
2627
+ self.send_response(status)
2628
+ self.send_header("Content-Type", content_type)
2629
+ self.send_header("Content-Length", str(max(0, end - start + 1)))
2630
+ self.send_header("Accept-Ranges", "bytes")
2631
+ if status == 206:
2632
+ self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
2633
+ self.send_header("Content-Disposition", f"{disposition}; filename*=UTF-8''{quote(file_name, safe='')}")
2634
+ for name, value in (extra or {}).items():
2635
+ self.send_header(name, value)
2515
2636
  self.send_header("X-Content-Type-Options", "nosniff")
2516
2637
  self.send_header("Content-Security-Policy", "default-src 'none'; sandbox")
2517
2638
  self.send_header("Cache-Control", "no-store")
2518
2639
  self.send_header("Referrer-Policy", "no-referrer")
2519
2640
  self.end_headers()
2520
- self.wfile.write(data)
2641
+ with path.open("rb") as source:
2642
+ source.seek(start)
2643
+ left = end - start + 1
2644
+ while left > 0:
2645
+ chunk = source.read(min(FILE_CHUNK_BYTES, left))
2646
+ if not chunk:
2647
+ break
2648
+ self.wfile.write(chunk)
2649
+ left -= len(chunk)
2521
2650
 
2522
2651
  def handle_scheduler_api(self, connection, parts, method):
2523
2652
  """Smart-scheduling decisions, their feedback and the routing marks of the local service."""