Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
163 lines (146 loc) · 5.48 KB
/
Copy pathmain.js
File metadata and controls
163 lines (146 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { app, BrowserWindow, ipcMain, safeStorage } from "electron";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { LayaEngine } from "./src/laya.js";
import { decide } from "./src/decide.js";
import { DEFAULT_OPENAI_MODEL, suggestReplies } from "./src/reply.js";
const here = path.dirname(fileURLToPath(import.meta.url));
const settingsFile = () => path.join(app.getPath("userData"), "settings.json");
// Packaged builds ship the sidecar under resources/ (outside the asar archive) so Python can read it.
const sidecarPath = () =>
app.isPackaged
? path.join(process.resourcesPath, "python", "laya_server.py")
: path.join(here, "python", "laya_server.py");
const DEFAULTS = {
relationship: "",
pythonPath: "python",
replyProvider: "anthropic", // anthropic | openai
anthropicKey: "",
openaiKey: "",
openaiModel: DEFAULT_OPENAI_MODEL,
openaiBaseURL: "",
};
const SECRET_FIELDS = ["anthropicKey", "openaiKey"];
// API keys are encrypted with the OS keychain (DPAPI on Windows) and never reach the renderer.
function loadSettings() {
try {
const raw = JSON.parse(fs.readFileSync(settingsFile(), "utf8"));
const s = { ...DEFAULTS, ...raw };
for (const f of SECRET_FIELDS) s[f] = raw[f] ? safeStorage.decryptString(Buffer.from(raw[f], "base64")) : "";
return s;
} catch {
return { ...DEFAULTS };
}
}
function saveSettings(s) {
const out = { ...s };
for (const f of SECRET_FIELDS) out[f] = s[f] ? safeStorage.encryptString(s[f]).toString("base64") : "";
fs.mkdirSync(path.dirname(settingsFile()), { recursive: true });
fs.writeFileSync(settingsFile(), JSON.stringify(out));
}
const keyFor = (provider) =>
provider === "openai"
? settings.openaiKey || process.env.OPENAI_API_KEY
: settings.anthropicKey || process.env.ANTHROPIC_API_KEY;
let settings;
let engine;
let win;
let lastStatus = { state: "stopped", message: "" };
function sendStatus(status) {
lastStatus = status;
win?.webContents.send("engine:status", status);
}
function publicSettings() {
return {
hasAnthropicKey: Boolean(keyFor("anthropic")),
hasOpenaiKey: Boolean(keyFor("openai")),
replyProvider: settings.replyProvider,
openaiModel: settings.openaiModel,
openaiBaseURL: settings.openaiBaseURL,
relationship: settings.relationship,
pythonPath: settings.pythonPath,
};
}
ipcMain.handle("settings:get", () => publicSettings());
ipcMain.handle("settings:set", (_e, patch) => {
// An empty key field means "keep the current key".
for (const f of SECRET_FIELDS) if (patch[f]) settings[f] = patch[f].trim();
if (patch.replyProvider === "anthropic" || patch.replyProvider === "openai") settings.replyProvider = patch.replyProvider;
if (typeof patch.openaiModel === "string") settings.openaiModel = patch.openaiModel.trim() || DEFAULT_OPENAI_MODEL;
if (typeof patch.openaiBaseURL === "string") settings.openaiBaseURL = patch.openaiBaseURL.trim().replace(/\/+$/, "");
if (typeof patch.relationship === "string") settings.relationship = patch.relationship.trim();
const py = typeof patch.pythonPath === "string" ? patch.pythonPath.trim() || "python" : settings.pythonPath;
const pythonChanged = py !== settings.pythonPath;
settings.pythonPath = py;
saveSettings(settings);
if (pythonChanged) {
engine.pythonPath = py;
engine.start();
}
return publicSettings();
});
ipcMain.handle("engine:status", () => lastStatus);
ipcMain.handle("engine:restart", () => engine.start());
ipcMain.handle("engine:install", async () => {
engine.stop();
sendStatus({ state: "installing", message: "正在安装 Laya(含 PyTorch,可能需要几分钟)…" });
const res = await engine.install((line) => sendStatus({ state: "installing", message: line.slice(0, 160) }));
if (!res.ok) {
sendStatus({ state: "not_installed", message: `安装失败:${res.error}` });
return res;
}
engine.start();
return res;
});
ipcMain.handle("analyze", async (_e, history) => {
const result = await engine.analyze(history, settings.relationship);
const decision = decide(result, { hasMyReply: history.some((m) => m.from === "me") });
const model = result.routing ? `laya-${result.routing.model}` : result.model;
return { model, usage: result.usage, decision };
});
ipcMain.handle("reply", async (_e, history, decision) => {
const provider = settings.replyProvider;
const apiKey = keyFor(provider);
if (!apiKey) {
return { replies: [], error: `未填写 ${provider === "openai" ? "OpenAI" : "Anthropic"} API Key,跳过回复建议。` };
}
try {
const replies = await suggestReplies(history, decision, {
provider,
apiKey,
model: settings.openaiModel,
baseURL: settings.openaiBaseURL,
relationship: settings.relationship,
});
return { replies };
} catch (err) {
return { replies: [], error: err.message };
}
});
function createWindow() {
win = new BrowserWindow({
width: 480,
height: 860,
minWidth: 380,
title: "聊天军师",
backgroundColor: "#ededed",
autoHideMenuBar: true,
webPreferences: {
preload: path.join(here, "preload.cjs"),
contextIsolation: true,
sandbox: true,
},
});
win.loadFile(path.join(here, "renderer", "index.html"));
}
app.whenReady().then(() => {
settings = loadSettings();
engine = new LayaEngine({ pythonPath: settings.pythonPath, scriptPath: sidecarPath(), onStatus: sendStatus });
createWindow();
engine.start();
});
app.on("window-all-closed", () => {
engine?.stop();
app.quit();
});