audit-e2w 1.11.2 → 1.11.7
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/README.md +152 -148
- package/dsh_plugins/audit-e2w/lib/index.js +9 -1
- package/dsh_plugins/audit-e2w/lib/skill.js +3 -2
- package/excel_word/README.md +45 -37
- package/excel_word/qoder_engine.py +10 -11
- package/excel_word/wesync/__init__.py +1 -1
- package/excel_word/wesync/ai/__init__.py +52 -0
- package/excel_word/wesync/ai/actions.py +369 -0
- package/excel_word/wesync/ai/client.py +340 -0
- package/excel_word/wesync/ai/config.py +291 -0
- package/excel_word/wesync/ai/docs.py +177 -0
- package/excel_word/wesync/ai/prompts.py +288 -0
- package/excel_word/wesync/ai/tasks/__init__.py +26 -0
- package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
- package/excel_word/wesync/ai/tasks/combined.py +123 -0
- package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
- package/excel_word/wesync/ai/tasks/headings.py +119 -0
- package/excel_word/wesync/ai/tasks/help_task.py +69 -0
- package/excel_word/wesync/ai/tasks/roles.py +128 -0
- package/excel_word/wesync/align.py +1 -0
- package/excel_word/wesync/api.py +544 -92
- package/excel_word/wesync/backup_history.py +44 -9
- package/excel_word/wesync/cli.py +19 -1
- package/excel_word/wesync/commands/blank_cmd.py +59 -30
- package/excel_word/wesync/commands/bookmark_cmd.py +41 -10
- package/excel_word/wesync/commands/clear_cmd.py +5 -3
- package/excel_word/wesync/commands/export_cmd.py +270 -220
- package/excel_word/wesync/commands/incremental_cmd.py +157 -0
- package/excel_word/wesync/commands/marks_cmd.py +24 -16
- package/excel_word/wesync/commands/placeholders_cmd.py +12 -7
- package/excel_word/wesync/commands/writeback_cmd.py +72 -116
- package/excel_word/wesync/config.py +3 -2
- package/excel_word/wesync/console.py +9 -2
- package/excel_word/wesync/docx_bookmarks.py +12 -5
- package/excel_word/wesync/docx_columns.py +1 -1
- package/excel_word/wesync/docx_marks.py +183 -75
- package/excel_word/wesync/docx_placeholders.py +65 -26
- package/excel_word/wesync/excel_blocks.py +144 -185
- package/excel_word/wesync/excel_export.py +15 -8
- package/excel_word/wesync/excel_marks.py +265 -193
- package/excel_word/wesync/fsops.py +11 -6
- package/excel_word/wesync/gui/__init__.py +21 -2
- package/excel_word/wesync/gui/app.py +243 -29
- package/excel_word/wesync/gui/manual.py +5 -3
- package/excel_word/wesync/gui/pages/__init__.py +53 -4
- package/excel_word/wesync/gui/pages/_page.py +129 -7
- package/excel_word/wesync/gui/pages/ai_page.py +854 -0
- package/excel_word/wesync/gui/pages/batch_page.py +64 -31
- package/excel_word/wesync/gui/pages/blank_page.py +529 -464
- package/excel_word/wesync/gui/pages/bookmark_page.py +97 -37
- package/excel_word/wesync/gui/pages/export_page.py +140 -87
- package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
- package/excel_word/wesync/gui/pages/format_page.py +551 -429
- package/excel_word/wesync/gui/pages/help_page.py +73 -7
- package/excel_word/wesync/gui/pages/history_page.py +167 -144
- package/excel_word/wesync/gui/pages/marks_page.py +210 -177
- package/excel_word/wesync/gui/pages/settings_page.py +450 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +167 -146
- package/excel_word/wesync/gui/runner.py +29 -13
- package/excel_word/wesync/gui/store.py +23 -7
- package/excel_word/wesync/gui/theme.py +220 -49
- package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
- package/excel_word/wesync/gui/widgets/cards.py +124 -5
- package/excel_word/wesync/gui/widgets/chips.py +565 -0
- package/excel_word/wesync/gui/widgets/filebar.py +1 -1
- package/excel_word/wesync/gui/widgets/logpane.py +24 -8
- package/excel_word/wesync/gui/widgets/nav.py +267 -12
- package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
- package/excel_word/wesync/report_format.py +9 -1
- package/excel_word/wesync/settings.py +35 -0
- package/excel_word/wesync/sort_rules.py +75 -26
- package/excel_word/wesync/valuefmt.py +40 -17
- package/package.json +53 -51
- package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
- package/qoder_plugins/audit-toolbox/README.md +159 -156
- package/qoder_plugins/audit-toolbox/catalog.mjs +13 -13
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""OpenAI 兼容 chat/completions 最小客户端(只用标准库 urllib)。
|
|
2
|
+
|
|
3
|
+
约束:
|
|
4
|
+
- 不引入任何第三方依赖,不改变打包体积;
|
|
5
|
+
- 传输层可注入(transport),测试不发真实网络;
|
|
6
|
+
- 异常信息不回显 Authorization 头或密钥;
|
|
7
|
+
- 只做一次请求,不重试、不流式,失败即抛 AiError 由调用方降级。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Callable
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AiError(Exception):
|
|
22
|
+
"""AI 调用失败(网络、鉴权、超时、返回格式错等)。"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class ChatResult:
|
|
27
|
+
text: str
|
|
28
|
+
model: str = ""
|
|
29
|
+
prompt_chars: int = 0
|
|
30
|
+
elapsed_ms: int = 0
|
|
31
|
+
raw: dict = field(default_factory=dict)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# transport(url, headers, body_bytes, timeout) -> (status, response_bytes)
|
|
35
|
+
Transport = Callable[[str, dict, bytes, int], tuple[int, bytes]]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _urllib_get(url: str, headers: dict, body: bytes = b"", timeout: int = 20) -> tuple[int, bytes]:
|
|
39
|
+
"""GET 请求(用于 /models 列表)。body 参数只为与 POST transport 签名对齐。"""
|
|
40
|
+
request = urllib.request.Request(url, headers=headers, method="GET")
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
43
|
+
return int(response.status), response.read()
|
|
44
|
+
except urllib.error.HTTPError as exc:
|
|
45
|
+
detail = ""
|
|
46
|
+
try:
|
|
47
|
+
detail = exc.read().decode("utf-8", "replace")[:600]
|
|
48
|
+
except Exception:
|
|
49
|
+
detail = ""
|
|
50
|
+
raise AiError(_http_message(exc.code, detail)) from None
|
|
51
|
+
except urllib.error.URLError as exc:
|
|
52
|
+
reason = getattr(exc, "reason", exc)
|
|
53
|
+
if isinstance(reason, socket.timeout):
|
|
54
|
+
raise AiError(f"连接超时({timeout} 秒)。") from None
|
|
55
|
+
raise AiError(f"无法连接模型服务:{reason}。请检查接口地址与本机网络。") from None
|
|
56
|
+
except socket.timeout:
|
|
57
|
+
raise AiError(f"连接超时({timeout} 秒)。") from None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def list_models(
|
|
61
|
+
base_url: str,
|
|
62
|
+
*,
|
|
63
|
+
api_key: str = "",
|
|
64
|
+
timeout: int = 20,
|
|
65
|
+
transport=None,
|
|
66
|
+
) -> list[str]:
|
|
67
|
+
"""查询服务商的模型列表(GET {base}/models),返回模型 id 列表。
|
|
68
|
+
|
|
69
|
+
兼容各家差异:只取 data[].id,按字母序返回并去重;结构不符时抛 AiError。
|
|
70
|
+
"""
|
|
71
|
+
url = join_url(base_url, "/models")
|
|
72
|
+
headers = {"Accept": "application/json"}
|
|
73
|
+
if api_key:
|
|
74
|
+
headers["Authorization"] = f"Bearer {api_key}"
|
|
75
|
+
fetch = transport or _urllib_get
|
|
76
|
+
try:
|
|
77
|
+
status, raw = fetch(url, headers, b"", max(5, min(int(timeout), 60)))
|
|
78
|
+
except TypeError:
|
|
79
|
+
# 注入的 transport 是 POST 签名(测试用),退化为四参数调用
|
|
80
|
+
raise AiError("传输层不支持查询模型列表。") from None
|
|
81
|
+
if status != 200:
|
|
82
|
+
detail = raw.decode("utf-8", "replace")[:600] if isinstance(raw, bytes) else str(raw)[:600]
|
|
83
|
+
raise AiError(_http_message(status, detail))
|
|
84
|
+
try:
|
|
85
|
+
data = json.loads(raw.decode("utf-8") if isinstance(raw, bytes) else raw)
|
|
86
|
+
except (ValueError, UnicodeDecodeError):
|
|
87
|
+
raise AiError("模型列表返回的不是合法 JSON。") from None
|
|
88
|
+
items = data.get("data") if isinstance(data, dict) else None
|
|
89
|
+
if not isinstance(items, list):
|
|
90
|
+
raise AiError("模型列表格式不符合 OpenAI 规范(缺少 data 数组)。")
|
|
91
|
+
names = []
|
|
92
|
+
for item in items:
|
|
93
|
+
if isinstance(item, dict):
|
|
94
|
+
name = item.get("id") or item.get("name")
|
|
95
|
+
if isinstance(name, str) and name.strip():
|
|
96
|
+
names.append(name.strip())
|
|
97
|
+
return sorted(set(names))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _urllib_transport(url: str, headers: dict, body: bytes, timeout: int) -> tuple[int, bytes]:
|
|
101
|
+
request = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
102
|
+
try:
|
|
103
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
104
|
+
return int(response.status), response.read()
|
|
105
|
+
except urllib.error.HTTPError as exc:
|
|
106
|
+
detail = ""
|
|
107
|
+
try:
|
|
108
|
+
detail = exc.read().decode("utf-8", "replace")[:600]
|
|
109
|
+
except Exception:
|
|
110
|
+
detail = ""
|
|
111
|
+
raise AiError(_http_message(exc.code, detail)) from None
|
|
112
|
+
except urllib.error.URLError as exc:
|
|
113
|
+
reason = getattr(exc, "reason", exc)
|
|
114
|
+
if isinstance(reason, socket.timeout):
|
|
115
|
+
raise AiError(f"连接超时({timeout} 秒),已退回本地规则。") from None
|
|
116
|
+
raise AiError(f"无法连接模型服务:{reason}。请检查接口地址与本机网络。") from None
|
|
117
|
+
except socket.timeout:
|
|
118
|
+
raise AiError(f"连接超时({timeout} 秒),已退回本地规则。") from None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _error_detail(detail: str, *, limit: int = 160) -> str:
|
|
122
|
+
"""从服务商的错误响应里抽出真正有用的那句话,丢掉整段 JSON 与堆栈。
|
|
123
|
+
|
|
124
|
+
各家错误体形状不一:OpenAI 风格是 {"error":{"message":...}},
|
|
125
|
+
有些直接给 {"message":...} 或 {"detail":...},还有的返回纯文本。
|
|
126
|
+
这里统一取一句话并截断,避免把整段 JSON 糊到界面上。
|
|
127
|
+
"""
|
|
128
|
+
text = (detail or "").strip()
|
|
129
|
+
if not text:
|
|
130
|
+
return ""
|
|
131
|
+
try:
|
|
132
|
+
data = json.loads(text)
|
|
133
|
+
except (ValueError, TypeError):
|
|
134
|
+
data = None
|
|
135
|
+
if isinstance(data, dict):
|
|
136
|
+
for path in (
|
|
137
|
+
("error", "message"), ("message",), ("error",), ("detail",), ("msg",),
|
|
138
|
+
):
|
|
139
|
+
value = data
|
|
140
|
+
for key in path:
|
|
141
|
+
value = value.get(key) if isinstance(value, dict) else None
|
|
142
|
+
if isinstance(value, str) and value.strip():
|
|
143
|
+
text = value.strip()
|
|
144
|
+
break
|
|
145
|
+
# 压平换行,避免长段落撑高界面
|
|
146
|
+
text = re.sub(r"\s+", " ", text)
|
|
147
|
+
if len(text) > limit:
|
|
148
|
+
text = text[:limit].rstrip() + "…"
|
|
149
|
+
return text
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _http_message(code: int, detail: str, *, model: str = "") -> str:
|
|
153
|
+
"""把 HTTP 状态码翻译成可操作的中文提示;不回显请求头或整段错误 JSON。"""
|
|
154
|
+
hints = {
|
|
155
|
+
400: "请求格式被拒绝",
|
|
156
|
+
401: "密钥无效或未填写",
|
|
157
|
+
403: "密钥无权访问该模型",
|
|
158
|
+
404: "接口地址或模型名不存在",
|
|
159
|
+
429: "调用过于频繁或额度不足",
|
|
160
|
+
500: "模型服务内部错误",
|
|
161
|
+
502: "模型服务网关错误",
|
|
162
|
+
503: "模型服务暂不可用",
|
|
163
|
+
}
|
|
164
|
+
base = hints.get(code, f"模型服务返回 HTTP {code}")
|
|
165
|
+
# 404 最常见的成因是模型名写错,直接给出下一步动作
|
|
166
|
+
advice = ""
|
|
167
|
+
if code == 404:
|
|
168
|
+
advice = "请点「获取模型列表」选一个可用模型,或核对接口地址是否要带 /v1。"
|
|
169
|
+
elif code == 401:
|
|
170
|
+
advice = "请检查 API Key 是否填对、是否过期。"
|
|
171
|
+
elif code == 429:
|
|
172
|
+
advice = "请稍后重试,或检查账户余额。"
|
|
173
|
+
head = f"{base}(HTTP {code})。"
|
|
174
|
+
if model:
|
|
175
|
+
head += f"当前模型:{model}。"
|
|
176
|
+
snippet = _error_detail(detail)
|
|
177
|
+
parts = [head]
|
|
178
|
+
if snippet:
|
|
179
|
+
parts.append(f"服务商提示:{snippet}")
|
|
180
|
+
if advice:
|
|
181
|
+
parts.append(advice)
|
|
182
|
+
return " ".join(parts).strip()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def join_url(base_url: str, path: str = "/chat/completions") -> str:
|
|
186
|
+
"""拼接接口地址,容忍结尾多余斜杠。"""
|
|
187
|
+
base = (base_url or "").strip().rstrip("/")
|
|
188
|
+
if not base:
|
|
189
|
+
raise AiError("接口地址为空,请先在设置里填写 base_url。")
|
|
190
|
+
if not base.lower().startswith(("http://", "https://")):
|
|
191
|
+
raise AiError("接口地址必须以 http:// 或 https:// 开头。")
|
|
192
|
+
if base.endswith("/chat/completions"):
|
|
193
|
+
return base
|
|
194
|
+
return f"{base}{path}"
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class ChatClient:
|
|
198
|
+
"""一次性对话客户端;每次调用只发一个请求。"""
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
*,
|
|
203
|
+
base_url: str,
|
|
204
|
+
model: str,
|
|
205
|
+
api_key: str = "",
|
|
206
|
+
timeout: int = 60,
|
|
207
|
+
temperature: float = 0.0,
|
|
208
|
+
transport: Transport | None = None,
|
|
209
|
+
thinking: bool | None = None,
|
|
210
|
+
json_mode: bool = False,
|
|
211
|
+
):
|
|
212
|
+
self.base_url = base_url
|
|
213
|
+
self.model = model
|
|
214
|
+
self.api_key = api_key
|
|
215
|
+
self.timeout = max(5, min(int(timeout), 600))
|
|
216
|
+
self.temperature = temperature
|
|
217
|
+
self._transport = transport or _urllib_transport
|
|
218
|
+
self.thinking = thinking
|
|
219
|
+
self.json_mode = json_mode
|
|
220
|
+
|
|
221
|
+
def _headers(self) -> dict:
|
|
222
|
+
headers = {"Content-Type": "application/json", "Accept": "application/json"}
|
|
223
|
+
if self.api_key:
|
|
224
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
225
|
+
return headers
|
|
226
|
+
|
|
227
|
+
def chat(self, messages: list[dict], *, max_tokens: int = 1024) -> ChatResult:
|
|
228
|
+
"""发送一次对话请求;任何失败都抛 AiError。"""
|
|
229
|
+
import time
|
|
230
|
+
|
|
231
|
+
if not self.model:
|
|
232
|
+
raise AiError("模型名为空,请先在设置里填写模型。")
|
|
233
|
+
payload = {
|
|
234
|
+
"model": self.model,
|
|
235
|
+
"messages": messages,
|
|
236
|
+
"temperature": self.temperature,
|
|
237
|
+
"max_tokens": max_tokens,
|
|
238
|
+
"stream": False,
|
|
239
|
+
}
|
|
240
|
+
# DeepSeek V4 系列默认开启思考模式:判级这类结构化任务不需要,
|
|
241
|
+
# 开着会慢 10 倍、思考 token 照常计费,且同一输入可能给出不同结论。
|
|
242
|
+
if self.thinking is not None:
|
|
243
|
+
payload["thinking"] = {"type": "enabled" if self.thinking else "disabled"}
|
|
244
|
+
if self.json_mode:
|
|
245
|
+
payload["response_format"] = {"type": "json_object"}
|
|
246
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
247
|
+
url = join_url(self.base_url)
|
|
248
|
+
prompt_chars = sum(len(str(item.get("content", ""))) for item in messages)
|
|
249
|
+
started = time.perf_counter()
|
|
250
|
+
status, raw = self._transport(url, self._headers(), body, self.timeout)
|
|
251
|
+
elapsed = int((time.perf_counter() - started) * 1000)
|
|
252
|
+
if status != 200:
|
|
253
|
+
detail = raw.decode("utf-8", "replace")[:600] if isinstance(raw, bytes) else str(raw)[:600]
|
|
254
|
+
raise AiError(_http_message(status, detail, model=self.model))
|
|
255
|
+
try:
|
|
256
|
+
data = json.loads(raw.decode("utf-8") if isinstance(raw, bytes) else raw)
|
|
257
|
+
except (ValueError, UnicodeDecodeError):
|
|
258
|
+
raise AiError("模型返回的不是合法 JSON,已退回本地规则。") from None
|
|
259
|
+
return ChatResult(
|
|
260
|
+
text=extract_text(data),
|
|
261
|
+
model=str(data.get("model") or self.model),
|
|
262
|
+
prompt_chars=prompt_chars,
|
|
263
|
+
elapsed_ms=elapsed,
|
|
264
|
+
raw=data,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def extract_text(data: dict) -> str:
|
|
269
|
+
"""从 chat/completions 响应里取出正文;结构不符时抛 AiError。"""
|
|
270
|
+
choices = data.get("choices")
|
|
271
|
+
if not isinstance(choices, list) or not choices:
|
|
272
|
+
raise AiError("模型返回里没有 choices,已退回本地规则。")
|
|
273
|
+
first = choices[0] if isinstance(choices[0], dict) else {}
|
|
274
|
+
message = first.get("message") if isinstance(first.get("message"), dict) else {}
|
|
275
|
+
text = message.get("content")
|
|
276
|
+
if isinstance(text, list):
|
|
277
|
+
text = "".join(
|
|
278
|
+
str(part.get("text", "")) for part in text if isinstance(part, dict)
|
|
279
|
+
)
|
|
280
|
+
if not isinstance(text, str) or not text.strip():
|
|
281
|
+
raise AiError("模型返回内容为空,已退回本地规则。")
|
|
282
|
+
return text.strip()
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def chat(
|
|
286
|
+
messages: list[dict],
|
|
287
|
+
*,
|
|
288
|
+
config: dict,
|
|
289
|
+
api_key: str = "",
|
|
290
|
+
transport: Transport | None = None,
|
|
291
|
+
thinking: bool | None = False,
|
|
292
|
+
json_mode: bool = False,
|
|
293
|
+
) -> ChatResult:
|
|
294
|
+
"""按配置发起一次请求的便捷入口。"""
|
|
295
|
+
client = ChatClient(
|
|
296
|
+
base_url=str(config.get("base_url", "")),
|
|
297
|
+
model=str(config.get("model", "")),
|
|
298
|
+
api_key=api_key,
|
|
299
|
+
timeout=int(config.get("timeout_seconds", 60)),
|
|
300
|
+
temperature=float(config.get("temperature", 0.0)),
|
|
301
|
+
transport=transport,
|
|
302
|
+
thinking=thinking,
|
|
303
|
+
json_mode=json_mode,
|
|
304
|
+
)
|
|
305
|
+
return client.chat(messages)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def parse_json_block(text: str) -> dict:
|
|
309
|
+
"""从模型输出里取出第一个 JSON 对象;兼容 ```json 围栏与前后废话。"""
|
|
310
|
+
stripped = (text or "").strip()
|
|
311
|
+
if not stripped:
|
|
312
|
+
raise AiError("模型没有返回内容。")
|
|
313
|
+
if stripped.startswith("```"):
|
|
314
|
+
lines = [line for line in stripped.splitlines() if not line.strip().startswith("```")]
|
|
315
|
+
stripped = "\n".join(lines).strip()
|
|
316
|
+
try:
|
|
317
|
+
value = json.loads(stripped)
|
|
318
|
+
if isinstance(value, dict):
|
|
319
|
+
return value
|
|
320
|
+
except ValueError:
|
|
321
|
+
pass
|
|
322
|
+
start = stripped.find("{")
|
|
323
|
+
while start != -1:
|
|
324
|
+
depth = 0
|
|
325
|
+
for index in range(start, len(stripped)):
|
|
326
|
+
char = stripped[index]
|
|
327
|
+
if char == "{":
|
|
328
|
+
depth += 1
|
|
329
|
+
elif char == "}":
|
|
330
|
+
depth -= 1
|
|
331
|
+
if depth == 0:
|
|
332
|
+
try:
|
|
333
|
+
value = json.loads(stripped[start : index + 1])
|
|
334
|
+
except ValueError:
|
|
335
|
+
break
|
|
336
|
+
if isinstance(value, dict):
|
|
337
|
+
return value
|
|
338
|
+
break
|
|
339
|
+
start = stripped.find("{", start + 1)
|
|
340
|
+
raise AiError("模型返回里找不到合法 JSON 对象,已退回本地规则。")
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""AI 配置:读写项目内 .wesync_ai.json,密钥用 Windows DPAPI 加密后落盘。
|
|
2
|
+
|
|
3
|
+
约定(遵循 AGENTS.md):
|
|
4
|
+
- 配置文件只落项目根,不写 AppData / 用户 home / 系统临时目录;
|
|
5
|
+
- 明文密钥绝不落盘,只存 DPAPI 密文(仅当前 Windows 用户可解);
|
|
6
|
+
- 非 Windows 或 DPAPI 不可用时退化为不保存密钥,并在配置里标明;
|
|
7
|
+
- 环境变量 AUDIT_TOOLBOX_AI_KEY 可覆盖,便于 CI 与临时使用。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from ..fsops import project_root
|
|
19
|
+
|
|
20
|
+
AI_CONFIG_NAME = ".wesync_ai.json"
|
|
21
|
+
KEY_ENV = "AUDIT_TOOLBOX_AI_KEY"
|
|
22
|
+
|
|
23
|
+
# 服务商预设:选中后自动填 base_url 与默认模型,用户仍可手改。
|
|
24
|
+
# 注意:各家模型名会轮换,预设只是"当前可用"的起点;界面上「获取模型列表」
|
|
25
|
+
# 会实时向服务商查询,避免预设过期。已知退役的名字不要写回预设:
|
|
26
|
+
# deepseek-chat / deepseek-reasoner(2026-07-24 停止服务)
|
|
27
|
+
# moonshot-v1-8k / -32k / -128k 及 kimi-k2.5(2026-08-31 全平台退役)
|
|
28
|
+
PROVIDERS: dict[str, dict] = {
|
|
29
|
+
"deepseek": {
|
|
30
|
+
"label": "DeepSeek(云端)",
|
|
31
|
+
"base_url": "https://api.deepseek.com/v1",
|
|
32
|
+
"model": "deepseek-flash",
|
|
33
|
+
"needs_key": True,
|
|
34
|
+
"hint": "当前主力:deepseek-flash;更强:deepseek-v4-pro",
|
|
35
|
+
},
|
|
36
|
+
"qwen": {
|
|
37
|
+
"label": "通义千问 / 百炼(云端)",
|
|
38
|
+
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
39
|
+
"model": "qwen-plus",
|
|
40
|
+
"needs_key": True,
|
|
41
|
+
"hint": "qwen-plus 均衡;要更强可换 qwen-max",
|
|
42
|
+
},
|
|
43
|
+
"kimi": {
|
|
44
|
+
"label": "Kimi / 月之暗面(云端)",
|
|
45
|
+
"base_url": "https://api.moonshot.cn/v1",
|
|
46
|
+
"model": "kimi-k2.6",
|
|
47
|
+
"needs_key": True,
|
|
48
|
+
"hint": "moonshot-v1 系列已退役;请用 kimi-k2 系列,建议点「获取模型列表」确认",
|
|
49
|
+
},
|
|
50
|
+
"siliconflow": {
|
|
51
|
+
"label": "硅基流动(云端)",
|
|
52
|
+
"base_url": "https://api.siliconflow.cn/v1",
|
|
53
|
+
"model": "Qwen/Qwen3-8B",
|
|
54
|
+
"needs_key": True,
|
|
55
|
+
"hint": "模型名带厂商前缀;建议点「获取模型列表」选",
|
|
56
|
+
},
|
|
57
|
+
"ollama": {
|
|
58
|
+
"label": "Ollama(本机,数据不出机器)",
|
|
59
|
+
"base_url": "http://127.0.0.1:11434/v1",
|
|
60
|
+
"model": "qwen3:8b",
|
|
61
|
+
"needs_key": False,
|
|
62
|
+
"hint": "先 ollama pull qwen3:8b;8B 以上判级质量更稳",
|
|
63
|
+
},
|
|
64
|
+
"lmstudio": {
|
|
65
|
+
"label": "LM Studio(本机,数据不出机器)",
|
|
66
|
+
"base_url": "http://127.0.0.1:1234/v1",
|
|
67
|
+
"model": "local-model",
|
|
68
|
+
"needs_key": False,
|
|
69
|
+
"hint": "填 LM Studio 里已加载模型的标识名",
|
|
70
|
+
},
|
|
71
|
+
"magpie": {
|
|
72
|
+
"label": "Magpie 网关(本机统一入口)",
|
|
73
|
+
"base_url": "http://127.0.0.1:3425/v1",
|
|
74
|
+
# 网关的模型名取决于本机接了哪些供应商,无法预设:留空并引导用户点「获取模型列表」,
|
|
75
|
+
# 比猜一个大概率不存在的名字好。
|
|
76
|
+
"model": "",
|
|
77
|
+
"needs_key": False,
|
|
78
|
+
"hint": "模型名因机器而异,请先点「获取模型列表」再选;格式为「供应商/模型」",
|
|
79
|
+
},
|
|
80
|
+
"custom": {
|
|
81
|
+
"label": "自定义(任意 OpenAI 兼容地址)",
|
|
82
|
+
"base_url": "",
|
|
83
|
+
"model": "",
|
|
84
|
+
"needs_key": True,
|
|
85
|
+
"hint": "填好地址后可点「获取模型列表」选模型",
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
PRIVACY_LEVELS = {"snippet": "只发送候选片段(推荐)", "off": "禁用发送"}
|
|
90
|
+
|
|
91
|
+
DEFAULT_AI: dict = {
|
|
92
|
+
"enabled": False,
|
|
93
|
+
"provider": "deepseek",
|
|
94
|
+
"base_url": PROVIDERS["deepseek"]["base_url"],
|
|
95
|
+
"model": PROVIDERS["deepseek"]["model"],
|
|
96
|
+
"timeout_seconds": 60,
|
|
97
|
+
"max_context_chars": 200,
|
|
98
|
+
"privacy_level": "snippet",
|
|
99
|
+
"fallback_local": True,
|
|
100
|
+
"temperature": 0.0,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# --------------------------------------------------------------------------- 密钥
|
|
105
|
+
|
|
106
|
+
class _DataBlob:
|
|
107
|
+
"""ctypes 用的 DATA_BLOB 结构(DPAPI 输入输出)。"""
|
|
108
|
+
|
|
109
|
+
def __init__(self, data: bytes = b""):
|
|
110
|
+
import ctypes
|
|
111
|
+
|
|
112
|
+
self._buffer = ctypes.create_string_buffer(data, len(data)) if data else None
|
|
113
|
+
self.size = len(data)
|
|
114
|
+
self.pbData = ctypes.cast(self._buffer, ctypes.c_void_p) if self._buffer else None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _dpapi_available() -> bool:
|
|
118
|
+
return sys.platform == "win32"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _dpapi_call(data: bytes, protect: bool) -> bytes:
|
|
122
|
+
"""调用 Windows DPAPI 加/解密;不可用时抛 AiError。"""
|
|
123
|
+
import ctypes
|
|
124
|
+
from ctypes import wintypes
|
|
125
|
+
|
|
126
|
+
if not _dpapi_available():
|
|
127
|
+
raise AiConfigError("当前系统不支持 Windows 数据保护接口,无法安全保存密钥。")
|
|
128
|
+
|
|
129
|
+
class DATA_BLOB(ctypes.Structure):
|
|
130
|
+
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
|
131
|
+
|
|
132
|
+
def to_blob(raw: bytes) -> tuple[DATA_BLOB, object]:
|
|
133
|
+
buffer = ctypes.create_string_buffer(raw, len(raw))
|
|
134
|
+
blob = DATA_BLOB(len(raw), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_char)))
|
|
135
|
+
return blob, buffer
|
|
136
|
+
|
|
137
|
+
crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
|
138
|
+
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
139
|
+
crypt32.CryptProtectData.argtypes = [
|
|
140
|
+
ctypes.POINTER(DATA_BLOB), wintypes.LPCWSTR, ctypes.POINTER(DATA_BLOB),
|
|
141
|
+
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DATA_BLOB),
|
|
142
|
+
]
|
|
143
|
+
crypt32.CryptUnprotectData.argtypes = [
|
|
144
|
+
ctypes.POINTER(DATA_BLOB), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(DATA_BLOB),
|
|
145
|
+
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DATA_BLOB),
|
|
146
|
+
]
|
|
147
|
+
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
|
|
148
|
+
|
|
149
|
+
source, source_buffer = to_blob(data)
|
|
150
|
+
target = DATA_BLOB()
|
|
151
|
+
if protect:
|
|
152
|
+
ok = crypt32.CryptProtectData(
|
|
153
|
+
ctypes.byref(source), "audit-toolbox-ai", None, None, None, 0, ctypes.byref(target)
|
|
154
|
+
)
|
|
155
|
+
else:
|
|
156
|
+
ok = crypt32.CryptUnprotectData(
|
|
157
|
+
ctypes.byref(source), None, None, None, None, 0, ctypes.byref(target)
|
|
158
|
+
)
|
|
159
|
+
if not ok:
|
|
160
|
+
raise AiConfigError(f"Windows 数据保护接口调用失败(错误码 {ctypes.get_last_error()})。")
|
|
161
|
+
try:
|
|
162
|
+
return ctypes.string_at(target.pbData, target.cbData)
|
|
163
|
+
finally:
|
|
164
|
+
kernel32.LocalFree(ctypes.cast(target.pbData, ctypes.c_void_p))
|
|
165
|
+
del source_buffer
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class AiConfigError(Exception):
|
|
169
|
+
"""AI 配置读写或密钥保护失败。"""
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def protect_key(plain: str) -> str:
|
|
173
|
+
"""把明文密钥加密成可落盘的 base64 密文。"""
|
|
174
|
+
if not plain:
|
|
175
|
+
return ""
|
|
176
|
+
return base64.b64encode(_dpapi_call(plain.encode("utf-8"), protect=True)).decode("ascii")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def unprotect_key(cipher: str) -> str:
|
|
180
|
+
"""把落盘密文还原为明文;失败返回空串,绝不抛给调用方。"""
|
|
181
|
+
if not cipher:
|
|
182
|
+
return ""
|
|
183
|
+
try:
|
|
184
|
+
return _dpapi_call(base64.b64decode(cipher.encode("ascii")), protect=False).decode("utf-8")
|
|
185
|
+
except Exception:
|
|
186
|
+
return ""
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def mask_key(key: str) -> str:
|
|
190
|
+
"""界面上只显示首尾各 4 位,中间用固定长度星号代替。"""
|
|
191
|
+
if not key:
|
|
192
|
+
return ""
|
|
193
|
+
if len(key) <= 8:
|
|
194
|
+
return "*" * len(key)
|
|
195
|
+
return f"{key[:4]}{'*' * 6}{key[-4:]}"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# --------------------------------------------------------------------------- 读写
|
|
199
|
+
|
|
200
|
+
def config_path() -> Path:
|
|
201
|
+
return project_root() / AI_CONFIG_NAME
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def normalize_ai(values: dict | None) -> dict:
|
|
205
|
+
"""把任意输入收敛成合法配置;未知字段忽略,越界值回默认。"""
|
|
206
|
+
result = dict(DEFAULT_AI)
|
|
207
|
+
values = values if isinstance(values, dict) else {}
|
|
208
|
+
if isinstance(values.get("enabled"), bool):
|
|
209
|
+
result["enabled"] = values["enabled"]
|
|
210
|
+
provider = values.get("provider")
|
|
211
|
+
if provider in PROVIDERS:
|
|
212
|
+
result["provider"] = provider
|
|
213
|
+
base_url = values.get("base_url")
|
|
214
|
+
if isinstance(base_url, str) and base_url.strip():
|
|
215
|
+
result["base_url"] = base_url.strip()
|
|
216
|
+
elif provider in PROVIDERS:
|
|
217
|
+
result["base_url"] = PROVIDERS[provider]["base_url"]
|
|
218
|
+
model = values.get("model")
|
|
219
|
+
if isinstance(model, str) and model.strip():
|
|
220
|
+
result["model"] = model.strip()
|
|
221
|
+
elif provider in PROVIDERS:
|
|
222
|
+
result["model"] = PROVIDERS[provider]["model"]
|
|
223
|
+
timeout = values.get("timeout_seconds")
|
|
224
|
+
if isinstance(timeout, int) and not isinstance(timeout, bool) and 5 <= timeout <= 600:
|
|
225
|
+
result["timeout_seconds"] = timeout
|
|
226
|
+
limit = values.get("max_context_chars")
|
|
227
|
+
if isinstance(limit, int) and not isinstance(limit, bool) and 40 <= limit <= 2000:
|
|
228
|
+
result["max_context_chars"] = limit
|
|
229
|
+
if values.get("privacy_level") in PRIVACY_LEVELS:
|
|
230
|
+
result["privacy_level"] = values["privacy_level"]
|
|
231
|
+
if isinstance(values.get("fallback_local"), bool):
|
|
232
|
+
result["fallback_local"] = values["fallback_local"]
|
|
233
|
+
temperature = values.get("temperature")
|
|
234
|
+
if isinstance(temperature, (int, float)) and not isinstance(temperature, bool) and 0 <= temperature <= 2:
|
|
235
|
+
result["temperature"] = float(temperature)
|
|
236
|
+
if isinstance(values.get("api_key_enc"), str):
|
|
237
|
+
result["api_key_enc"] = values["api_key_enc"]
|
|
238
|
+
return result
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def load_ai_config(*, strict: bool = False) -> dict:
|
|
242
|
+
"""读配置;损坏或不存在时返回默认值(strict 时抛错)。"""
|
|
243
|
+
path = config_path()
|
|
244
|
+
if not path.exists():
|
|
245
|
+
return dict(DEFAULT_AI)
|
|
246
|
+
try:
|
|
247
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
248
|
+
data = json.load(handle)
|
|
249
|
+
return normalize_ai(data if isinstance(data, dict) else {})
|
|
250
|
+
except Exception:
|
|
251
|
+
if strict:
|
|
252
|
+
raise
|
|
253
|
+
return dict(DEFAULT_AI)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def save_ai_config(values: dict, *, repair: bool = False) -> dict:
|
|
257
|
+
"""保存配置;密文随文件落盘,明文只在内存中出现。"""
|
|
258
|
+
normalized = normalize_ai(values)
|
|
259
|
+
path = config_path()
|
|
260
|
+
try:
|
|
261
|
+
data = load_ai_config(strict=True) if path.exists() else {}
|
|
262
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
263
|
+
if not repair:
|
|
264
|
+
raise AiConfigError("现有 AI 配置已损坏,请先修复后再保存。")
|
|
265
|
+
data = {}
|
|
266
|
+
data.update(normalized)
|
|
267
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
268
|
+
staged = path.with_name(f".{path.name}.tmp")
|
|
269
|
+
try:
|
|
270
|
+
with staged.open("w", encoding="utf-8") as handle:
|
|
271
|
+
json.dump(data, handle, ensure_ascii=False, indent=2)
|
|
272
|
+
handle.flush()
|
|
273
|
+
os.fsync(handle.fileno())
|
|
274
|
+
os.replace(staged, path)
|
|
275
|
+
finally:
|
|
276
|
+
staged.unlink(missing_ok=True)
|
|
277
|
+
return normalized
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def resolve_api_key(config: dict | None = None) -> str:
|
|
281
|
+
"""取明文密钥:环境变量优先,其次解密密文。"""
|
|
282
|
+
env = os.environ.get(KEY_ENV, "").strip()
|
|
283
|
+
if env:
|
|
284
|
+
return env
|
|
285
|
+
config = load_ai_config() if config is None else config
|
|
286
|
+
return unprotect_key(config.get("api_key_enc", ""))
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def save_api_key(plain: str) -> str:
|
|
290
|
+
"""加密并返回密文;空串表示清除。"""
|
|
291
|
+
return protect_key(plain.strip())
|