dsh-quay-bot 0.7.4 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +105 -28
- package/bin/doctor.mjs +148 -0
- package/botscreen/requirements-offline.txt +11 -0
- package/client.js +1 -2
- package/cordis.patch.yml +1 -1
- package/host/api.js +0 -4
- package/host/remote.js +2 -140
- package/host/screen.js +85 -21
- package/market/index.json +41 -0
- package/package.json +32 -13
- package/vendor/wheels/any/annotated_doc-0.0.7-py3-none-any.whl +0 -0
- package/vendor/wheels/any/annotated_types-0.8.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/anyio-4.16.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/certifi-2026.11.20-py3-none-any.whl +0 -0
- package/vendor/wheels/any/click-8.5.1-py3-none-any.whl +0 -0
- package/vendor/wheels/any/fastapi-0.165.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/h11-0.16.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/httpcore-1.0.9-py3-none-any.whl +0 -0
- package/vendor/wheels/any/httpx-0.29.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/idna-3.20-py3-none-any.whl +0 -0
- package/vendor/wheels/any/mss-10.2.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/opentelemetry_api-1.45.2-py3-none-any.whl +0 -0
- package/vendor/wheels/any/pydantic-2.14.4-py3-none-any.whl +0 -0
- package/vendor/wheels/any/python_multipart-0.0.34-py3-none-any.whl +0 -0
- package/vendor/wheels/any/python_xlib-0.33-py2.py3-none-any.whl +0 -0
- package/vendor/wheels/any/six-1.17.0-py2.py3-none-any.whl +0 -0
- package/vendor/wheels/any/starlette-1.10.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/typing_extensions-4.16.0-py3-none-any.whl +0 -0
- package/vendor/wheels/any/typing_inspection-0.4.5-py3-none-any.whl +0 -0
- package/vendor/wheels/any/uvicorn-0.54.0-py3-none-any.whl +0 -0
- package/vendor/wheels/linux-aarch64/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl +0 -0
- package/vendor/wheels/linux-aarch64/pydantic_core-2.50.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl +0 -0
- package/vendor/wheels/linux-aarch64/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl +0 -0
- package/vendor/wheels/linux-x86_64/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl +0 -0
- package/vendor/wheels/linux-x86_64/pydantic_core-2.50.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl +0 -0
- package/vendor/wheels/linux-x86_64/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl +0 -0
- package/botscreen/botscreen/__init__.py +0 -2
- package/botscreen/botscreen/__main__.py +0 -5
- package/botscreen/botscreen/artifacts.py +0 -388
- package/botscreen/botscreen/audit.py +0 -94
- package/botscreen/botscreen/cgroup.py +0 -293
- package/botscreen/botscreen/config.py +0 -320
- package/botscreen/botscreen/desktop/assets/chrome.png +0 -0
- package/botscreen/botscreen/desktop/assets/codex.png +0 -0
- package/botscreen/botscreen/desktop/assets/drive.png +0 -0
- package/botscreen/botscreen/desktop/assets/folder.png +0 -0
- package/botscreen/botscreen/desktop/assets/search.png +0 -0
- package/botscreen/botscreen/desktop/assets/terminal.png +0 -0
- package/botscreen/botscreen/desktop/assets/trash.png +0 -0
- package/botscreen/botscreen/desktop/assets/wallpaper.png +0 -0
- package/botscreen/botscreen/desktop.py +0 -244
- package/botscreen/botscreen/driver.py +0 -832
- package/botscreen/botscreen/gateway.py +0 -2089
- package/botscreen/botscreen/iconlayer.py +0 -841
- package/botscreen/botscreen/mcp_server.py +0 -435
- package/botscreen/botscreen/resources.py +0 -494
- package/botscreen/botscreen/screen.py +0 -1282
- package/botscreen/botscreen/session.py +0 -706
- package/botscreen/botscreen/state.py +0 -330
- package/botscreen/botscreen/streamer.py +0 -388
- package/remote/bin/dsh-remote.mjs +0 -418
- package/remote/package.json +0 -27
- package/remote/src/config.mjs +0 -183
- package/remote/src/crypto.mjs +0 -220
- package/remote/src/keys.mjs +0 -226
- package/remote/src/proxy.mjs +0 -1028
- package/remote/src/sessions.mjs +0 -163
- package/remote/src/shim.js +0 -838
- package/remote/src/supervisor.mjs +0 -207
- package/remote/src/tunnel.mjs +0 -489
- package/remote/src/upstream.mjs +0 -372
- package/remote/src/util.mjs +0 -139
- package/remote/src/ws.mjs +0 -313
- package/requirements.txt +0 -8
|
@@ -1,388 +0,0 @@
|
|
|
1
|
-
"""Agent 回复产物(Artifact)网关存储、检索、下载与打包管理。"""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
import base64
|
|
5
|
-
import contextlib
|
|
6
|
-
import hashlib
|
|
7
|
-
import io
|
|
8
|
-
import json
|
|
9
|
-
import mimetypes
|
|
10
|
-
import os
|
|
11
|
-
import re
|
|
12
|
-
import secrets
|
|
13
|
-
import tempfile
|
|
14
|
-
import time
|
|
15
|
-
import zipfile
|
|
16
|
-
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
17
|
-
from urllib.parse import quote
|
|
18
|
-
|
|
19
|
-
from fastapi import HTTPException
|
|
20
|
-
|
|
21
|
-
from .config import ARTIFACT_BUNDLE_MAX_BYTES, ARTIFACT_MAX_BYTES
|
|
22
|
-
|
|
23
|
-
_SAFE_ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,96}$")
|
|
24
|
-
_SAFE_KIND_SET = {"artifact", "deliverable", "file", "reply"}
|
|
25
|
-
|
|
26
|
-
_EXT_BY_TYPE = {
|
|
27
|
-
"html": "html",
|
|
28
|
-
"htm": "html",
|
|
29
|
-
"markdown": "md",
|
|
30
|
-
"md": "md",
|
|
31
|
-
"json": "json",
|
|
32
|
-
"yaml": "yaml",
|
|
33
|
-
"yml": "yml",
|
|
34
|
-
"xml": "xml",
|
|
35
|
-
"svg": "svg",
|
|
36
|
-
"csv": "csv",
|
|
37
|
-
"tsv": "tsv",
|
|
38
|
-
"python": "py",
|
|
39
|
-
"py": "py",
|
|
40
|
-
"javascript": "js",
|
|
41
|
-
"js": "js",
|
|
42
|
-
"typescript": "ts",
|
|
43
|
-
"ts": "ts",
|
|
44
|
-
"css": "css",
|
|
45
|
-
"sql": "sql",
|
|
46
|
-
"shell": "sh",
|
|
47
|
-
"sh": "sh",
|
|
48
|
-
"bash": "sh",
|
|
49
|
-
"pdf": "pdf",
|
|
50
|
-
"png": "png",
|
|
51
|
-
"jpeg": "jpg",
|
|
52
|
-
"jpg": "jpg",
|
|
53
|
-
"webp": "webp",
|
|
54
|
-
"gif": "gif",
|
|
55
|
-
"zip": "zip",
|
|
56
|
-
"text": "txt",
|
|
57
|
-
"txt": "txt",
|
|
58
|
-
"code": "txt",
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
_MIME_BY_TYPE = {
|
|
62
|
-
"html": "text/html; charset=utf-8",
|
|
63
|
-
"htm": "text/html; charset=utf-8",
|
|
64
|
-
"markdown": "text/markdown; charset=utf-8",
|
|
65
|
-
"md": "text/markdown; charset=utf-8",
|
|
66
|
-
"json": "application/json; charset=utf-8",
|
|
67
|
-
"yaml": "application/yaml; charset=utf-8",
|
|
68
|
-
"yml": "application/yaml; charset=utf-8",
|
|
69
|
-
"xml": "application/xml; charset=utf-8",
|
|
70
|
-
"svg": "image/svg+xml",
|
|
71
|
-
"csv": "text/csv; charset=utf-8",
|
|
72
|
-
"tsv": "text/tab-separated-values; charset=utf-8",
|
|
73
|
-
"css": "text/css; charset=utf-8",
|
|
74
|
-
"javascript": "text/javascript; charset=utf-8",
|
|
75
|
-
"js": "text/javascript; charset=utf-8",
|
|
76
|
-
"typescript": "text/typescript; charset=utf-8",
|
|
77
|
-
"ts": "text/typescript; charset=utf-8",
|
|
78
|
-
"python": "text/x-python; charset=utf-8",
|
|
79
|
-
"py": "text/x-python; charset=utf-8",
|
|
80
|
-
"text": "text/plain; charset=utf-8",
|
|
81
|
-
"txt": "text/plain; charset=utf-8",
|
|
82
|
-
"code": "text/plain; charset=utf-8",
|
|
83
|
-
"pdf": "application/pdf",
|
|
84
|
-
"png": "image/png",
|
|
85
|
-
"jpeg": "image/jpeg",
|
|
86
|
-
"jpg": "image/jpeg",
|
|
87
|
-
"webp": "image/webp",
|
|
88
|
-
"gif": "image/gif",
|
|
89
|
-
"zip": "application/zip",
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def validate_artifact_id(raw: Optional[str]) -> str:
|
|
94
|
-
if raw is None or str(raw).strip() == "":
|
|
95
|
-
return f"art_{secrets.token_hex(6)}"
|
|
96
|
-
aid = str(raw).strip()
|
|
97
|
-
if not _SAFE_ID_RE.match(aid) or aid in (".", ".."):
|
|
98
|
-
raise HTTPException(400, "invalid artifact_id: only [A-Za-z0-9._-] up to 96 chars allowed")
|
|
99
|
-
return aid
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def sanitize_filename(raw: Optional[str], title: str = "", artifact_type: str = "") -> str:
|
|
103
|
-
candidate = str(raw or "").strip().replace("\\", "/")
|
|
104
|
-
candidate = os.path.basename(candidate) if candidate else ""
|
|
105
|
-
candidate = re.sub(r"[\x00-\x1f\x7f\"<>|*?:/\\]+", "_", candidate).strip(" .")
|
|
106
|
-
if candidate:
|
|
107
|
-
return candidate[:180]
|
|
108
|
-
base = re.sub(r"[\x00-\x1f\x7f\"<>|*?:/\\]+", "_", str(title or "").strip()).strip(" .")
|
|
109
|
-
base = re.sub(r"\s+", "_", base)[:120] or "artifact"
|
|
110
|
-
ext = _EXT_BY_TYPE.get(str(artifact_type or "").strip().lower(), "")
|
|
111
|
-
if ext and not base.lower().endswith(f".{ext}"):
|
|
112
|
-
return f"{base}.{ext}"
|
|
113
|
-
return base
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def guess_mime_type(filename: str, artifact_type: str = "", explicit: Optional[str] = None) -> str:
|
|
117
|
-
if explicit and str(explicit).strip():
|
|
118
|
-
clean = re.sub(r"[\r\n]+", "", str(explicit).strip())
|
|
119
|
-
if clean:
|
|
120
|
-
return clean
|
|
121
|
-
t_key = str(artifact_type or "").strip().lower()
|
|
122
|
-
if t_key in _MIME_BY_TYPE:
|
|
123
|
-
return _MIME_BY_TYPE[t_key]
|
|
124
|
-
guessed, _ = mimetypes.guess_type(filename)
|
|
125
|
-
if guessed:
|
|
126
|
-
if guessed.startswith("text/") or guessed in ("application/json", "application/xml", "application/javascript"):
|
|
127
|
-
return f"{guessed}; charset=utf-8"
|
|
128
|
-
return guessed
|
|
129
|
-
return "application/octet-stream"
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
def build_content_disposition(filename: str, inline: bool = False) -> str:
|
|
133
|
-
safe = sanitize_filename(filename)
|
|
134
|
-
ascii_fallback = re.sub(r"[^\x20-\x7e]+", "_", safe).replace('"', "'").strip(" .")
|
|
135
|
-
if not ascii_fallback:
|
|
136
|
-
_, ext = os.path.splitext(safe)
|
|
137
|
-
ascii_fallback = f"artifact{ext if re.match(r'^\\.[A-Za-z0-9]{1,12}$', ext) else ''}"
|
|
138
|
-
disp = "inline" if inline else "attachment"
|
|
139
|
-
encoded = quote(safe, safe="")
|
|
140
|
-
return f'{disp}; filename="{ascii_fallback}"; filename*=UTF-8\'\'{encoded}'
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
def decode_content_bytes(content: str, encoding: str = "utf-8") -> bytes:
|
|
144
|
-
enc = str(encoding or "utf-8").strip().lower()
|
|
145
|
-
if enc in ("base64", "b64"):
|
|
146
|
-
try:
|
|
147
|
-
raw = base64.b64decode(content.encode("ascii"), validate=True)
|
|
148
|
-
except Exception as exc: # noqa: BLE001
|
|
149
|
-
raise HTTPException(400, f"invalid base64 content: {exc}") from exc
|
|
150
|
-
elif enc in ("utf-8", "utf8", "text", "plain", ""):
|
|
151
|
-
raw = content.encode("utf-8")
|
|
152
|
-
else:
|
|
153
|
-
raise HTTPException(400, f"unsupported encoding: {encoding}")
|
|
154
|
-
if len(raw) > ARTIFACT_MAX_BYTES:
|
|
155
|
-
raise HTTPException(413, f"artifact exceeds max size ({ARTIFACT_MAX_BYTES} bytes)")
|
|
156
|
-
return raw
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
def _atomic_write_bytes(dest: str, data: bytes) -> None:
|
|
160
|
-
directory = os.path.dirname(dest)
|
|
161
|
-
os.makedirs(directory, exist_ok=True)
|
|
162
|
-
fd, tmp = tempfile.mkstemp(dir=directory, prefix=".art-")
|
|
163
|
-
try:
|
|
164
|
-
with os.fdopen(fd, "wb") as fh:
|
|
165
|
-
fh.write(data)
|
|
166
|
-
fh.flush()
|
|
167
|
-
os.fsync(fh.fileno())
|
|
168
|
-
os.replace(tmp, dest)
|
|
169
|
-
except BaseException:
|
|
170
|
-
with contextlib.suppress(OSError):
|
|
171
|
-
os.unlink(tmp)
|
|
172
|
-
raise
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
def _atomic_write_json(dest: str, payload: dict) -> None:
|
|
176
|
-
raw = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
|
177
|
-
_atomic_write_bytes(dest, raw)
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
def _preview_text(data: bytes, mime_type: str) -> str:
|
|
181
|
-
base_mime = mime_type.split(";")[0].strip().lower()
|
|
182
|
-
is_text = (
|
|
183
|
-
base_mime.startswith("text/")
|
|
184
|
-
or base_mime in (
|
|
185
|
-
"application/json",
|
|
186
|
-
"application/xml",
|
|
187
|
-
"application/javascript",
|
|
188
|
-
"application/yaml",
|
|
189
|
-
"image/svg+xml",
|
|
190
|
-
)
|
|
191
|
-
)
|
|
192
|
-
if not is_text:
|
|
193
|
-
return ""
|
|
194
|
-
try:
|
|
195
|
-
return data[:2048].decode("utf-8", errors="replace").strip()[:400]
|
|
196
|
-
except Exception: # noqa: BLE001
|
|
197
|
-
return ""
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
def enrich_artifact_record(meta: dict) -> dict:
|
|
201
|
-
aid = meta["artifact_id"]
|
|
202
|
-
bid = meta["bot_id"]
|
|
203
|
-
out = dict(meta)
|
|
204
|
-
out["download_url"] = f"/api/artifacts/{quote(aid, safe='')}/download"
|
|
205
|
-
out["bot_download_url"] = f"/api/screens/{quote(bid, safe='')}/artifacts/{quote(aid, safe='')}/download"
|
|
206
|
-
out["agent_download_url"] = f"/api/agent/{quote(bid, safe='')}/artifacts/{quote(aid, safe='')}/download"
|
|
207
|
-
return out
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
class ArtifactStore:
|
|
211
|
-
"""管理所有已注册 Bot 目录下的 Agent 回复产物。"""
|
|
212
|
-
|
|
213
|
-
def __init__(self, artifacts_dir: str, bot_id: str) -> None:
|
|
214
|
-
self.dir = artifacts_dir
|
|
215
|
-
self.bot_id = bot_id
|
|
216
|
-
|
|
217
|
-
def _bin_path(self, artifact_id: str) -> str:
|
|
218
|
-
return os.path.join(self.dir, f"{artifact_id}.bin")
|
|
219
|
-
|
|
220
|
-
def _meta_path(self, artifact_id: str) -> str:
|
|
221
|
-
return os.path.join(self.dir, f"{artifact_id}.meta.json")
|
|
222
|
-
|
|
223
|
-
def save_bytes(
|
|
224
|
-
self,
|
|
225
|
-
data: bytes,
|
|
226
|
-
*,
|
|
227
|
-
artifact_id: Optional[str] = None,
|
|
228
|
-
title: str = "",
|
|
229
|
-
filename: Optional[str] = None,
|
|
230
|
-
kind: str = "artifact",
|
|
231
|
-
artifact_type: str = "",
|
|
232
|
-
mime_type: Optional[str] = None,
|
|
233
|
-
room_id: str = "",
|
|
234
|
-
room_name: str = "",
|
|
235
|
-
message_id: str = "",
|
|
236
|
-
source_path: str = "",
|
|
237
|
-
metadata: Optional[Dict[str, Any]] = None,
|
|
238
|
-
) -> dict:
|
|
239
|
-
if len(data) > ARTIFACT_MAX_BYTES:
|
|
240
|
-
raise HTTPException(413, f"artifact exceeds max size ({ARTIFACT_MAX_BYTES} bytes)")
|
|
241
|
-
aid = validate_artifact_id(artifact_id)
|
|
242
|
-
norm_kind = str(kind or "artifact").strip().lower()
|
|
243
|
-
if norm_kind not in _SAFE_KIND_SET:
|
|
244
|
-
norm_kind = "artifact"
|
|
245
|
-
norm_type = str(artifact_type or "").strip().lower() or ("file" if norm_kind == "deliverable" else "text")
|
|
246
|
-
resolved_name = sanitize_filename(filename, title=title, artifact_type=norm_type)
|
|
247
|
-
resolved_title = str(title or "").strip() or resolved_name
|
|
248
|
-
resolved_mime = guess_mime_type(resolved_name, artifact_type=norm_type, explicit=mime_type)
|
|
249
|
-
sha256 = hashlib.sha256(data).hexdigest()
|
|
250
|
-
now = time.time()
|
|
251
|
-
|
|
252
|
-
existing = self.get_meta(aid)
|
|
253
|
-
created_at = existing.get("created_at", now) if existing else now
|
|
254
|
-
|
|
255
|
-
meta = {
|
|
256
|
-
"artifact_id": aid,
|
|
257
|
-
"bot_id": self.bot_id,
|
|
258
|
-
"title": resolved_title[:240],
|
|
259
|
-
"filename": resolved_name,
|
|
260
|
-
"kind": norm_kind,
|
|
261
|
-
"artifact_type": norm_type[:64],
|
|
262
|
-
"mime_type": resolved_mime,
|
|
263
|
-
"size": len(data),
|
|
264
|
-
"sha256": sha256,
|
|
265
|
-
"room_id": str(room_id or "").strip()[:128],
|
|
266
|
-
"room_name": str(room_name or "").strip()[:160],
|
|
267
|
-
"message_id": str(message_id or "").strip()[:128],
|
|
268
|
-
"source_path": str(source_path or "").strip()[:512],
|
|
269
|
-
"preview": _preview_text(data, resolved_mime),
|
|
270
|
-
"metadata": metadata if isinstance(metadata, dict) else {},
|
|
271
|
-
"created_at": created_at,
|
|
272
|
-
"updated_at": now,
|
|
273
|
-
}
|
|
274
|
-
os.makedirs(self.dir, exist_ok=True)
|
|
275
|
-
_atomic_write_bytes(self._bin_path(aid), data)
|
|
276
|
-
_atomic_write_json(self._meta_path(aid), meta)
|
|
277
|
-
return enrich_artifact_record(meta)
|
|
278
|
-
|
|
279
|
-
def get_meta(self, artifact_id: str) -> Optional[dict]:
|
|
280
|
-
aid = validate_artifact_id(artifact_id)
|
|
281
|
-
mpath = self._meta_path(aid)
|
|
282
|
-
bpath = self._bin_path(aid)
|
|
283
|
-
if not (os.path.isfile(mpath) and os.path.isfile(bpath)):
|
|
284
|
-
return None
|
|
285
|
-
try:
|
|
286
|
-
with open(mpath, encoding="utf-8") as fh:
|
|
287
|
-
raw = json.load(fh)
|
|
288
|
-
if not isinstance(raw, dict):
|
|
289
|
-
return None
|
|
290
|
-
raw.setdefault("artifact_id", aid)
|
|
291
|
-
raw.setdefault("bot_id", self.bot_id)
|
|
292
|
-
return enrich_artifact_record(raw)
|
|
293
|
-
except (OSError, json.JSONDecodeError):
|
|
294
|
-
return None
|
|
295
|
-
|
|
296
|
-
def resolve_file(self, artifact_id: str) -> Optional[Tuple[str, dict]]:
|
|
297
|
-
meta = self.get_meta(artifact_id)
|
|
298
|
-
if meta is None:
|
|
299
|
-
return None
|
|
300
|
-
bpath = self._bin_path(meta["artifact_id"])
|
|
301
|
-
if not os.path.isfile(bpath):
|
|
302
|
-
return None
|
|
303
|
-
return bpath, meta
|
|
304
|
-
|
|
305
|
-
def list_items(
|
|
306
|
-
self,
|
|
307
|
-
*,
|
|
308
|
-
room_id: Optional[str] = None,
|
|
309
|
-
kind: Optional[str] = None,
|
|
310
|
-
limit: int = 100,
|
|
311
|
-
) -> List[dict]:
|
|
312
|
-
if not os.path.isdir(self.dir):
|
|
313
|
-
return []
|
|
314
|
-
out: List[dict] = []
|
|
315
|
-
try:
|
|
316
|
-
names = os.listdir(self.dir)
|
|
317
|
-
except OSError:
|
|
318
|
-
return []
|
|
319
|
-
for name in names:
|
|
320
|
-
if not name.endswith(".meta.json"):
|
|
321
|
-
continue
|
|
322
|
-
aid = name[: -len(".meta.json")]
|
|
323
|
-
if not _SAFE_ID_RE.match(aid):
|
|
324
|
-
continue
|
|
325
|
-
meta = self.get_meta(aid)
|
|
326
|
-
if meta is None:
|
|
327
|
-
continue
|
|
328
|
-
if room_id and meta.get("room_id") != room_id:
|
|
329
|
-
continue
|
|
330
|
-
if kind and meta.get("kind") != kind:
|
|
331
|
-
continue
|
|
332
|
-
out.append(meta)
|
|
333
|
-
out.sort(key=lambda item: float(item.get("updated_at") or 0.0), reverse=True)
|
|
334
|
-
return out[: max(1, min(500, int(limit or 100)))]
|
|
335
|
-
|
|
336
|
-
def delete(self, artifact_id: str) -> bool:
|
|
337
|
-
aid = validate_artifact_id(artifact_id)
|
|
338
|
-
existed = False
|
|
339
|
-
for path in (self._bin_path(aid), self._meta_path(aid)):
|
|
340
|
-
if os.path.exists(path):
|
|
341
|
-
with contextlib.suppress(OSError):
|
|
342
|
-
os.unlink(path)
|
|
343
|
-
existed = True
|
|
344
|
-
return existed
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
def build_zip_bundle(entries: Iterable[Tuple[str, dict]]) -> Tuple[bytes, int, List[dict]]:
|
|
348
|
-
"""把多个产物打包成 ZIP 字节流(自动去重文件名,并校验打包上限)。"""
|
|
349
|
-
buf = io.BytesIO()
|
|
350
|
-
total_raw = 0
|
|
351
|
-
seen_names: Dict[str, int] = {}
|
|
352
|
-
manifest: List[dict] = []
|
|
353
|
-
with zipfile.ZipFile(buf, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
|
|
354
|
-
for bpath, meta in entries:
|
|
355
|
-
if not os.path.isfile(bpath):
|
|
356
|
-
continue
|
|
357
|
-
size = os.path.getsize(bpath)
|
|
358
|
-
total_raw += size
|
|
359
|
-
if total_raw > ARTIFACT_BUNDLE_MAX_BYTES:
|
|
360
|
-
raise HTTPException(
|
|
361
|
-
413,
|
|
362
|
-
f"bundle exceeds max uncompressed size ({ARTIFACT_BUNDLE_MAX_BYTES} bytes)",
|
|
363
|
-
)
|
|
364
|
-
base_name = sanitize_filename(meta.get("filename"), title=meta.get("title", ""), artifact_type=meta.get("artifact_type", ""))
|
|
365
|
-
arcname = base_name
|
|
366
|
-
count = seen_names.get(base_name.lower(), 0)
|
|
367
|
-
if count > 0:
|
|
368
|
-
stem, ext = os.path.splitext(base_name)
|
|
369
|
-
arcname = f"{stem}_{count + 1}{ext}"
|
|
370
|
-
seen_names[base_name.lower()] = count + 1
|
|
371
|
-
zf.write(bpath, arcname=arcname)
|
|
372
|
-
manifest.append({
|
|
373
|
-
"artifact_id": meta.get("artifact_id"),
|
|
374
|
-
"bot_id": meta.get("bot_id"),
|
|
375
|
-
"filename": arcname,
|
|
376
|
-
"title": meta.get("title"),
|
|
377
|
-
"kind": meta.get("kind"),
|
|
378
|
-
"artifact_type": meta.get("artifact_type"),
|
|
379
|
-
"mime_type": meta.get("mime_type"),
|
|
380
|
-
"size": size,
|
|
381
|
-
"sha256": meta.get("sha256"),
|
|
382
|
-
})
|
|
383
|
-
if manifest:
|
|
384
|
-
zf.writestr(
|
|
385
|
-
"manifest.json",
|
|
386
|
-
json.dumps({"count": len(manifest), "artifacts": manifest}, ensure_ascii=False, indent=2),
|
|
387
|
-
)
|
|
388
|
-
return buf.getvalue(), len(manifest), manifest
|
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
"""操作审计:actions.jsonl + 每动作缩略图(方案四.3 Kill Switch 配套)。"""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
import json
|
|
5
|
-
import os
|
|
6
|
-
import time
|
|
7
|
-
from typing import Optional
|
|
8
|
-
|
|
9
|
-
from .config import AUDIT_ENABLED, BotPaths
|
|
10
|
-
|
|
11
|
-
MAX_THUMBS = 400
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class Auditor:
|
|
15
|
-
def __init__(self, bot_id: str, paths: BotPaths) -> None:
|
|
16
|
-
self.bot_id = bot_id
|
|
17
|
-
self.paths = paths
|
|
18
|
-
for d in (self.paths.audit, os.path.join(self.paths.audit, "thumbs")):
|
|
19
|
-
try:
|
|
20
|
-
os.makedirs(d, exist_ok=True)
|
|
21
|
-
except OSError:
|
|
22
|
-
# 目录由 Worker.prepare() 负责创建;构造期不因权限问题失败
|
|
23
|
-
pass
|
|
24
|
-
|
|
25
|
-
@property
|
|
26
|
-
def thumb_dir(self) -> str:
|
|
27
|
-
return os.path.join(self.paths.audit, "thumbs")
|
|
28
|
-
|
|
29
|
-
def record(
|
|
30
|
-
self,
|
|
31
|
-
action: str,
|
|
32
|
-
payload: dict,
|
|
33
|
-
thumb: Optional[bytes] = None,
|
|
34
|
-
state: Optional[str] = None,
|
|
35
|
-
) -> dict:
|
|
36
|
-
ts = time.time()
|
|
37
|
-
entry = {
|
|
38
|
-
"ts": ts,
|
|
39
|
-
"iso": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(ts)),
|
|
40
|
-
"bot_id": self.bot_id,
|
|
41
|
-
"action": action,
|
|
42
|
-
"state": state,
|
|
43
|
-
**payload,
|
|
44
|
-
}
|
|
45
|
-
if AUDIT_ENABLED and thumb:
|
|
46
|
-
# 缩略图由 driver 以 JPEG 编码,扩展名跟随实际内容
|
|
47
|
-
ext = "jpg" if thumb[:2] == b"\xff\xd8" else "webp"
|
|
48
|
-
name = f"{int(ts * 1000)}_{action}.{ext}"
|
|
49
|
-
path = os.path.join(self.thumb_dir, name)
|
|
50
|
-
try:
|
|
51
|
-
with open(path, "wb") as fh:
|
|
52
|
-
fh.write(thumb)
|
|
53
|
-
entry["thumb"] = os.path.relpath(path, self.paths.audit)
|
|
54
|
-
except OSError as exc: # noqa: BLE001
|
|
55
|
-
entry["thumb_error"] = str(exc)
|
|
56
|
-
try:
|
|
57
|
-
with open(self.paths.actions_log, "a", encoding="utf-8") as fh:
|
|
58
|
-
fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
59
|
-
except OSError as exc: # noqa: BLE001
|
|
60
|
-
entry["log_error"] = str(exc)
|
|
61
|
-
self._prune()
|
|
62
|
-
return entry
|
|
63
|
-
|
|
64
|
-
def _prune(self) -> None:
|
|
65
|
-
try:
|
|
66
|
-
files = sorted(
|
|
67
|
-
(os.path.join(self.thumb_dir, f) for f in os.listdir(self.thumb_dir)),
|
|
68
|
-
key=os.path.getmtime,
|
|
69
|
-
)
|
|
70
|
-
except OSError:
|
|
71
|
-
return
|
|
72
|
-
for path in files[:-MAX_THUMBS] if len(files) > MAX_THUMBS else []:
|
|
73
|
-
try:
|
|
74
|
-
os.unlink(path)
|
|
75
|
-
except OSError:
|
|
76
|
-
pass
|
|
77
|
-
|
|
78
|
-
def tail(self, limit: int = 50) -> list[dict]:
|
|
79
|
-
"""读最近 N 条审计记录(供前端审计页 / 回放)。"""
|
|
80
|
-
try:
|
|
81
|
-
with open(self.paths.actions_log, encoding="utf-8") as fh:
|
|
82
|
-
lines = fh.readlines()[-limit:]
|
|
83
|
-
except OSError:
|
|
84
|
-
return []
|
|
85
|
-
out = []
|
|
86
|
-
for line in lines:
|
|
87
|
-
line = line.strip()
|
|
88
|
-
if not line:
|
|
89
|
-
continue
|
|
90
|
-
try:
|
|
91
|
-
out.append(json.loads(line))
|
|
92
|
-
except json.JSONDecodeError:
|
|
93
|
-
continue
|
|
94
|
-
return out
|