aizz-server 1.0.0__py3-none-any.whl
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.
Potentially problematic release.
This version of aizz-server might be problematic. Click here for more details.
- aizz_server/CHAT_INSTRUCTIONS.example.md +4 -0
- aizz_server/CHAT_MEMORY.example.md +3 -0
- aizz_server/__init__.py +2 -0
- aizz_server/app.py +2184 -0
- aizz_server/auth_middleware.py +73 -0
- aizz_server/background_tasks.py +248 -0
- aizz_server/chat_tools.py +487 -0
- aizz_server/cli.py +105 -0
- aizz_server/codex_bridge.py +386 -0
- aizz_server/codex_proxy.py +836 -0
- aizz_server/config.example.json +34 -0
- aizz_server/device_auth.py +155 -0
- aizz_server/migrate_storage.py +127 -0
- aizz_server/pairing.py +30 -0
- aizz_server/service_logging.py +27 -0
- aizz_server/skills.py +137 -0
- aizz_server/storage_paths.py +28 -0
- aizz_server/task_notifications.py +145 -0
- aizz_server/terminal.py +140 -0
- aizz_server/tool_policy.example.json +11 -0
- aizz_server/tool_policy.py +114 -0
- aizz_server/workspace_git.py +409 -0
- aizz_server/workspace_preview.py +30 -0
- aizz_server/workspaces.example.json +4 -0
- aizz_server/worktrees.py +45 -0
- aizz_server-1.0.0.dist-info/METADATA +546 -0
- aizz_server-1.0.0.dist-info/RECORD +30 -0
- aizz_server-1.0.0.dist-info/WHEEL +5 -0
- aizz_server-1.0.0.dist-info/entry_points.txt +2 -0
- aizz_server-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Bounded tools and command approval requests for ordinary chat."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import base64
|
|
6
|
+
import binascii
|
|
7
|
+
import difflib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import shlex
|
|
11
|
+
import signal
|
|
12
|
+
import stat
|
|
13
|
+
import tempfile
|
|
14
|
+
import uuid
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Callable
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
from . import tool_policy, skills
|
|
21
|
+
|
|
22
|
+
MAX_RESULT = 16_000
|
|
23
|
+
PENDING: dict[str, dict[str, Any]] = {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _tool(name: str, description: str, properties: dict, required: list[str]) -> dict:
|
|
27
|
+
return {"type": "function", "function": {"name": name, "description": description,
|
|
28
|
+
"parameters": {"type": "object", "properties": properties, "required": required,
|
|
29
|
+
"additionalProperties": False}}}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
TOOLS = [
|
|
33
|
+
_tool("list_files", "列出工作目录或已发现的 skill 目录内文件", {"path": {"type": "string"}}, ["path"]),
|
|
34
|
+
_tool("read_file", "读取工作目录或 skill 内的 UTF-8 文件;offset、limit 按字符分页", {
|
|
35
|
+
"path": {"type": "string"}, "offset": {"type": "integer", "minimum": 0},
|
|
36
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 16000}}, ["path"]),
|
|
37
|
+
_tool("search_files", "在工作目录或 skill 内搜索文件内容", {"query": {"type": "string"},
|
|
38
|
+
"path": {"type": "string"}}, ["query"]),
|
|
39
|
+
_tool("edit_file", "精确替换当前工作目录内已有 UTF-8 文件的文本;先读取文件,old_text 必须非空且只匹配一处;new_text 可为空以删除文本。失败时重新读取并缩小修改范围。", {
|
|
40
|
+
"path": {"type": "string"}, "old_text": {"type": "string", "minLength": 1},
|
|
41
|
+
"new_text": {"type": "string"}}, ["path", "old_text", "new_text"]),
|
|
42
|
+
_tool("run_command", "在工作目录运行单条命令;按本地策略放行、审核或禁止;不支持管道或重定向", {
|
|
43
|
+
"command": {"type": "string"}, "cwd": {"type": "string", "description": "可选工作目录,仅限当前项目或已发现的 skill 目录;支持 ~/"}}, ["command"]),
|
|
44
|
+
_tool("web_search", "联网搜索并返回带来源链接的结果", {
|
|
45
|
+
"query": {"type": "string"}}, ["query"]),
|
|
46
|
+
_tool("imagegen", "使用配置的默认图片服务生成或编辑一张图片,并作为图片附件发送给用户", {
|
|
47
|
+
"prompt": {"type": "string", "description": "详细描述要生成的图片或修改要求"},
|
|
48
|
+
"use_reference_images": {"type": "boolean", "description":
|
|
49
|
+
"基于本轮上传或最近一组图片编辑时设为 true,独立创作新图时设为 false;省略时仅自动使用本轮上传图片"}}, ["prompt"]),
|
|
50
|
+
_tool("imagegen_gpt", "明确使用 GPT 图片服务生成或编辑图片,并作为附件发送给用户", {
|
|
51
|
+
"prompt": {"type": "string"}, "use_reference_images": {"type": "boolean"}}, ["prompt"]),
|
|
52
|
+
_tool("imagegen_gemini", "明确使用 Gemini 图片服务生成或编辑图片,并作为附件发送给用户", {
|
|
53
|
+
"prompt": {"type": "string"}, "use_reference_images": {"type": "boolean"}}, ["prompt"]),
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
MAX_IMAGE_BYTES = 8 * 1024 * 1024
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def images_url(base_url: str, operation: str = "generations") -> str:
|
|
60
|
+
cleaned = base_url.strip().rstrip("/")
|
|
61
|
+
for suffix in ("/images/generations", "/images/edits"):
|
|
62
|
+
if cleaned.endswith(suffix):
|
|
63
|
+
return cleaned[:-len(suffix)] + f"/images/{operation}"
|
|
64
|
+
if cleaned.endswith("/v1"):
|
|
65
|
+
return f"{cleaned}/images/{operation}"
|
|
66
|
+
return f"{cleaned}/v1/images/{operation}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def image_mime(data: bytes) -> str:
|
|
70
|
+
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
71
|
+
return "image/png"
|
|
72
|
+
if data.startswith(b"\xff\xd8\xff"):
|
|
73
|
+
return "image/jpeg"
|
|
74
|
+
if data.startswith((b"GIF87a", b"GIF89a")):
|
|
75
|
+
return "image/gif"
|
|
76
|
+
if data.startswith(b"RIFF") and data[8:12] == b"WEBP":
|
|
77
|
+
return "image/webp"
|
|
78
|
+
raise ValueError("图片接口返回了不支持的格式")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def image_backends(settings: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
82
|
+
image_settings = settings.get("image_generation") or {}
|
|
83
|
+
result = {name: image_settings[name] for name in ("gpt", "gemini")
|
|
84
|
+
if isinstance(image_settings.get(name), dict)}
|
|
85
|
+
if "gpt" not in result and image_settings.get("base_url"):
|
|
86
|
+
result["gpt"] = image_settings # Existing single-backend configuration.
|
|
87
|
+
return result
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def default_image_backend(settings: dict[str, Any]) -> str:
|
|
91
|
+
return (settings.get("image_generation") or {}).get("default", "gpt")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def available_image_tools(settings: dict[str, Any]) -> set[str]:
|
|
95
|
+
backends = image_backends(settings)
|
|
96
|
+
result = {f"imagegen_{name}" for name in backends}
|
|
97
|
+
if default_image_backend(settings) in backends:
|
|
98
|
+
result.add("imagegen")
|
|
99
|
+
return result
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _decode_image(encoded: str) -> bytes:
|
|
103
|
+
if len(encoded) > (MAX_IMAGE_BYTES + 2) // 3 * 4:
|
|
104
|
+
raise ValueError("生成图片超过 8 MB")
|
|
105
|
+
try:
|
|
106
|
+
return base64.b64decode(encoded, validate=True)
|
|
107
|
+
except (binascii.Error, ValueError) as exc:
|
|
108
|
+
raise ValueError("图片接口返回的 base64 无效") from exc
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def generate_image(args: dict[str, Any], settings: dict[str, Any], *,
|
|
112
|
+
images: list[tuple[str, bytes]] | None = None,
|
|
113
|
+
backend: str | None = None) -> tuple[str, bytes]:
|
|
114
|
+
tool_policy.require_tool("imagegen" if backend is None else f"imagegen_{backend}")
|
|
115
|
+
prompt = args.get("prompt")
|
|
116
|
+
if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 4000:
|
|
117
|
+
raise ValueError("图片提示词不能为空且不能超过 4000 字符")
|
|
118
|
+
backend = backend or default_image_backend(settings)
|
|
119
|
+
image_settings = image_backends(settings).get(backend)
|
|
120
|
+
if image_settings is None:
|
|
121
|
+
raise ValueError(f"请配置 image_generation.{backend} 图片服务")
|
|
122
|
+
if backend == "gemini":
|
|
123
|
+
return await _generate_gemini_image(prompt.strip(), image_settings, settings, images or [])
|
|
124
|
+
if backend != "gpt":
|
|
125
|
+
raise ValueError(f"不支持的图片服务:{backend}")
|
|
126
|
+
base_url = image_settings.get("base_url", "")
|
|
127
|
+
model = image_settings.get("model", "")
|
|
128
|
+
key_env = image_settings.get("api_key_env", "")
|
|
129
|
+
key = os.getenv(key_env, "") if key_env else image_settings.get("api_key", "")
|
|
130
|
+
if not all(isinstance(value, str) and value.strip() for value in (base_url, model, key)):
|
|
131
|
+
raise ValueError("请配置 image_generation 的 base_url、model 和 API Key")
|
|
132
|
+
size = image_settings.get("size", "1024x1024")
|
|
133
|
+
timeout = image_settings.get("timeout_seconds", 300)
|
|
134
|
+
if not isinstance(timeout, (int, float)) or not 0 < timeout <= 600:
|
|
135
|
+
raise ValueError("image_generation.timeout_seconds 必须在 0 到 600 秒之间")
|
|
136
|
+
files = []
|
|
137
|
+
for index, (mime, image) in enumerate(images or []):
|
|
138
|
+
extension = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}.get(mime)
|
|
139
|
+
if not extension:
|
|
140
|
+
raise ValueError("参考图片仅支持 PNG、JPEG 和 WebP,请转换格式后重试")
|
|
141
|
+
if not image or len(image) > MAX_IMAGE_BYTES:
|
|
142
|
+
raise ValueError("参考图片大小需在 8 MB 以内")
|
|
143
|
+
files.append(("image[]", (f"reference-{index}.{extension}", image, mime)))
|
|
144
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
145
|
+
payload = {"model": model, "prompt": prompt.strip(), "n": 1,
|
|
146
|
+
"size": size, "output_format": "png"}
|
|
147
|
+
headers = {"Authorization": f"Bearer {key}"}
|
|
148
|
+
if files:
|
|
149
|
+
response = await client.post(images_url(base_url, "edits"), headers=headers,
|
|
150
|
+
data={name: str(value) for name, value in payload.items()}, files=files)
|
|
151
|
+
else:
|
|
152
|
+
response = await client.post(images_url(base_url), headers=headers, json=payload)
|
|
153
|
+
if response.is_error:
|
|
154
|
+
if files and response.status_code in (404, 405, 501):
|
|
155
|
+
raise RuntimeError(f"图片编辑接口 HTTP {response.status_code}:请确认反代支持 /v1/images/edits 和参考图片上传")
|
|
156
|
+
raise RuntimeError(f"图片生成接口 HTTP {response.status_code}")
|
|
157
|
+
body = response.json()
|
|
158
|
+
data = body.get("data") if isinstance(body, dict) else None
|
|
159
|
+
if not isinstance(data, list) or not data or not isinstance(data[0], dict):
|
|
160
|
+
raise ValueError("图片接口未返回图片 data")
|
|
161
|
+
first = data[0]
|
|
162
|
+
if isinstance(first.get("b64_json"), str) and first["b64_json"].strip():
|
|
163
|
+
encoded = first["b64_json"].strip()
|
|
164
|
+
image = _decode_image(encoded)
|
|
165
|
+
elif isinstance(first.get("url"), str) and first["url"].startswith(("https://", "http://")):
|
|
166
|
+
# 下载图片时不转发 API Key。
|
|
167
|
+
download = await client.get(first["url"], follow_redirects=True)
|
|
168
|
+
download.raise_for_status()
|
|
169
|
+
image = download.content
|
|
170
|
+
else:
|
|
171
|
+
raise ValueError("图片接口未返回 b64_json 或图片 URL")
|
|
172
|
+
if not image or len(image) > MAX_IMAGE_BYTES:
|
|
173
|
+
raise ValueError("生成图片大小需在 8 MB 以内")
|
|
174
|
+
return image_mime(image), image
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _chat_completions_url(base_url: str) -> str:
|
|
178
|
+
url = base_url.strip().rstrip("/")
|
|
179
|
+
if url.endswith("/chat/completions"):
|
|
180
|
+
return url
|
|
181
|
+
if url.endswith("/v1"):
|
|
182
|
+
return url + "/chat/completions"
|
|
183
|
+
return url + "/v1/chat/completions"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
async def _generate_gemini_image(prompt: str, settings: dict[str, Any],
|
|
187
|
+
all_settings: dict[str, Any],
|
|
188
|
+
images: list[tuple[str, bytes]]) -> tuple[str, bytes]:
|
|
189
|
+
provider_id = settings.get("provider")
|
|
190
|
+
connection = settings
|
|
191
|
+
if provider_id is not None:
|
|
192
|
+
if not isinstance(provider_id, str) or not provider_id.strip():
|
|
193
|
+
raise ValueError("image_generation.gemini.provider 必须是 Provider 名称")
|
|
194
|
+
connection = (all_settings.get("providers") or {}).get(provider_id)
|
|
195
|
+
if not isinstance(connection, dict) or connection.get("type", "openai") != "openai":
|
|
196
|
+
raise ValueError(f"Gemini 图片 Provider {provider_id} 不存在或不是 OpenAI 兼容服务")
|
|
197
|
+
model = settings.get("model", "")
|
|
198
|
+
key_env = connection.get("api_key_env", "")
|
|
199
|
+
key = os.getenv(key_env, "") if key_env else connection.get("api_key", "")
|
|
200
|
+
base_url = connection.get("base_url", "")
|
|
201
|
+
timeout = settings.get("timeout_seconds", 300)
|
|
202
|
+
if not all(isinstance(value, str) and value.strip() for value in (model, key, base_url)):
|
|
203
|
+
raise ValueError("请配置 image_generation.gemini 的 model、Provider 地址和 API Key")
|
|
204
|
+
if not isinstance(timeout, (int, float)) or not 0 < timeout <= 600:
|
|
205
|
+
raise ValueError("image_generation.gemini.timeout_seconds 必须在 0 到 600 秒之间")
|
|
206
|
+
parts = [{"type": "text", "text": prompt}]
|
|
207
|
+
for mime, image in images:
|
|
208
|
+
if mime not in ("image/png", "image/jpeg", "image/webp"):
|
|
209
|
+
raise ValueError("参考图片仅支持 PNG、JPEG 和 WebP,请转换格式后重试")
|
|
210
|
+
if not image or len(image) > MAX_IMAGE_BYTES:
|
|
211
|
+
raise ValueError("参考图片大小需在 8 MB 以内")
|
|
212
|
+
parts.append({"type": "image_url", "image_url": {
|
|
213
|
+
"url": f"data:{mime};base64,{base64.b64encode(image).decode()}"}})
|
|
214
|
+
payload = {"model": model, "messages": [{"role": "user", "content": parts if images else prompt}]}
|
|
215
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
216
|
+
response = await client.post(_chat_completions_url(base_url),
|
|
217
|
+
headers={"Authorization": f"Bearer {key}"}, json=payload)
|
|
218
|
+
if response.is_error:
|
|
219
|
+
raise RuntimeError(f"Gemini 图片接口 HTTP {response.status_code}")
|
|
220
|
+
body = response.json()
|
|
221
|
+
choices = body.get("choices") if isinstance(body, dict) else None
|
|
222
|
+
message = choices[0].get("message") if isinstance(choices, list) and choices and isinstance(choices[0], dict) else None
|
|
223
|
+
image_items = message.get("images") if isinstance(message, dict) else None
|
|
224
|
+
if not isinstance(image_items, list) or not image_items:
|
|
225
|
+
raise ValueError("Gemini 图片接口未返回 choices[0].message.images")
|
|
226
|
+
first = image_items[0]
|
|
227
|
+
image_url = first.get("image_url") if isinstance(first, dict) else None
|
|
228
|
+
data_url = image_url.get("url") if isinstance(image_url, dict) else None
|
|
229
|
+
if not isinstance(data_url, str) or not data_url.startswith("data:image/") or ";base64," not in data_url:
|
|
230
|
+
raise ValueError("Gemini 图片接口未返回 base64 图片 data URL")
|
|
231
|
+
image = _decode_image(data_url.split(";base64,", 1)[1])
|
|
232
|
+
if not image or len(image) > MAX_IMAGE_BYTES:
|
|
233
|
+
raise ValueError("生成图片大小需在 8 MB 以内")
|
|
234
|
+
return image_mime(image), image
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def bounded(value: str) -> str:
|
|
238
|
+
return value[:MAX_RESULT] + ("\n[结果已截断]" if len(value) > MAX_RESULT else "")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def workspace_path(root: Path, value: str) -> Path:
|
|
242
|
+
if not isinstance(value, str) or len(value) > 2000:
|
|
243
|
+
raise ValueError("路径无效")
|
|
244
|
+
path = (root / (value or ".")).resolve()
|
|
245
|
+
if not path.is_relative_to(root.resolve()):
|
|
246
|
+
raise ValueError("路径超出工作目录")
|
|
247
|
+
return path
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def command_directory(root: Path, value: str | None = None) -> Path:
|
|
251
|
+
path = root.resolve() if value is None else skills.resolve_path(root, value)
|
|
252
|
+
if not path.is_dir():
|
|
253
|
+
raise ValueError("命令工作目录不存在")
|
|
254
|
+
return path
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def safe_read_command(command: str, root: Path) -> bool:
|
|
258
|
+
"""Only a small, fully parsed subset runs without review."""
|
|
259
|
+
try:
|
|
260
|
+
parts = shlex.split(command)
|
|
261
|
+
except ValueError:
|
|
262
|
+
return False
|
|
263
|
+
if parts == ["pwd"]:
|
|
264
|
+
return True
|
|
265
|
+
if parts and parts[0] == "ls" and len(parts) <= 2:
|
|
266
|
+
if len(parts) == 1:
|
|
267
|
+
return True
|
|
268
|
+
if parts[1].startswith("-"):
|
|
269
|
+
return False
|
|
270
|
+
try:
|
|
271
|
+
workspace_path(root, parts[1])
|
|
272
|
+
return True
|
|
273
|
+
except ValueError:
|
|
274
|
+
return False
|
|
275
|
+
return parts in (["git", "status", "--short"], ["git", "status"])
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def command_decision(command: str, root: Path) -> str:
|
|
279
|
+
return tool_policy.command_decision(command, legacy_safe=safe_read_command(command, root))
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def available_tools(settings: dict[str, Any] | None = None) -> list[dict]:
|
|
283
|
+
allowed = tool_policy.allowed_tools()
|
|
284
|
+
if settings is not None:
|
|
285
|
+
image_names = {"imagegen", "imagegen_gpt", "imagegen_gemini"}
|
|
286
|
+
allowed = (allowed - image_names) | (allowed & available_image_tools(settings))
|
|
287
|
+
return [tool for tool in TOOLS if tool["function"]["name"] in allowed]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def request_approval(session_id: str, command: str, root: Path, *,
|
|
291
|
+
remember: Callable[[str], None] | None = None,
|
|
292
|
+
permanent: bool = True, explicit_ask: bool = False) -> tuple[str, asyncio.Future[str], dict]:
|
|
293
|
+
token = uuid.uuid4().hex
|
|
294
|
+
loop = asyncio.get_running_loop()
|
|
295
|
+
future: asyncio.Future[str] = loop.create_future()
|
|
296
|
+
decisions = ["accept", "decline"]
|
|
297
|
+
if remember is not None and not explicit_ask:
|
|
298
|
+
decisions[1:1] = ["acceptForSession", *(["acceptPermanently"] if permanent else [])]
|
|
299
|
+
PENDING[token] = {"session_id": session_id, "future": future, "decisions": decisions,
|
|
300
|
+
"remember": remember, "expires_at": loop.time() + 1800}
|
|
301
|
+
return token, future, {"token": token, "source": "chat", "decisions": decisions,
|
|
302
|
+
"params": {"command": command, "cwd": str(root),
|
|
303
|
+
**({"policy_note": "策略要求每次审核"} if explicit_ask else {}),
|
|
304
|
+
"warning": "命令以服务端用户身份执行,工作目录不限制 shell 访问其他路径。"},
|
|
305
|
+
"item": {}}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def answer_approval(session_id: str, token: str, decision: str) -> None:
|
|
309
|
+
pending = PENDING.get(token)
|
|
310
|
+
if pending is None or pending["session_id"] != session_id or pending["future"].done():
|
|
311
|
+
raise ValueError("审核请求已失效")
|
|
312
|
+
if pending["expires_at"] <= asyncio.get_running_loop().time():
|
|
313
|
+
raise ValueError("审核请求已过期")
|
|
314
|
+
if decision not in pending["decisions"]:
|
|
315
|
+
raise ValueError("不支持的审核决定")
|
|
316
|
+
if decision in ("acceptForSession", "acceptPermanently"):
|
|
317
|
+
pending["remember"](decision)
|
|
318
|
+
pending["future"].set_result(decision)
|
|
319
|
+
PENDING.pop(token, None)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
async def run_command(command: str, root: Path, *, approved: bool = False) -> str:
|
|
323
|
+
tool_policy.require_tool("run_command")
|
|
324
|
+
decision = command_decision(command, root)
|
|
325
|
+
if decision == "deny":
|
|
326
|
+
raise ValueError("命令被 shell 策略禁止")
|
|
327
|
+
if decision == "ask" and not approved:
|
|
328
|
+
raise ValueError("命令需要用户审核")
|
|
329
|
+
environment = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TERM") if key in os.environ}
|
|
330
|
+
environment["GIT_OPTIONAL_LOCKS"] = "0"
|
|
331
|
+
options = {"cwd": root, "env": environment, "stdin": asyncio.subprocess.DEVNULL,
|
|
332
|
+
"stdout": asyncio.subprocess.PIPE, "stderr": asyncio.subprocess.STDOUT,
|
|
333
|
+
"start_new_session": os.name == "posix"}
|
|
334
|
+
process = await asyncio.create_subprocess_exec(*tool_policy.command_parts(command), **options)
|
|
335
|
+
try:
|
|
336
|
+
async with asyncio.timeout(30):
|
|
337
|
+
chunks = []
|
|
338
|
+
size = 0
|
|
339
|
+
while data := await process.stdout.read(4096):
|
|
340
|
+
chunks.append(data)
|
|
341
|
+
size += len(data)
|
|
342
|
+
if size > MAX_RESULT:
|
|
343
|
+
raise ValueError("命令输出超过限制")
|
|
344
|
+
await process.wait()
|
|
345
|
+
return bounded(b"".join(chunks).decode(errors="replace") + f"\n[退出码 {process.returncode}]")
|
|
346
|
+
finally:
|
|
347
|
+
if process.returncode is None:
|
|
348
|
+
if os.name == "posix":
|
|
349
|
+
try:
|
|
350
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
351
|
+
except ProcessLookupError:
|
|
352
|
+
pass
|
|
353
|
+
else:
|
|
354
|
+
process.kill()
|
|
355
|
+
await process.wait()
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def edit_file(args: dict[str, Any], root: Path) -> str:
|
|
359
|
+
value, old, new = args.get("path"), args.get("old_text"), args.get("new_text")
|
|
360
|
+
if not isinstance(value, str) or not value or len(value) > 2000 or "\0" in value:
|
|
361
|
+
raise ValueError("路径无效")
|
|
362
|
+
if not isinstance(old, str) or not old or not isinstance(new, str):
|
|
363
|
+
raise ValueError("old_text 必须为非空字符串,new_text 必须为字符串")
|
|
364
|
+
if "\0" in old or "\0" in new:
|
|
365
|
+
raise ValueError("编辑文本不能包含 NUL")
|
|
366
|
+
candidate = root / Path(value).expanduser()
|
|
367
|
+
path = candidate.resolve()
|
|
368
|
+
if not path.is_relative_to(root.resolve()):
|
|
369
|
+
raise ValueError("路径超出工作目录")
|
|
370
|
+
before = path.stat()
|
|
371
|
+
if not stat.S_ISREG(before.st_mode):
|
|
372
|
+
raise ValueError("只能编辑已有的普通文件")
|
|
373
|
+
original = path.read_bytes()
|
|
374
|
+
text = original.decode("utf-8")
|
|
375
|
+
if "\0" in text:
|
|
376
|
+
raise ValueError("不能编辑二进制文件")
|
|
377
|
+
first = text.find(old)
|
|
378
|
+
if first < 0 or text.find(old, first + 1) >= 0:
|
|
379
|
+
raise ValueError("old_text 未匹配或匹配多处,必须只匹配一处;请重新读取文件并提供唯一上下文")
|
|
380
|
+
updated = text.replace(old, new, 1)
|
|
381
|
+
temporary = None
|
|
382
|
+
try:
|
|
383
|
+
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=".aizz-edit-", delete=False) as file:
|
|
384
|
+
temporary = Path(file.name)
|
|
385
|
+
file.write(updated.encode("utf-8"))
|
|
386
|
+
file.flush()
|
|
387
|
+
os.fsync(file.fileno())
|
|
388
|
+
os.fchmod(file.fileno(), stat.S_IMODE(before.st_mode))
|
|
389
|
+
# Refuse stale edits, including a renamed file or a retargeted symlink.
|
|
390
|
+
current = path.stat()
|
|
391
|
+
def identity(info):
|
|
392
|
+
return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns,
|
|
393
|
+
info.st_ctime_ns, info.st_mode, info.st_uid, info.st_gid)
|
|
394
|
+
if (candidate.resolve() != path or identity(current) != identity(before) or path.read_bytes() != original):
|
|
395
|
+
raise ValueError("文件在编辑期间已变化,请重新读取后重试")
|
|
396
|
+
tool_policy.require_tool("edit_file")
|
|
397
|
+
os.replace(temporary, path)
|
|
398
|
+
finally:
|
|
399
|
+
if temporary is not None:
|
|
400
|
+
temporary.unlink(missing_ok=True)
|
|
401
|
+
lines = difflib.unified_diff(text.splitlines(keepends=True), updated.splitlines(keepends=True),
|
|
402
|
+
fromfile=str(path), tofile=str(path))
|
|
403
|
+
diff = "".join(line if line.endswith("\n") else line + "\n\\n"
|
|
404
|
+
for line in lines)
|
|
405
|
+
return bounded(f"已修改:{path}\n{diff}")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
async def execute(name: str, args: dict[str, Any], root: Path, *, approved: bool = False) -> str:
|
|
409
|
+
tool_policy.require_tool(name)
|
|
410
|
+
if name == "edit_file":
|
|
411
|
+
return edit_file(args, root)
|
|
412
|
+
if name == "list_files":
|
|
413
|
+
path = skills.resolve_path(root, args.get("path", "."))
|
|
414
|
+
if not path.is_dir():
|
|
415
|
+
raise ValueError("目录不存在")
|
|
416
|
+
return bounded("\n".join(sorted(f"{item.name}{'/' if item.is_dir() else ''}" for item in path.iterdir())[:300]))
|
|
417
|
+
if name == "read_file":
|
|
418
|
+
path = skills.resolve_path(root, args["path"])
|
|
419
|
+
if not path.is_file():
|
|
420
|
+
raise ValueError("文件不存在")
|
|
421
|
+
offset, limit = args.get("offset", 0), args.get("limit", MAX_RESULT)
|
|
422
|
+
if type(offset) is not int or offset < 0 or type(limit) is not int or not 1 <= limit <= MAX_RESULT:
|
|
423
|
+
raise ValueError("offset 必须为非负整数,limit 必须为 1–16000 的整数")
|
|
424
|
+
with path.open("r", encoding="utf-8", newline="") as file:
|
|
425
|
+
remaining = offset
|
|
426
|
+
while remaining:
|
|
427
|
+
chunk = file.read(min(remaining, MAX_RESULT))
|
|
428
|
+
if not chunk:
|
|
429
|
+
return ""
|
|
430
|
+
remaining -= len(chunk)
|
|
431
|
+
text = file.read(limit)
|
|
432
|
+
more = bool(file.read(1))
|
|
433
|
+
return text + (f"\n[结果已截断;next_offset={offset + len(text)},请使用 read_file 继续读取]" if more else "")
|
|
434
|
+
if name == "search_files":
|
|
435
|
+
query = args["query"]
|
|
436
|
+
if not isinstance(query, str) or not query or len(query) > 300:
|
|
437
|
+
raise ValueError("搜索词无效")
|
|
438
|
+
path = skills.resolve_path(root, args.get("path", "."))
|
|
439
|
+
process = await asyncio.create_subprocess_exec(
|
|
440
|
+
"rg", "--no-heading", "-n", "-F", "--max-count", "20", "--max-columns", "1000",
|
|
441
|
+
"--", query, str(path), cwd=root, stdout=asyncio.subprocess.PIPE,
|
|
442
|
+
stderr=asyncio.subprocess.STDOUT)
|
|
443
|
+
try:
|
|
444
|
+
async with asyncio.timeout(15):
|
|
445
|
+
chunks = []
|
|
446
|
+
size = 0
|
|
447
|
+
truncated = False
|
|
448
|
+
while data := await process.stdout.read(4096):
|
|
449
|
+
chunks.append(data)
|
|
450
|
+
size += len(data)
|
|
451
|
+
if size > MAX_RESULT:
|
|
452
|
+
truncated = True
|
|
453
|
+
process.kill()
|
|
454
|
+
break
|
|
455
|
+
await process.wait()
|
|
456
|
+
except BaseException:
|
|
457
|
+
if process.returncode is None:
|
|
458
|
+
process.kill()
|
|
459
|
+
await process.wait()
|
|
460
|
+
raise
|
|
461
|
+
out = b"".join(chunks).decode(errors="replace")
|
|
462
|
+
if truncated:
|
|
463
|
+
return bounded(out)
|
|
464
|
+
if process.returncode not in (0, 1):
|
|
465
|
+
raise RuntimeError(bounded(out))
|
|
466
|
+
return bounded(out) or "没有匹配结果"
|
|
467
|
+
if name == "run_command":
|
|
468
|
+
return await run_command(args["command"], command_directory(root, args.get("cwd")), approved=approved)
|
|
469
|
+
if name == "web_search":
|
|
470
|
+
query = args["query"]
|
|
471
|
+
if not isinstance(query, str) or not query or len(query) > 400:
|
|
472
|
+
raise ValueError("搜索词无效")
|
|
473
|
+
key = os.getenv("TAVILY_API_KEY")
|
|
474
|
+
if not key:
|
|
475
|
+
raise RuntimeError("未配置 TAVILY_API_KEY,联网搜索不可用")
|
|
476
|
+
async with httpx.AsyncClient(timeout=15) as client:
|
|
477
|
+
response = await client.post("https://api.tavily.com/search",
|
|
478
|
+
headers={"Authorization": f"Bearer {key}"},
|
|
479
|
+
json={"query": query, "search_depth": "basic", "max_results": 5,
|
|
480
|
+
"include_answer": False, "include_raw_content": False})
|
|
481
|
+
response.raise_for_status()
|
|
482
|
+
results = response.json().get("results", [])
|
|
483
|
+
return bounded(json.dumps([{"title": str(item.get("title") or "")[:200],
|
|
484
|
+
"url": str(item.get("url") or "")[:1000],
|
|
485
|
+
"content": str(item.get("content") or "")[:1200]} for item in results[:5]],
|
|
486
|
+
ensure_ascii=False))
|
|
487
|
+
raise ValueError(f"未知工具:{name}")
|
aizz_server/cli.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""User-invoked local administration; never starts services implicitly."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import shutil
|
|
8
|
+
import sqlite3
|
|
9
|
+
|
|
10
|
+
from . import device_auth, storage_paths
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .pairing import payload, server_url
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def initialize():
|
|
16
|
+
resources = Path(__file__).resolve().parent
|
|
17
|
+
target = storage_paths.data_dir()
|
|
18
|
+
storage_paths.ensure_private_directory(target)
|
|
19
|
+
storage_paths.ensure_private_directory(target / 'skills')
|
|
20
|
+
files = {
|
|
21
|
+
storage_paths.config_path(): 'config.example.json',
|
|
22
|
+
storage_paths.workspaces_path(): 'workspaces.example.json',
|
|
23
|
+
target / 'tool_policy.json': 'tool_policy.example.json',
|
|
24
|
+
target / 'CHAT_INSTRUCTIONS.md': 'CHAT_INSTRUCTIONS.example.md',
|
|
25
|
+
target / 'CHAT_MEMORY.md': 'CHAT_MEMORY.example.md',
|
|
26
|
+
}
|
|
27
|
+
for destination, example in files.items():
|
|
28
|
+
if destination.exists():
|
|
29
|
+
continue
|
|
30
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
try:
|
|
32
|
+
fd = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
33
|
+
except FileExistsError:
|
|
34
|
+
continue
|
|
35
|
+
with os.fdopen(fd, 'wb') as output:
|
|
36
|
+
output.write((resources / example).read_bytes())
|
|
37
|
+
device_auth.initialize(storage_paths.database_path())
|
|
38
|
+
return target
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parser():
|
|
42
|
+
result = argparse.ArgumentParser(description='AIZZ 私人助手服务端(macOS / Linux;Python 3.11+)')
|
|
43
|
+
result.add_argument('--version', action='version', version=f'aizz {__version__}')
|
|
44
|
+
commands = result.add_subparsers(dest='command', required=True)
|
|
45
|
+
commands.add_parser('init', help='创建缺失的私人配置,不覆盖已有文件')
|
|
46
|
+
serve = commands.add_parser('serve', help='手动启动前台服务;单 worker')
|
|
47
|
+
serve.add_argument('--host', default='0.0.0.0')
|
|
48
|
+
serve.add_argument('--port', type=int, default=8000)
|
|
49
|
+
serve.add_argument('--forwarded-allow-ips', default='127.0.0.1', help='仅填写实际可信的反向代理 IP')
|
|
50
|
+
pair = commands.add_parser('pair', help='在本地终端生成五分钟有效、单次使用的配对二维码')
|
|
51
|
+
pair.add_argument('--url', required=True, type=server_url, help='手机可以访问的 HTTP 或 HTTPS 源地址')
|
|
52
|
+
devices = commands.add_parser('devices', help='管理当前数据库中的设备').add_subparsers(dest='action', required=True)
|
|
53
|
+
devices.add_parser('list')
|
|
54
|
+
removal = devices.add_parser('revoke')
|
|
55
|
+
selection = removal.add_mutually_exclusive_group(required=True)
|
|
56
|
+
selection.add_argument('--id')
|
|
57
|
+
selection.add_argument('--all', action='store_true')
|
|
58
|
+
migration = commands.add_parser('migrate', help='显式迁移旧源码目录内的私人数据;需手动停止服务端')
|
|
59
|
+
migration.add_argument('--from', dest='source', required=True, type=Path)
|
|
60
|
+
return result
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def main(argv=None):
|
|
64
|
+
arguments = parser().parse_args(argv)
|
|
65
|
+
try:
|
|
66
|
+
if arguments.command == 'init':
|
|
67
|
+
print(f'私人配置目录:{initialize()}')
|
|
68
|
+
elif arguments.command == 'serve':
|
|
69
|
+
if not 1 <= arguments.port <= 65535:
|
|
70
|
+
raise ValueError('端口必须介于 1 和 65535 之间')
|
|
71
|
+
if not shutil.which('codex'):
|
|
72
|
+
raise ValueError('未找到 codex,请先安装并登录 Codex CLI,并确保 codex 在 PATH 中')
|
|
73
|
+
initialize()
|
|
74
|
+
import uvicorn
|
|
75
|
+
uvicorn.run('aizz_server.app:app', host=arguments.host, port=arguments.port,
|
|
76
|
+
workers=1, proxy_headers=True,
|
|
77
|
+
forwarded_allow_ips=arguments.forwarded_allow_ips)
|
|
78
|
+
elif arguments.command == 'pair':
|
|
79
|
+
import qrcode
|
|
80
|
+
code = device_auth.issue_code(storage_paths.database_path())
|
|
81
|
+
qr = qrcode.QRCode(border=4)
|
|
82
|
+
qr.add_data(payload(arguments.url, code))
|
|
83
|
+
qr.make(fit=True)
|
|
84
|
+
print(f'服务器:{arguments.url}')
|
|
85
|
+
qr.print_ascii(tty=False, invert=True)
|
|
86
|
+
print(f'一次性授权码:{code}\n5 分钟有效,仅可绑定一台设备;新码使旧码失效。请勿分享二维码。')
|
|
87
|
+
elif arguments.command == 'devices':
|
|
88
|
+
path = storage_paths.database_path()
|
|
89
|
+
device_auth.initialize(path)
|
|
90
|
+
if arguments.action == 'list':
|
|
91
|
+
for item in device_auth.devices(path):
|
|
92
|
+
print(f"{item['id']} {item['name']} {item['platform']} "
|
|
93
|
+
f"{'已撤销' if item['revoked_at'] else '已授权'}")
|
|
94
|
+
else:
|
|
95
|
+
print(f'已撤销 {device_auth.revoke(path, None if arguments.all else arguments.id)} 台设备')
|
|
96
|
+
elif arguments.command == 'migrate':
|
|
97
|
+
from .migrate_storage import migrate
|
|
98
|
+
moved = migrate(arguments.source, storage_paths.data_dir())
|
|
99
|
+
print(f'已迁移 {len(moved)} 个文件到 {storage_paths.data_dir()}')
|
|
100
|
+
except (OSError, ValueError, KeyError, sqlite3.Error, RuntimeError) as exc:
|
|
101
|
+
raise SystemExit(str(exc)) from exc
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
if __name__ == '__main__':
|
|
105
|
+
main()
|