moneyswitch 0.5.0
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 +202 -0
- package/README.md +63 -0
- package/dist/cli.js +523 -0
- package/dist/desktop.js +2699 -0
- package/dist/mcp.js +21535 -0
- package/dist/sell.js +34034 -0
- package/dist/ui/app.css +1 -0
- package/dist/ui/app.js +8 -0
- package/dist/ui/index.html +14 -0
- package/package.json +61 -0
package/dist/desktop.js
ADDED
|
@@ -0,0 +1,2699 @@
|
|
|
1
|
+
// src/desktop/ui.ts
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import path6 from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
// ../connect/dist/lib/runner.js
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
function quoteWinArg(arg) {
|
|
9
|
+
if (arg.length > 0 && !/[\s"&|<>^%()!,;=]/.test(arg))
|
|
10
|
+
return arg;
|
|
11
|
+
return `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`;
|
|
12
|
+
}
|
|
13
|
+
var RealCommandRunner = class {
|
|
14
|
+
opts;
|
|
15
|
+
constructor(opts = {}) {
|
|
16
|
+
this.opts = opts;
|
|
17
|
+
}
|
|
18
|
+
run(cmd, args) {
|
|
19
|
+
const win = process.platform === "win32";
|
|
20
|
+
try {
|
|
21
|
+
const res = win ? spawnSync([cmd, ...args].map(quoteWinArg).join(" "), {
|
|
22
|
+
encoding: "utf8",
|
|
23
|
+
shell: true,
|
|
24
|
+
env: this.opts.env ?? process.env,
|
|
25
|
+
cwd: this.opts.cwd,
|
|
26
|
+
timeout: this.opts.timeoutMs
|
|
27
|
+
}) : spawnSync(cmd, args, {
|
|
28
|
+
encoding: "utf8",
|
|
29
|
+
env: this.opts.env ?? process.env,
|
|
30
|
+
cwd: this.opts.cwd,
|
|
31
|
+
timeout: this.opts.timeoutMs
|
|
32
|
+
});
|
|
33
|
+
if (res.error) {
|
|
34
|
+
return { ok: false, code: null, stdout: "", stderr: String(res.error.message ?? res.error) };
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
ok: (res.status ?? 1) === 0,
|
|
38
|
+
code: res.status,
|
|
39
|
+
stdout: res.stdout ?? "",
|
|
40
|
+
stderr: res.stderr ?? ""
|
|
41
|
+
};
|
|
42
|
+
} catch (e) {
|
|
43
|
+
return { ok: false, code: null, stdout: "", stderr: e.message };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// src/desktop/server.ts
|
|
49
|
+
import http from "node:http";
|
|
50
|
+
import fs4 from "node:fs";
|
|
51
|
+
import path5 from "node:path";
|
|
52
|
+
|
|
53
|
+
// src/desktop/session.ts
|
|
54
|
+
import crypto from "node:crypto";
|
|
55
|
+
var COOKIE_NAME = "ms_desktop_session";
|
|
56
|
+
function randomToken(bytes = 32) {
|
|
57
|
+
return crypto.randomBytes(bytes).toString("base64url");
|
|
58
|
+
}
|
|
59
|
+
function safeEqual(a, b) {
|
|
60
|
+
const ab = Buffer.from(a);
|
|
61
|
+
const bb = Buffer.from(b);
|
|
62
|
+
return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);
|
|
63
|
+
}
|
|
64
|
+
var SessionManager = class {
|
|
65
|
+
constructor(port, token = randomToken()) {
|
|
66
|
+
this.port = port;
|
|
67
|
+
this.oneTimeToken = token;
|
|
68
|
+
}
|
|
69
|
+
port;
|
|
70
|
+
oneTimeToken;
|
|
71
|
+
sessions = /* @__PURE__ */ new Map();
|
|
72
|
+
/** The token to put in the launch URL fragment. Null once it has been used. */
|
|
73
|
+
get pendingToken() {
|
|
74
|
+
return this.oneTimeToken;
|
|
75
|
+
}
|
|
76
|
+
/** Mint a fresh one-time token (e.g. `moneyswitch ui` asked to re-open the browser). */
|
|
77
|
+
rotateToken() {
|
|
78
|
+
this.oneTimeToken = randomToken();
|
|
79
|
+
return this.oneTimeToken;
|
|
80
|
+
}
|
|
81
|
+
/** Exchange the one-time token for a session id. Returns null if wrong or already used. */
|
|
82
|
+
exchange(token) {
|
|
83
|
+
if (typeof token !== "string" || !this.oneTimeToken) return null;
|
|
84
|
+
if (!safeEqual(token, this.oneTimeToken)) return null;
|
|
85
|
+
this.oneTimeToken = null;
|
|
86
|
+
const sid = randomToken();
|
|
87
|
+
this.sessions.set(sid, { createdAt: Date.now() });
|
|
88
|
+
return sid;
|
|
89
|
+
}
|
|
90
|
+
isValid(sid) {
|
|
91
|
+
return typeof sid === "string" && this.sessions.has(sid);
|
|
92
|
+
}
|
|
93
|
+
revoke(sid) {
|
|
94
|
+
this.sessions.delete(sid);
|
|
95
|
+
}
|
|
96
|
+
cookieHeader(sid) {
|
|
97
|
+
return `${COOKIE_NAME}=${sid}; HttpOnly; SameSite=Strict; Path=/`;
|
|
98
|
+
}
|
|
99
|
+
/** Origins this server accepts (exact match, scheme+host+port). */
|
|
100
|
+
allowedOrigins() {
|
|
101
|
+
return [`http://127.0.0.1:${this.port}`, `http://localhost:${this.port}`];
|
|
102
|
+
}
|
|
103
|
+
allowedHosts() {
|
|
104
|
+
return [`127.0.0.1:${this.port}`, `localhost:${this.port}`];
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
function readCookie(header, name) {
|
|
108
|
+
if (!header) return null;
|
|
109
|
+
for (const part of header.split(";")) {
|
|
110
|
+
const i = part.indexOf("=");
|
|
111
|
+
if (i === -1) continue;
|
|
112
|
+
if (part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
function guardRequest(sm, req) {
|
|
117
|
+
const host = String(req.headers.host ?? "").toLowerCase();
|
|
118
|
+
if (!sm.allowedHosts().includes(host)) {
|
|
119
|
+
return { status: 421, code: "BAD_HOST", message: "unexpected Host header" };
|
|
120
|
+
}
|
|
121
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
122
|
+
const url = req.url ?? "/";
|
|
123
|
+
const isApi = url.startsWith("/api/");
|
|
124
|
+
const mutating = method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
|
|
125
|
+
if (isApi && mutating) {
|
|
126
|
+
const origin = req.headers.origin;
|
|
127
|
+
if (typeof origin !== "string" || !sm.allowedOrigins().includes(origin)) {
|
|
128
|
+
return { status: 403, code: "BAD_ORIGIN", message: "cross-origin request refused" };
|
|
129
|
+
}
|
|
130
|
+
const ct = String(req.headers["content-type"] ?? "");
|
|
131
|
+
if (!ct.toLowerCase().startsWith("application/json")) {
|
|
132
|
+
return { status: 415, code: "JSON_REQUIRED", message: "Content-Type must be application/json" };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (isApi && !(method === "POST" && url.split("?")[0] === "/api/session")) {
|
|
136
|
+
const sid = readCookie(req.headers.cookie, COOKIE_NAME);
|
|
137
|
+
if (!sm.isValid(sid)) return { status: 401, code: "NO_SESSION", message: "open the link printed by `moneyswitch ui`" };
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/desktop/service.ts
|
|
143
|
+
import os2 from "node:os";
|
|
144
|
+
|
|
145
|
+
// ../connect/dist/lib/mcp-entry.js
|
|
146
|
+
import { createRequire } from "node:module";
|
|
147
|
+
function resolveMcpCommand(fromUrl = import.meta.url) {
|
|
148
|
+
const require2 = createRequire(fromUrl);
|
|
149
|
+
try {
|
|
150
|
+
const entry = require2.resolve("@moneyswitch/mcp");
|
|
151
|
+
return { command: "node", args: [entry] };
|
|
152
|
+
} catch {
|
|
153
|
+
return { command: "npx", args: ["-y", "moneyswitch", "mcp"] };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function isNpmRegistryFallback(cmd) {
|
|
157
|
+
return cmd.command === "npx" && cmd.args.length === 3 && cmd.args[0] === "-y" && cmd.args[1] === "moneyswitch" && cmd.args[2] === "mcp";
|
|
158
|
+
}
|
|
159
|
+
async function resolvePortableMcpCommand(server, fetchImpl = fetch) {
|
|
160
|
+
const base = server.replace(/\/+$/, "");
|
|
161
|
+
const tarballUrl = `${base}/dl/moneyswitch.tgz`;
|
|
162
|
+
try {
|
|
163
|
+
const res = await fetchImpl(tarballUrl, { method: "HEAD" });
|
|
164
|
+
if (res.ok)
|
|
165
|
+
return { command: "npx", args: ["-y", `--package=${tarballUrl}`, "moneyswitch", "mcp"] };
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
return { command: "npx", args: ["-y", "moneyswitch", "mcp"] };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/desktop/agents.ts
|
|
172
|
+
import fs from "node:fs";
|
|
173
|
+
import path2 from "node:path";
|
|
174
|
+
|
|
175
|
+
// src/desktop/paths.ts
|
|
176
|
+
import path from "node:path";
|
|
177
|
+
import os from "node:os";
|
|
178
|
+
function homeDir(env) {
|
|
179
|
+
if (process.platform === "win32") {
|
|
180
|
+
if (env.USERPROFILE) return env.USERPROFILE;
|
|
181
|
+
if (env.HOME) return env.HOME;
|
|
182
|
+
} else if (env.HOME) {
|
|
183
|
+
return env.HOME;
|
|
184
|
+
}
|
|
185
|
+
return os.homedir();
|
|
186
|
+
}
|
|
187
|
+
function claudeConfigDir(env) {
|
|
188
|
+
return env.CLAUDE_CONFIG_DIR ? env.CLAUDE_CONFIG_DIR : path.join(homeDir(env), ".claude");
|
|
189
|
+
}
|
|
190
|
+
function claudeSettingsPath(env) {
|
|
191
|
+
return path.join(claudeConfigDir(env), "settings.json");
|
|
192
|
+
}
|
|
193
|
+
function claudeJsonPath(env) {
|
|
194
|
+
return env.CLAUDE_CONFIG_DIR ? path.join(env.CLAUDE_CONFIG_DIR, ".claude.json") : path.join(homeDir(env), ".claude.json");
|
|
195
|
+
}
|
|
196
|
+
function codexConfigFile(env) {
|
|
197
|
+
const home = env.CODEX_HOME ? env.CODEX_HOME : path.join(homeDir(env), ".codex");
|
|
198
|
+
return path.join(home, "config.toml");
|
|
199
|
+
}
|
|
200
|
+
function desktopDir(env) {
|
|
201
|
+
return path.join(homeDir(env), ".moneyswitch");
|
|
202
|
+
}
|
|
203
|
+
function desktopStorePath(env) {
|
|
204
|
+
return path.join(desktopDir(env), "desktop.json");
|
|
205
|
+
}
|
|
206
|
+
function displayPath(p, env) {
|
|
207
|
+
const home = homeDir(env);
|
|
208
|
+
const norm = (s) => s.replace(/\\/g, "/");
|
|
209
|
+
const np = norm(p);
|
|
210
|
+
const nh = norm(home).replace(/\/+$/, "");
|
|
211
|
+
if (np.toLowerCase().startsWith(nh.toLowerCase() + "/")) return "~" + np.slice(nh.length);
|
|
212
|
+
return np;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/desktop/plan.ts
|
|
216
|
+
import crypto2 from "node:crypto";
|
|
217
|
+
function maskSecret(value) {
|
|
218
|
+
if (value == null) return "";
|
|
219
|
+
const v = String(value);
|
|
220
|
+
if (v.length <= 10) return "\u2022\u2022\u2022\u2022";
|
|
221
|
+
const head = v.startsWith("mk_live_") ? 12 : Math.min(7, Math.floor(v.length / 4));
|
|
222
|
+
return `${v.slice(0, head)}\u2026${v.slice(-4)}`;
|
|
223
|
+
}
|
|
224
|
+
var AUTO_AGENTS = ["claude", "codex"];
|
|
225
|
+
var ALL_AGENTS = ["claude", "codex", "workbuddy", "openclaw", "cherry"];
|
|
226
|
+
function fieldChange(field, before, after, secret = false) {
|
|
227
|
+
const b = before ?? null;
|
|
228
|
+
const a = after ?? null;
|
|
229
|
+
const op = b === a ? "same" : b === null ? "add" : a === null ? "remove" : "update";
|
|
230
|
+
return {
|
|
231
|
+
field,
|
|
232
|
+
op,
|
|
233
|
+
before: secret && b !== null ? maskSecret(b) : b,
|
|
234
|
+
after: secret && a !== null ? maskSecret(a) : a,
|
|
235
|
+
...secret ? { secret: true } : {}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function sha256(text) {
|
|
239
|
+
return crypto2.createHash("sha256").update(text).digest("hex");
|
|
240
|
+
}
|
|
241
|
+
function stableStringify(v) {
|
|
242
|
+
if (v === null || typeof v !== "object") return JSON.stringify(v);
|
|
243
|
+
if (Array.isArray(v)) return `[${v.map(stableStringify).join(",")}]`;
|
|
244
|
+
const o = v;
|
|
245
|
+
return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
|
|
246
|
+
}
|
|
247
|
+
function deepEqual(a, b) {
|
|
248
|
+
return stableStringify(a) === stableStringify(b);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// src/desktop/agents.ts
|
|
252
|
+
var AGENT_INFO = {
|
|
253
|
+
claude: { id: "claude", name: "Claude Code", mode: "auto" },
|
|
254
|
+
codex: { id: "codex", name: "Codex", mode: "auto" },
|
|
255
|
+
workbuddy: { id: "workbuddy", name: "WorkBuddy", mode: "manual" },
|
|
256
|
+
openclaw: { id: "openclaw", name: "OpenClaw", mode: "manual" },
|
|
257
|
+
cherry: { id: "cherry", name: "Cherry Studio", mode: "manual" }
|
|
258
|
+
};
|
|
259
|
+
function firstLine(s) {
|
|
260
|
+
return s.split(/\r?\n/).find((l) => l.trim())?.trim() ?? "";
|
|
261
|
+
}
|
|
262
|
+
function viaCli(runner, cmd) {
|
|
263
|
+
const r = runner.run(cmd, ["--version"]);
|
|
264
|
+
if (!r.ok) return null;
|
|
265
|
+
return { installed: true, version: firstLine(r.stdout) || null, via: `${cmd} --version` };
|
|
266
|
+
}
|
|
267
|
+
function viaPath(env, candidates) {
|
|
268
|
+
const home = homeDir(env);
|
|
269
|
+
for (const c of candidates) {
|
|
270
|
+
const abs = c.startsWith("~") ? path2.join(home, c.slice(2)) : c;
|
|
271
|
+
if (fs.existsSync(abs)) return { installed: true, version: null, via: c };
|
|
272
|
+
}
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
var NONE = { installed: false, version: null, via: null };
|
|
276
|
+
function detectAgents(env, runner) {
|
|
277
|
+
const appData = env.APPDATA ?? path2.join(homeDir(env), "AppData", "Roaming");
|
|
278
|
+
const localAppData = env.LOCALAPPDATA ?? path2.join(homeDir(env), "AppData", "Local");
|
|
279
|
+
const cherryDirs = process.platform === "win32" ? [path2.join(appData, "CherryStudio")] : process.platform === "darwin" ? ["~/Library/Application Support/CherryStudio"] : ["~/.config/CherryStudio"];
|
|
280
|
+
return {
|
|
281
|
+
claude: viaCli(runner, "claude") ?? NONE,
|
|
282
|
+
codex: viaCli(runner, "codex") ?? NONE,
|
|
283
|
+
workbuddy: viaPath(env, ["~/.workbuddy", path2.join(localAppData, "Programs", "WorkBuddy")]) ?? NONE,
|
|
284
|
+
openclaw: viaPath(env, ["~/.openclaw"]) ?? viaCli(runner, "openclaw") ?? NONE,
|
|
285
|
+
cherry: viaPath(env, cherryDirs) ?? NONE
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function mcpJson(server, key, mcp, mask) {
|
|
289
|
+
return JSON.stringify(
|
|
290
|
+
{ mcpServers: { moneyswitch: { command: mcp.command, args: mcp.args, env: { MONEY_API_BASE: server, MONEY_API_KEY: mask ? maskSecret(key) : key } } } },
|
|
291
|
+
null,
|
|
292
|
+
2
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
function openclawPatch(brain, server, key, mcp, mask) {
|
|
296
|
+
const parts = ["{"];
|
|
297
|
+
if (brain) {
|
|
298
|
+
const model = brain.model || "<model>";
|
|
299
|
+
parts.push(
|
|
300
|
+
` models: { mode: "merge", providers: { moneyswitch_brain: { baseUrl: ${JSON.stringify(brain.baseUrl || "<base url>")}, apiKey: ${JSON.stringify(mask ? "<API key>" : brain.apiKey || "<API key>")}, api: "openai-completions", models: [{ id: ${JSON.stringify(model)}, name: ${JSON.stringify(model)} }] } } },`,
|
|
301
|
+
` agents: { defaults: { model: { primary: ${JSON.stringify(`moneyswitch_brain/${model}`)} } } },`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
if (server && key) {
|
|
305
|
+
parts.push(
|
|
306
|
+
` mcp: { servers: { moneyswitch: { command: ${JSON.stringify(mcp.command)}, args: ${JSON.stringify(mcp.args)}, env: { MONEY_API_BASE: ${JSON.stringify(server)}, MONEY_API_KEY: ${JSON.stringify(mask ? maskSecret(key) : key)} } } } },`
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
parts.push("}");
|
|
310
|
+
return parts.join("\n");
|
|
311
|
+
}
|
|
312
|
+
function manualSteps(agent, ctx) {
|
|
313
|
+
const { server, walletKey, mcp } = ctx;
|
|
314
|
+
const openaiBase = server ? `${server.replace(/\/+$/, "")}/v1` : "<server>/v1";
|
|
315
|
+
if (agent === "openclaw") {
|
|
316
|
+
if (!walletKey && !ctx.brain) return [];
|
|
317
|
+
const steps = [
|
|
318
|
+
{
|
|
319
|
+
titleKey: "stepOpenclawSave",
|
|
320
|
+
code: openclawPatch(ctx.brain, server, walletKey, mcp, true),
|
|
321
|
+
copy: openclawPatch(ctx.brain, server, walletKey, mcp, false)
|
|
322
|
+
},
|
|
323
|
+
{ titleKey: "stepOpenclawDryRun", code: "openclaw config patch --file moneyswitch.json5 --dry-run", copy: "openclaw config patch --file moneyswitch.json5 --dry-run" },
|
|
324
|
+
{ titleKey: "stepOpenclawApply", code: "openclaw config patch --file moneyswitch.json5\nopenclaw config validate\nopenclaw mcp list", copy: "openclaw config patch --file moneyswitch.json5" }
|
|
325
|
+
];
|
|
326
|
+
return steps;
|
|
327
|
+
}
|
|
328
|
+
if (agent === "workbuddy" || agent === "cherry") {
|
|
329
|
+
const steps = [];
|
|
330
|
+
if (server && walletKey) {
|
|
331
|
+
steps.push({
|
|
332
|
+
titleKey: agent === "cherry" ? "stepCherryMcp" : "stepWorkbuddyMcp",
|
|
333
|
+
code: mcpJson(server, walletKey, mcp, true),
|
|
334
|
+
copy: mcpJson(server, walletKey, mcp, false)
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
steps.push({
|
|
338
|
+
titleKey: agent === "cherry" ? "stepCherryModel" : "stepWorkbuddyModel",
|
|
339
|
+
rows: [
|
|
340
|
+
{ labelKey: "rowBaseUrl", value: openaiBase, copy: openaiBase },
|
|
341
|
+
...walletKey ? [{ labelKey: "rowApiKey", value: maskSecret(walletKey), copy: walletKey }] : []
|
|
342
|
+
]
|
|
343
|
+
});
|
|
344
|
+
return steps;
|
|
345
|
+
}
|
|
346
|
+
return [];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ../connect/dist/lib/claude.js
|
|
350
|
+
var SERVER_NAME = "moneyswitch";
|
|
351
|
+
function applyClaude(runner, server, key, mcpCommand) {
|
|
352
|
+
const removed = runner.run("claude", ["mcp", "remove", SERVER_NAME, "-s", "user"]);
|
|
353
|
+
const added = runner.run("claude", [
|
|
354
|
+
"mcp",
|
|
355
|
+
"add",
|
|
356
|
+
SERVER_NAME,
|
|
357
|
+
"-s",
|
|
358
|
+
"user",
|
|
359
|
+
"-e",
|
|
360
|
+
`MONEY_API_BASE=${server}`,
|
|
361
|
+
"-e",
|
|
362
|
+
`MONEY_API_KEY=${key}`,
|
|
363
|
+
"--",
|
|
364
|
+
mcpCommand.command,
|
|
365
|
+
...mcpCommand.args
|
|
366
|
+
]);
|
|
367
|
+
return { removed, added };
|
|
368
|
+
}
|
|
369
|
+
function removeClaude(runner) {
|
|
370
|
+
return runner.run("claude", ["mcp", "remove", SERVER_NAME, "-s", "user"]);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// src/desktop/filetx.ts
|
|
374
|
+
import fs2 from "node:fs";
|
|
375
|
+
import path3 from "node:path";
|
|
376
|
+
var FileTransaction = class {
|
|
377
|
+
touched = /* @__PURE__ */ new Map();
|
|
378
|
+
backups = [];
|
|
379
|
+
stamp;
|
|
380
|
+
constructor(stamp = Date.now()) {
|
|
381
|
+
this.stamp = stamp;
|
|
382
|
+
}
|
|
383
|
+
/** Take a backup of `file` (once per transaction). Call before anything modifies it, including agent CLIs. */
|
|
384
|
+
snapshot(file) {
|
|
385
|
+
const known = this.touched.get(file);
|
|
386
|
+
if (known) return known.backup;
|
|
387
|
+
const existed = fs2.existsSync(file);
|
|
388
|
+
let backup = null;
|
|
389
|
+
if (existed) {
|
|
390
|
+
backup = `${file}.bak-${this.stamp}`;
|
|
391
|
+
let n = 1;
|
|
392
|
+
while (fs2.existsSync(backup)) backup = `${file}.bak-${this.stamp}-${n++}`;
|
|
393
|
+
fs2.copyFileSync(file, backup);
|
|
394
|
+
this.backups.push(backup);
|
|
395
|
+
}
|
|
396
|
+
this.touched.set(file, { backup, existed });
|
|
397
|
+
return backup;
|
|
398
|
+
}
|
|
399
|
+
/** Write `content` to `file` (snapshotting first), then re-read and run `verify` on what is actually on disk. */
|
|
400
|
+
write(file, content, verify) {
|
|
401
|
+
this.snapshot(file);
|
|
402
|
+
fs2.mkdirSync(path3.dirname(file), { recursive: true });
|
|
403
|
+
fs2.writeFileSync(file, content, "utf8");
|
|
404
|
+
const back = fs2.readFileSync(file, "utf8");
|
|
405
|
+
if (back !== content) throw new Error(`read-back mismatch for ${file}`);
|
|
406
|
+
verify?.(back);
|
|
407
|
+
}
|
|
408
|
+
/** Delete `file` (snapshotting first). */
|
|
409
|
+
remove(file) {
|
|
410
|
+
this.snapshot(file);
|
|
411
|
+
if (fs2.existsSync(file)) fs2.rmSync(file);
|
|
412
|
+
}
|
|
413
|
+
/** Restore every touched file to its pre-transaction state. Never throws; returns what failed. */
|
|
414
|
+
rollback() {
|
|
415
|
+
const errors = [];
|
|
416
|
+
for (const [file, { backup, existed }] of this.touched) {
|
|
417
|
+
try {
|
|
418
|
+
if (existed && backup) fs2.copyFileSync(backup, file);
|
|
419
|
+
else if (!existed && fs2.existsSync(file)) fs2.rmSync(file);
|
|
420
|
+
} catch (e) {
|
|
421
|
+
errors.push(`${file}: ${e.message}`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return errors;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
function readIfExists(file) {
|
|
428
|
+
try {
|
|
429
|
+
return fs2.readFileSync(file, "utf8");
|
|
430
|
+
} catch (e) {
|
|
431
|
+
if (e.code === "ENOENT") return null;
|
|
432
|
+
throw e;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// src/desktop/presets.ts
|
|
437
|
+
var CLAUDE_PRESETS = [
|
|
438
|
+
{
|
|
439
|
+
id: "anthropic",
|
|
440
|
+
label: "Anthropic",
|
|
441
|
+
baseUrl: "https://api.anthropic.com",
|
|
442
|
+
models: ["claude-sonnet-4-5", "claude-haiku-4-5"],
|
|
443
|
+
authVar: "ANTHROPIC_API_KEY",
|
|
444
|
+
keyHint: "sk-ant-\u2026"
|
|
445
|
+
},
|
|
446
|
+
{
|
|
447
|
+
id: "openrouter",
|
|
448
|
+
label: "OpenRouter",
|
|
449
|
+
baseUrl: "https://openrouter.ai/api",
|
|
450
|
+
models: ["anthropic/claude-sonnet-4.5"],
|
|
451
|
+
authVar: "ANTHROPIC_AUTH_TOKEN",
|
|
452
|
+
keyHint: "sk-or-\u2026"
|
|
453
|
+
},
|
|
454
|
+
{
|
|
455
|
+
id: "deepseek",
|
|
456
|
+
label: "DeepSeek",
|
|
457
|
+
baseUrl: "https://api.deepseek.com/anthropic",
|
|
458
|
+
models: ["deepseek-chat", "deepseek-reasoner"],
|
|
459
|
+
authVar: "ANTHROPIC_AUTH_TOKEN",
|
|
460
|
+
keyHint: "sk-\u2026"
|
|
461
|
+
},
|
|
462
|
+
{
|
|
463
|
+
id: "custom",
|
|
464
|
+
label: "Custom",
|
|
465
|
+
baseUrl: "",
|
|
466
|
+
models: [],
|
|
467
|
+
authVar: "ANTHROPIC_AUTH_TOKEN",
|
|
468
|
+
noteKey: "presetCustomClaude"
|
|
469
|
+
}
|
|
470
|
+
];
|
|
471
|
+
var CODEX_PRESETS = [
|
|
472
|
+
{
|
|
473
|
+
id: "openai",
|
|
474
|
+
label: "OpenAI",
|
|
475
|
+
baseUrl: "https://api.openai.com/v1",
|
|
476
|
+
models: ["gpt-6-sol", "gpt-5-codex"],
|
|
477
|
+
keyHint: "sk-\u2026"
|
|
478
|
+
},
|
|
479
|
+
{
|
|
480
|
+
id: "openrouter",
|
|
481
|
+
label: "OpenRouter",
|
|
482
|
+
baseUrl: "https://openrouter.ai/api/v1",
|
|
483
|
+
models: ["openai/gpt-5", "anthropic/claude-sonnet-4.5"],
|
|
484
|
+
keyHint: "sk-or-\u2026"
|
|
485
|
+
},
|
|
486
|
+
{
|
|
487
|
+
id: "deepseek",
|
|
488
|
+
label: "DeepSeek",
|
|
489
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
490
|
+
models: ["deepseek-chat"],
|
|
491
|
+
keyHint: "sk-\u2026",
|
|
492
|
+
noteKey: "presetDeepseekCodex"
|
|
493
|
+
},
|
|
494
|
+
{
|
|
495
|
+
id: "custom",
|
|
496
|
+
label: "Custom",
|
|
497
|
+
baseUrl: "",
|
|
498
|
+
models: [],
|
|
499
|
+
noteKey: "presetCustomCodex"
|
|
500
|
+
}
|
|
501
|
+
];
|
|
502
|
+
function presetsFor(agent) {
|
|
503
|
+
if (agent === "claude") return CLAUDE_PRESETS;
|
|
504
|
+
if (agent === "codex") return CODEX_PRESETS;
|
|
505
|
+
return [];
|
|
506
|
+
}
|
|
507
|
+
function claudeAuthVar(presetId) {
|
|
508
|
+
return CLAUDE_PRESETS.find((p) => p.id === presetId)?.authVar ?? "ANTHROPIC_AUTH_TOKEN";
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// src/desktop/claude.ts
|
|
512
|
+
function toMcpEntry(j) {
|
|
513
|
+
if (!j || typeof j.command !== "string") return null;
|
|
514
|
+
const env = {};
|
|
515
|
+
for (const [k, v] of Object.entries(j.env ?? {})) if (typeof v === "string") env[k] = v;
|
|
516
|
+
return { command: j.command, args: Array.isArray(j.args) ? j.args.map(String) : [], env };
|
|
517
|
+
}
|
|
518
|
+
function addMcpEntry(runner, e) {
|
|
519
|
+
const envArgs = Object.entries(e.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
|
|
520
|
+
return runner.run("claude", ["mcp", "add", "moneyswitch", "-s", "user", ...envArgs, "--", e.command, ...e.args]);
|
|
521
|
+
}
|
|
522
|
+
function parseJsonObject(text, file) {
|
|
523
|
+
if (text === null || text.trim() === "") return {};
|
|
524
|
+
let v;
|
|
525
|
+
try {
|
|
526
|
+
v = JSON.parse(text);
|
|
527
|
+
} catch (e) {
|
|
528
|
+
throw new AgentConfigError("PARSE_FAILED", `${file} is not valid JSON (${e.message}); fix it by hand first \u2014 nothing was written.`);
|
|
529
|
+
}
|
|
530
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) throw new AgentConfigError("PARSE_FAILED", `${file} is not a JSON object; nothing was written.`);
|
|
531
|
+
return v;
|
|
532
|
+
}
|
|
533
|
+
var AgentConfigError = class extends Error {
|
|
534
|
+
constructor(code, message, detail) {
|
|
535
|
+
super(message);
|
|
536
|
+
this.code = code;
|
|
537
|
+
this.detail = detail;
|
|
538
|
+
}
|
|
539
|
+
code;
|
|
540
|
+
detail;
|
|
541
|
+
};
|
|
542
|
+
function envOf(settings) {
|
|
543
|
+
const e = settings.env;
|
|
544
|
+
return e && typeof e === "object" && !Array.isArray(e) ? e : {};
|
|
545
|
+
}
|
|
546
|
+
function str(v) {
|
|
547
|
+
return typeof v === "string" ? v : v == null ? null : String(v);
|
|
548
|
+
}
|
|
549
|
+
function brainEnv(brain) {
|
|
550
|
+
const authVar = claudeAuthVar(brain.preset);
|
|
551
|
+
const other = authVar === "ANTHROPIC_API_KEY" ? "ANTHROPIC_AUTH_TOKEN" : "ANTHROPIC_API_KEY";
|
|
552
|
+
const out = {
|
|
553
|
+
ANTHROPIC_BASE_URL: brain.baseUrl.replace(/\/+$/, ""),
|
|
554
|
+
[authVar]: brain.apiKey,
|
|
555
|
+
// Remove the other auth variable so Claude Code cannot pick a stale key for this endpoint.
|
|
556
|
+
[other]: null
|
|
557
|
+
};
|
|
558
|
+
if (brain.model.trim()) out.ANTHROPIC_MODEL = brain.model.trim();
|
|
559
|
+
return out;
|
|
560
|
+
}
|
|
561
|
+
function readMcpEntry(env) {
|
|
562
|
+
const file = claudeJsonPath(env);
|
|
563
|
+
const text = readIfExists(file);
|
|
564
|
+
if (text === null) return null;
|
|
565
|
+
try {
|
|
566
|
+
const j = JSON.parse(text);
|
|
567
|
+
const servers = j.mcpServers;
|
|
568
|
+
const entry = servers?.moneyswitch;
|
|
569
|
+
return entry && typeof entry === "object" ? entry : null;
|
|
570
|
+
} catch {
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function mcpFields(entry) {
|
|
575
|
+
if (!entry) return { command: null, base: null, key: null };
|
|
576
|
+
const args = Array.isArray(entry.args) ? entry.args.map(String) : [];
|
|
577
|
+
const e = entry.env ?? {};
|
|
578
|
+
return {
|
|
579
|
+
command: [str(entry.command) ?? "", ...args].join(" ").trim() || null,
|
|
580
|
+
base: str(e.MONEY_API_BASE),
|
|
581
|
+
key: str(e.MONEY_API_KEY)
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
function prevOf(applied) {
|
|
585
|
+
return applied ? applied.previous : null;
|
|
586
|
+
}
|
|
587
|
+
function desiredEnv(target, prev) {
|
|
588
|
+
const want = target.brain ? brainEnv(target.brain) : {};
|
|
589
|
+
for (const [k, v] of Object.entries(prev?.env ?? {})) if (!(k in want)) want[k] = v;
|
|
590
|
+
return want;
|
|
591
|
+
}
|
|
592
|
+
function planClaude(env, action, target, applied) {
|
|
593
|
+
const settingsPath = claudeSettingsPath(env);
|
|
594
|
+
const settingsText = readIfExists(settingsPath);
|
|
595
|
+
const settings = parseJsonObject(settingsText, displayPath(settingsPath, env));
|
|
596
|
+
const curEnv = envOf(settings);
|
|
597
|
+
const prev = prevOf(applied);
|
|
598
|
+
const warnings = [];
|
|
599
|
+
const want = action === "enable" && target ? desiredEnv(target, prev) : { ...prev?.env ?? {} };
|
|
600
|
+
const envChanges = Object.keys(want).sort().map((k) => fieldChange(`env.${k}`, str(curEnv[k]), want[k], /KEY|TOKEN/.test(k)));
|
|
601
|
+
const files = [];
|
|
602
|
+
if (envChanges.some((c) => c.op !== "same")) {
|
|
603
|
+
files.push({ path: settingsPath, display: displayPath(settingsPath, env), exists: settingsText !== null, writer: "moneyswitch", changes: envChanges });
|
|
604
|
+
}
|
|
605
|
+
const commands = [];
|
|
606
|
+
const cur = mcpFields(readMcpEntry(env));
|
|
607
|
+
const jsonPath = claudeJsonPath(env);
|
|
608
|
+
const wantWallet = action === "enable" && target?.wallet ? target.wallet : null;
|
|
609
|
+
if (wantWallet && target) {
|
|
610
|
+
const cmd = [target.mcpCommand.command, ...target.mcpCommand.args].join(" ");
|
|
611
|
+
const changes = [
|
|
612
|
+
fieldChange("mcpServers.moneyswitch.command", cur.command, cmd),
|
|
613
|
+
fieldChange("mcpServers.moneyswitch.env.MONEY_API_BASE", cur.base, wantWallet.server),
|
|
614
|
+
fieldChange("mcpServers.moneyswitch.env.MONEY_API_KEY", cur.key, wantWallet.key, true)
|
|
615
|
+
];
|
|
616
|
+
if (changes.some((c) => c.op !== "same")) {
|
|
617
|
+
files.push({ path: jsonPath, display: displayPath(jsonPath, env), exists: readIfExists(jsonPath) !== null, writer: "agent-cli", changes });
|
|
618
|
+
commands.push({
|
|
619
|
+
display: `claude mcp remove moneyswitch -s user`,
|
|
620
|
+
why: "replace"
|
|
621
|
+
});
|
|
622
|
+
commands.push({
|
|
623
|
+
display: `claude mcp add moneyswitch -s user -e MONEY_API_BASE=${wantWallet.server} -e MONEY_API_KEY=${maskSecret(wantWallet.key)} -- ${cmd}`,
|
|
624
|
+
why: "add"
|
|
625
|
+
});
|
|
626
|
+
if (cur.key && !prev?.mcpExisted && !applied?.parts.wallet) warnings.push("claudeReplacesExistingMcp");
|
|
627
|
+
}
|
|
628
|
+
} else if (applied?.parts.wallet && cur.key !== null) {
|
|
629
|
+
const restore = prev?.mcpEntry ?? null;
|
|
630
|
+
const r = restore ? { command: [restore.command, ...restore.args].join(" "), base: restore.env.MONEY_API_BASE ?? null, key: restore.env.MONEY_API_KEY ?? null } : { command: null, base: null, key: null };
|
|
631
|
+
files.push({
|
|
632
|
+
path: jsonPath,
|
|
633
|
+
display: displayPath(jsonPath, env),
|
|
634
|
+
exists: true,
|
|
635
|
+
writer: "agent-cli",
|
|
636
|
+
changes: [
|
|
637
|
+
fieldChange("mcpServers.moneyswitch.command", cur.command, r.command),
|
|
638
|
+
fieldChange("mcpServers.moneyswitch.env.MONEY_API_BASE", cur.base, r.base),
|
|
639
|
+
fieldChange("mcpServers.moneyswitch.env.MONEY_API_KEY", cur.key, r.key, true)
|
|
640
|
+
]
|
|
641
|
+
});
|
|
642
|
+
commands.push({ display: "claude mcp remove moneyswitch -s user", why: "remove" });
|
|
643
|
+
if (restore) {
|
|
644
|
+
const envShown = Object.entries(restore.env).map(([k, v]) => `-e ${k}=${/KEY|TOKEN/.test(k) ? maskSecret(v) : v}`).join(" ");
|
|
645
|
+
commands.push({ display: `claude mcp add moneyswitch -s user ${envShown} -- ${r.command}`, why: "restore" });
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
const noop = files.length === 0 && commands.length === 0;
|
|
649
|
+
const inputHash = sha256(stableStringify({ settings: settingsText, mcp: cur }));
|
|
650
|
+
return { plan: { agent: "claude", action, files, commands, warnings, noop }, inputHash };
|
|
651
|
+
}
|
|
652
|
+
function claudeFingerprint(env, managedEnvKeys, walletManaged) {
|
|
653
|
+
const settings = (() => {
|
|
654
|
+
try {
|
|
655
|
+
return parseJsonObject(readIfExists(claudeSettingsPath(env)), "settings.json");
|
|
656
|
+
} catch {
|
|
657
|
+
return {};
|
|
658
|
+
}
|
|
659
|
+
})();
|
|
660
|
+
const e = envOf(settings);
|
|
661
|
+
const vals = {};
|
|
662
|
+
for (const k of [...managedEnvKeys].sort()) vals[k] = str(e[k]);
|
|
663
|
+
const mcp = walletManaged ? mcpFields(readMcpEntry(env)) : null;
|
|
664
|
+
return sha256(stableStringify({ env: vals, mcp: mcp ? { base: mcp.base, key: mcp.key } : null }));
|
|
665
|
+
}
|
|
666
|
+
function applyClaudePlan(env, action, target, applied, runner, now = /* @__PURE__ */ new Date()) {
|
|
667
|
+
const settingsPath = claudeSettingsPath(env);
|
|
668
|
+
const jsonPath = claudeJsonPath(env);
|
|
669
|
+
const settingsText = readIfExists(settingsPath);
|
|
670
|
+
const settings = parseJsonObject(settingsText, displayPath(settingsPath, env));
|
|
671
|
+
const curEnv = { ...envOf(settings) };
|
|
672
|
+
const prevRec = prevOf(applied);
|
|
673
|
+
const previous = prevRec ? { ...prevRec, env: { ...prevRec.env } } : { settingsExisted: settingsText !== null, hadEnv: settings.env !== void 0, env: {}, mcpExisted: readMcpEntry(env) !== null, mcpEntry: toMcpEntry(readMcpEntry(env)) };
|
|
674
|
+
const want = action === "enable" && target ? desiredEnv(target, prevRec) : { ...prevRec?.env ?? {} };
|
|
675
|
+
if (action === "enable") {
|
|
676
|
+
for (const k of Object.keys(want)) if (!(k in previous.env)) previous.env[k] = str(curEnv[k]);
|
|
677
|
+
}
|
|
678
|
+
const tx = new FileTransaction(now.getTime());
|
|
679
|
+
try {
|
|
680
|
+
const nextEnv = { ...curEnv };
|
|
681
|
+
for (const [k, v] of Object.entries(want)) {
|
|
682
|
+
if (v === null) delete nextEnv[k];
|
|
683
|
+
else nextEnv[k] = v;
|
|
684
|
+
}
|
|
685
|
+
const envChanged = stableStringify(nextEnv) !== stableStringify(curEnv);
|
|
686
|
+
if (envChanged) {
|
|
687
|
+
const next = { ...settings };
|
|
688
|
+
if (Object.keys(nextEnv).length === 0 && action === "disable" && !previous.hadEnv) delete next.env;
|
|
689
|
+
else next.env = nextEnv;
|
|
690
|
+
const restoreToNothing = action === "disable" && !previous.settingsExisted && Object.keys(next).length === 0;
|
|
691
|
+
if (restoreToNothing) {
|
|
692
|
+
tx.remove(settingsPath);
|
|
693
|
+
} else {
|
|
694
|
+
tx.write(settingsPath, JSON.stringify(next, null, 2) + "\n", (onDisk) => {
|
|
695
|
+
const back = envOf(JSON.parse(onDisk));
|
|
696
|
+
for (const [k, v] of Object.entries(want)) {
|
|
697
|
+
if (v === null && k in back || v !== null && back[k] !== v) {
|
|
698
|
+
throw new AgentConfigError("VERIFY_FAILED", `settings.json read-back: ${k} is not what was written`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
const wallet = action === "enable" && target?.wallet ? target.wallet : null;
|
|
705
|
+
const hadOurWallet = applied?.parts.wallet ?? false;
|
|
706
|
+
if (wallet && target) {
|
|
707
|
+
const cur = mcpFields(readMcpEntry(env));
|
|
708
|
+
const cmd = [target.mcpCommand.command, ...target.mcpCommand.args].join(" ");
|
|
709
|
+
if (cur.key !== wallet.key || cur.base !== wallet.server || cur.command !== cmd) {
|
|
710
|
+
tx.snapshot(jsonPath);
|
|
711
|
+
const res = applyClaude(runner, wallet.server, wallet.key, target.mcpCommand);
|
|
712
|
+
if (!res.added.ok) {
|
|
713
|
+
throw new AgentConfigError(
|
|
714
|
+
/not recognized|not found|ENOENT|不是内部或外部命令/i.test(res.added.stderr) ? "NOT_INSTALLED" : "CLI_FAILED",
|
|
715
|
+
`claude mcp add failed: ${(res.added.stderr || res.added.stdout).trim().slice(0, 400)}`
|
|
716
|
+
);
|
|
717
|
+
}
|
|
718
|
+
const after = mcpFields(readMcpEntry(env));
|
|
719
|
+
if (after.key !== wallet.key || after.base !== wallet.server) {
|
|
720
|
+
throw new AgentConfigError("VERIFY_FAILED", `claude mcp add reported success but ${displayPath(jsonPath, env)} has no matching mcpServers.moneyswitch`);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
} else if (hadOurWallet && readMcpEntry(env) !== null) {
|
|
724
|
+
tx.snapshot(jsonPath);
|
|
725
|
+
const res = removeClaude(runner);
|
|
726
|
+
if (!res.ok || readMcpEntry(env) !== null) {
|
|
727
|
+
throw new AgentConfigError("CLI_FAILED", `claude mcp remove failed: ${(res.stderr || res.stdout).trim().slice(0, 400)}`);
|
|
728
|
+
}
|
|
729
|
+
const restore = previous.mcpEntry ?? null;
|
|
730
|
+
if (restore) {
|
|
731
|
+
const r = addMcpEntry(runner, restore);
|
|
732
|
+
const back = toMcpEntry(readMcpEntry(env));
|
|
733
|
+
if (!r.ok || !back || back.env.MONEY_API_KEY !== restore.env.MONEY_API_KEY) {
|
|
734
|
+
throw new AgentConfigError("CLI_FAILED", `restoring the previous moneyswitch MCP entry failed: ${(r.stderr || r.stdout).trim().slice(0, 400)}`);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (action === "disable") return { applied: null, backups: tx.backups };
|
|
739
|
+
const managedKeys = Object.keys(want);
|
|
740
|
+
const record = {
|
|
741
|
+
at: now.toISOString(),
|
|
742
|
+
backups: [...applied?.backups ?? [], ...tx.backups],
|
|
743
|
+
fingerprint: claudeFingerprint(env, managedKeys, Boolean(wallet)),
|
|
744
|
+
previous,
|
|
745
|
+
parts: { brain: Boolean(target?.brain), wallet: Boolean(wallet) },
|
|
746
|
+
server: wallet?.server
|
|
747
|
+
};
|
|
748
|
+
return { applied: record, backups: tx.backups };
|
|
749
|
+
} catch (e) {
|
|
750
|
+
const rbErrors = tx.rollback();
|
|
751
|
+
if (rbErrors.length) e.message += ` (rollback problems: ${rbErrors.join("; ")})`;
|
|
752
|
+
throw e;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
function claudeManagedKeys(applied) {
|
|
756
|
+
return Object.keys(applied.previous.env ?? {});
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
|
|
760
|
+
function getLineColFromPtr(string, ptr) {
|
|
761
|
+
let lines = string.slice(0, ptr).split(/\r?\n/);
|
|
762
|
+
return [lines.length, lines.pop().length + 1];
|
|
763
|
+
}
|
|
764
|
+
function makeCodeBlock(string, line, column) {
|
|
765
|
+
let lines = string.split(/\r?\n/);
|
|
766
|
+
let codeblock = "";
|
|
767
|
+
let numberLen = (Math.log10(line + 1) | 0) + 1;
|
|
768
|
+
for (let i = line - 1; i <= line + 1; i++) {
|
|
769
|
+
let l = lines[i - 1];
|
|
770
|
+
if (!l)
|
|
771
|
+
continue;
|
|
772
|
+
codeblock += i.toString().padEnd(numberLen, " ");
|
|
773
|
+
codeblock += ": ";
|
|
774
|
+
codeblock += l;
|
|
775
|
+
codeblock += "\n";
|
|
776
|
+
if (i === line) {
|
|
777
|
+
codeblock += " ".repeat(numberLen + column + 2);
|
|
778
|
+
codeblock += "^\n";
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
return codeblock;
|
|
782
|
+
}
|
|
783
|
+
var TomlError = class _TomlError extends Error {
|
|
784
|
+
line;
|
|
785
|
+
column;
|
|
786
|
+
codeblock;
|
|
787
|
+
constructor(message, options) {
|
|
788
|
+
const [line, column] = getLineColFromPtr(options.toml, options.ptr);
|
|
789
|
+
const codeblock = makeCodeBlock(options.toml, line, column);
|
|
790
|
+
super(`Invalid TOML document: ${message}
|
|
791
|
+
|
|
792
|
+
${codeblock}`, options);
|
|
793
|
+
this.line = line;
|
|
794
|
+
this.column = column;
|
|
795
|
+
this.codeblock = codeblock;
|
|
796
|
+
}
|
|
797
|
+
/** @internal */
|
|
798
|
+
static x(message, ctx, ptr) {
|
|
799
|
+
throw new _TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/primitive.js
|
|
804
|
+
function parseString(ctx) {
|
|
805
|
+
let startPtr = ctx.p;
|
|
806
|
+
let c = ctx.s.charCodeAt(ctx.p++);
|
|
807
|
+
let first = c;
|
|
808
|
+
let isLiteral = c === 39;
|
|
809
|
+
let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
|
|
810
|
+
if (isMultiline) {
|
|
811
|
+
if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
|
|
812
|
+
ctx.p++;
|
|
813
|
+
else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
|
|
814
|
+
ctx.p += 2;
|
|
815
|
+
}
|
|
816
|
+
let parsed = "";
|
|
817
|
+
let sliceStart = ctx.p;
|
|
818
|
+
let state = 0;
|
|
819
|
+
for (; ctx.p < ctx.s.length; ctx.p++) {
|
|
820
|
+
c = ctx.s.charCodeAt(ctx.p);
|
|
821
|
+
if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
|
|
822
|
+
state = state && 3;
|
|
823
|
+
} else if (c < 32 && c !== 9 || c === 127) {
|
|
824
|
+
TomlError.x("control characters are not allowed in strings", ctx);
|
|
825
|
+
} else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
|
|
826
|
+
if (isMultiline) {
|
|
827
|
+
if (ctx.s.charCodeAt(ctx.p + 3) === first)
|
|
828
|
+
ctx.p++;
|
|
829
|
+
if (ctx.s.charCodeAt(ctx.p + 3) === first)
|
|
830
|
+
ctx.p++;
|
|
831
|
+
}
|
|
832
|
+
if (!state) {
|
|
833
|
+
let s = ctx.s.slice(sliceStart, ctx.p);
|
|
834
|
+
parsed = parsed ? parsed + s : s;
|
|
835
|
+
}
|
|
836
|
+
ctx.p += isMultiline ? 3 : 1;
|
|
837
|
+
return parsed;
|
|
838
|
+
} else if (!state) {
|
|
839
|
+
if (!isLiteral && c === 92) {
|
|
840
|
+
parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
|
|
841
|
+
state = 1;
|
|
842
|
+
}
|
|
843
|
+
} else if (state === 1) {
|
|
844
|
+
if (c === 120 || c === 117 || c === 85) {
|
|
845
|
+
let errPtr = ctx.p++ - 1;
|
|
846
|
+
let value = 0;
|
|
847
|
+
let len = c === 120 ? 2 : c === 117 ? 4 : 8;
|
|
848
|
+
for (let j = 0; j < len; j++, ctx.p++) {
|
|
849
|
+
let hex = ctx.s.charCodeAt(ctx.p);
|
|
850
|
+
let digit = (
|
|
851
|
+
/* 0-9 */
|
|
852
|
+
hex >= 48 && hex <= 57 ? hex - 48 : (
|
|
853
|
+
/* A-F */
|
|
854
|
+
hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
|
|
855
|
+
/* a-f */
|
|
856
|
+
hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
|
|
857
|
+
)
|
|
858
|
+
)
|
|
859
|
+
);
|
|
860
|
+
if (digit < 0)
|
|
861
|
+
TomlError.x("invalid non-hex character in unicode escape", ctx);
|
|
862
|
+
value = value << 4 | digit;
|
|
863
|
+
}
|
|
864
|
+
if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
|
|
865
|
+
TomlError.x("invalid unicode escape", ctx, errPtr);
|
|
866
|
+
}
|
|
867
|
+
parsed += String.fromCodePoint(value);
|
|
868
|
+
sliceStart = ctx.p--;
|
|
869
|
+
state = 0;
|
|
870
|
+
} else if (isMultiline && (c === 32 || c === 9)) {
|
|
871
|
+
state = 2;
|
|
872
|
+
} else {
|
|
873
|
+
if (c === 98)
|
|
874
|
+
parsed += "\b";
|
|
875
|
+
else if (c === 116)
|
|
876
|
+
parsed += " ";
|
|
877
|
+
else if (c === 110)
|
|
878
|
+
parsed += "\n";
|
|
879
|
+
else if (c === 102)
|
|
880
|
+
parsed += "\f";
|
|
881
|
+
else if (c === 114)
|
|
882
|
+
parsed += "\r";
|
|
883
|
+
else if (c === 101)
|
|
884
|
+
parsed += "\x1B";
|
|
885
|
+
else if (c === 34)
|
|
886
|
+
parsed += '"';
|
|
887
|
+
else if (c === 92)
|
|
888
|
+
parsed += "\\";
|
|
889
|
+
else
|
|
890
|
+
TomlError.x("unrecognised escape sequence", ctx);
|
|
891
|
+
sliceStart = ctx.p + 1;
|
|
892
|
+
state = 0;
|
|
893
|
+
}
|
|
894
|
+
} else if (c !== 32 && c !== 9) {
|
|
895
|
+
if (state === 2)
|
|
896
|
+
TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
|
|
897
|
+
state = !isLiteral && c === 92 ? 1 : 0;
|
|
898
|
+
sliceStart = ctx.p;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
TomlError.x("unfinished string", ctx, startPtr);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/date.js
|
|
905
|
+
var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
|
|
906
|
+
var TomlDate = class _TomlDate extends Date {
|
|
907
|
+
#hasDate = false;
|
|
908
|
+
#hasTime = false;
|
|
909
|
+
#offset = null;
|
|
910
|
+
constructor(date, fasttype, unsafeDelim) {
|
|
911
|
+
let hasDate = true;
|
|
912
|
+
let hasTime = true;
|
|
913
|
+
let offset = "Z";
|
|
914
|
+
let c;
|
|
915
|
+
if (typeof date === "string") {
|
|
916
|
+
if (fasttype)
|
|
917
|
+
prep: {
|
|
918
|
+
if (fasttype < 3) {
|
|
919
|
+
if (+date.slice(11, 13) > 23) {
|
|
920
|
+
date = "";
|
|
921
|
+
break prep;
|
|
922
|
+
}
|
|
923
|
+
if (fasttype === 2) {
|
|
924
|
+
offset = null;
|
|
925
|
+
date += "Z";
|
|
926
|
+
} else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
|
|
927
|
+
offset = date.slice(date.length - 6);
|
|
928
|
+
}
|
|
929
|
+
if (unsafeDelim)
|
|
930
|
+
date = date.slice(0, 10) + "T" + date.slice(11);
|
|
931
|
+
} else if (fasttype === 4) {
|
|
932
|
+
date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
|
|
933
|
+
}
|
|
934
|
+
hasDate = fasttype !== 4;
|
|
935
|
+
hasTime = fasttype !== 3;
|
|
936
|
+
}
|
|
937
|
+
else {
|
|
938
|
+
let match = date.match(DATE_TIME_RE);
|
|
939
|
+
if (match) {
|
|
940
|
+
if (!match[1]) {
|
|
941
|
+
hasDate = false;
|
|
942
|
+
date = `0000-01-01T${date}`;
|
|
943
|
+
}
|
|
944
|
+
hasTime = !!match[2];
|
|
945
|
+
hasTime && date[10] === " " && (date = date.replace(" ", "T"));
|
|
946
|
+
if (match[2] && +match[2] > 23) {
|
|
947
|
+
date = "";
|
|
948
|
+
} else {
|
|
949
|
+
offset = match[3] || null;
|
|
950
|
+
if (!offset && hasTime)
|
|
951
|
+
date += "Z";
|
|
952
|
+
}
|
|
953
|
+
} else {
|
|
954
|
+
date = "";
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
super(date);
|
|
959
|
+
if (!isNaN(this.getTime())) {
|
|
960
|
+
this.#hasDate = hasDate;
|
|
961
|
+
this.#hasTime = hasTime;
|
|
962
|
+
this.#offset = offset;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
isDateTime() {
|
|
966
|
+
return this.#hasDate && this.#hasTime;
|
|
967
|
+
}
|
|
968
|
+
isLocal() {
|
|
969
|
+
return !this.#hasDate || !this.#hasTime || !this.#offset;
|
|
970
|
+
}
|
|
971
|
+
isDate() {
|
|
972
|
+
return this.#hasDate && !this.#hasTime;
|
|
973
|
+
}
|
|
974
|
+
isTime() {
|
|
975
|
+
return this.#hasTime && !this.#hasDate;
|
|
976
|
+
}
|
|
977
|
+
isValid() {
|
|
978
|
+
return this.#hasDate || this.#hasTime;
|
|
979
|
+
}
|
|
980
|
+
toISOString() {
|
|
981
|
+
let iso = super.toISOString();
|
|
982
|
+
if (this.isDate())
|
|
983
|
+
return iso.slice(0, 10);
|
|
984
|
+
if (this.isTime())
|
|
985
|
+
return iso.slice(11, 23);
|
|
986
|
+
if (this.#offset === null)
|
|
987
|
+
return iso.slice(0, -1);
|
|
988
|
+
if (this.#offset === "Z" || this.#offset === "z")
|
|
989
|
+
return iso;
|
|
990
|
+
let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
|
|
991
|
+
offset = this.#offset[0] === "-" ? offset : -offset;
|
|
992
|
+
let offsetDate = new Date(this.getTime() - offset * 6e4);
|
|
993
|
+
return offsetDate.toISOString().slice(0, -1) + this.#offset;
|
|
994
|
+
}
|
|
995
|
+
static wrapAsOffsetDateTime(jsDate, offset = "Z") {
|
|
996
|
+
let date = new _TomlDate(jsDate);
|
|
997
|
+
date.#offset = offset;
|
|
998
|
+
return date;
|
|
999
|
+
}
|
|
1000
|
+
static wrapAsLocalDateTime(jsDate) {
|
|
1001
|
+
let date = new _TomlDate(jsDate);
|
|
1002
|
+
date.#offset = null;
|
|
1003
|
+
return date;
|
|
1004
|
+
}
|
|
1005
|
+
static wrapAsLocalDate(jsDate) {
|
|
1006
|
+
let date = new _TomlDate(jsDate);
|
|
1007
|
+
date.#hasTime = false;
|
|
1008
|
+
date.#offset = null;
|
|
1009
|
+
return date;
|
|
1010
|
+
}
|
|
1011
|
+
static wrapAsLocalTime(jsDate) {
|
|
1012
|
+
let date = new _TomlDate(jsDate);
|
|
1013
|
+
date.#hasDate = false;
|
|
1014
|
+
date.#offset = null;
|
|
1015
|
+
return date;
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
|
|
1019
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/extract.js
|
|
1020
|
+
function isDigit(char, base = 10) {
|
|
1021
|
+
return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
|
|
1022
|
+
}
|
|
1023
|
+
function isEndOfValue(char, delim) {
|
|
1024
|
+
return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
|
|
1025
|
+
delim && (char === delim || char === 44) || // Comment
|
|
1026
|
+
char === 35;
|
|
1027
|
+
}
|
|
1028
|
+
function extractValue(ctx, end) {
|
|
1029
|
+
let errPtr = ctx.p;
|
|
1030
|
+
let c = ctx.s.charCodeAt(ctx.p);
|
|
1031
|
+
if (c === 91 || c === 123) {
|
|
1032
|
+
ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
|
|
1033
|
+
let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
|
|
1034
|
+
ctx.d++;
|
|
1035
|
+
return value;
|
|
1036
|
+
}
|
|
1037
|
+
if (c === 34 || c === 39) {
|
|
1038
|
+
return parseString(ctx);
|
|
1039
|
+
}
|
|
1040
|
+
if (c === 116) {
|
|
1041
|
+
if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
|
|
1042
|
+
TomlError.x("invalid value", ctx, errPtr);
|
|
1043
|
+
return ctx.p++, true;
|
|
1044
|
+
}
|
|
1045
|
+
if (c === 102) {
|
|
1046
|
+
if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
|
|
1047
|
+
TomlError.x("invalid value", ctx, errPtr);
|
|
1048
|
+
return ctx.p++, false;
|
|
1049
|
+
}
|
|
1050
|
+
if (c === 43 || c === 45) {
|
|
1051
|
+
return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
|
|
1052
|
+
}
|
|
1053
|
+
if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
|
|
1054
|
+
return parseDate(ctx, c, end);
|
|
1055
|
+
}
|
|
1056
|
+
if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
|
|
1057
|
+
return parseTime(ctx, c, end);
|
|
1058
|
+
}
|
|
1059
|
+
return parseNumber(ctx, ctx.p, c, 0, end);
|
|
1060
|
+
}
|
|
1061
|
+
function parseNumber(ctx, startPtr, startChr, sign, endChr) {
|
|
1062
|
+
let c = startChr;
|
|
1063
|
+
let state = 0;
|
|
1064
|
+
let hasUnderscores = false;
|
|
1065
|
+
if (c === 105) {
|
|
1066
|
+
if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
|
|
1067
|
+
TomlError.x("invalid value", ctx, startPtr);
|
|
1068
|
+
return ctx.p++, (sign || 1) / 0;
|
|
1069
|
+
}
|
|
1070
|
+
if (c === 110) {
|
|
1071
|
+
if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
|
|
1072
|
+
TomlError.x("invalid value", ctx, startPtr);
|
|
1073
|
+
return ctx.p++, NaN;
|
|
1074
|
+
}
|
|
1075
|
+
if (c === 48) {
|
|
1076
|
+
if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
|
|
1077
|
+
return ctx.bi === true ? 0n : 0;
|
|
1078
|
+
if (!sign) {
|
|
1079
|
+
if (c === 120)
|
|
1080
|
+
return parseIntegerBaseN(ctx, startPtr, 16, endChr);
|
|
1081
|
+
else if (c === 98)
|
|
1082
|
+
return parseIntegerBaseN(ctx, startPtr, 2, endChr);
|
|
1083
|
+
else if (c === 111)
|
|
1084
|
+
return parseIntegerBaseN(ctx, startPtr, 8, endChr);
|
|
1085
|
+
}
|
|
1086
|
+
if (c === 46)
|
|
1087
|
+
state = 2;
|
|
1088
|
+
else if (c === 101 || c === 69)
|
|
1089
|
+
state = 4;
|
|
1090
|
+
else
|
|
1091
|
+
TomlError.x("illegal leading zero", ctx, startPtr);
|
|
1092
|
+
} else if (!isDigit(c))
|
|
1093
|
+
TomlError.x("invalid value", ctx, startPtr);
|
|
1094
|
+
while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
|
|
1095
|
+
if (!state)
|
|
1096
|
+
state = 1;
|
|
1097
|
+
if (c === 95) {
|
|
1098
|
+
if (!(state & 1))
|
|
1099
|
+
TomlError.x("illegal underscore", ctx);
|
|
1100
|
+
state += 11;
|
|
1101
|
+
hasUnderscores = true;
|
|
1102
|
+
} else if (state === 1 && c === 46)
|
|
1103
|
+
state = 2;
|
|
1104
|
+
else if ((state === 1 || state === 3) && (c === 101 || c === 69))
|
|
1105
|
+
state = 4;
|
|
1106
|
+
else if (state === 4 && (c === 43 || c === 45)) {
|
|
1107
|
+
} else if (!isDigit(c))
|
|
1108
|
+
TomlError.x(`illegal character in numeric literal`, ctx);
|
|
1109
|
+
else if (state > 9)
|
|
1110
|
+
state -= 11;
|
|
1111
|
+
else if (!(state & 1))
|
|
1112
|
+
state++;
|
|
1113
|
+
}
|
|
1114
|
+
if (!state) {
|
|
1115
|
+
let val = (startChr - 48) * (sign || 1);
|
|
1116
|
+
return ctx.bi === true ? BigInt(val) : val;
|
|
1117
|
+
}
|
|
1118
|
+
if (!(state & 1))
|
|
1119
|
+
TomlError.x("unfinished numeric value", ctx, startPtr);
|
|
1120
|
+
let str2 = ctx.s.slice(startPtr, ctx.p);
|
|
1121
|
+
if (hasUnderscores)
|
|
1122
|
+
str2 = str2.replaceAll("_", "");
|
|
1123
|
+
return state > 1 ? parseFloat(str2) : parseInteger(ctx, str2, 10, startPtr);
|
|
1124
|
+
}
|
|
1125
|
+
function parseIntegerBaseN(ctx, startPtr, base, endChr) {
|
|
1126
|
+
let c, underscore = 1;
|
|
1127
|
+
while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
|
|
1128
|
+
if (c === 95) {
|
|
1129
|
+
if (underscore & 1)
|
|
1130
|
+
TomlError.x("illegal underscore", ctx);
|
|
1131
|
+
underscore = 3;
|
|
1132
|
+
} else if (!isDigit(c, base))
|
|
1133
|
+
TomlError.x(`illegal character in numeric literal`, ctx);
|
|
1134
|
+
else if (underscore & 1)
|
|
1135
|
+
underscore--;
|
|
1136
|
+
}
|
|
1137
|
+
if (underscore & 1)
|
|
1138
|
+
TomlError.x("unfinished numeric value", ctx);
|
|
1139
|
+
let str2 = ctx.s.slice(startPtr + 2, ctx.p);
|
|
1140
|
+
if (underscore)
|
|
1141
|
+
str2 = str2.replaceAll("_", "");
|
|
1142
|
+
return parseInteger(ctx, str2, base, startPtr);
|
|
1143
|
+
}
|
|
1144
|
+
function parseInteger(ctx, str2, base, startPtr) {
|
|
1145
|
+
if (ctx.bi !== true)
|
|
1146
|
+
int: {
|
|
1147
|
+
let val = parseInt(str2, base);
|
|
1148
|
+
if (!Number.isSafeInteger(val)) {
|
|
1149
|
+
if (ctx.bi)
|
|
1150
|
+
break int;
|
|
1151
|
+
TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
|
|
1152
|
+
}
|
|
1153
|
+
return val;
|
|
1154
|
+
}
|
|
1155
|
+
return base === 10 ? BigInt(str2) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str2);
|
|
1156
|
+
}
|
|
1157
|
+
function parseDate(ctx, c, endChr) {
|
|
1158
|
+
let startPtr = ctx.p++, unsafeSeparator;
|
|
1159
|
+
if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
|
|
1160
|
+
return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
|
|
1161
|
+
}
|
|
1162
|
+
ctx.p += 5;
|
|
1163
|
+
if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
|
|
1164
|
+
TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
|
|
1165
|
+
if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
|
|
1166
|
+
let t2 = ctx.s.slice(startPtr, ctx.p);
|
|
1167
|
+
return readDate(ctx, t2, 3, false, startPtr);
|
|
1168
|
+
}
|
|
1169
|
+
if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
|
|
1170
|
+
TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
|
|
1171
|
+
if (ctx.s.charCodeAt(ctx.p += 3) === 58)
|
|
1172
|
+
ctx.p += 3;
|
|
1173
|
+
if (ctx.s.charCodeAt(ctx.p) === 46)
|
|
1174
|
+
while (isDigit(ctx.s.charCodeAt(++ctx.p)))
|
|
1175
|
+
;
|
|
1176
|
+
if (c = ctx.s.charCodeAt(ctx.p)) {
|
|
1177
|
+
if (c === 90 || c === 122) {
|
|
1178
|
+
let t2 = ctx.s.slice(startPtr, ++ctx.p);
|
|
1179
|
+
return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
|
|
1180
|
+
}
|
|
1181
|
+
if (c === 43 || c === 45) {
|
|
1182
|
+
let t2 = ctx.s.slice(startPtr, ctx.p += 6);
|
|
1183
|
+
return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
let t = ctx.s.slice(startPtr, ctx.p);
|
|
1187
|
+
return readDate(ctx, t, 2, unsafeSeparator, startPtr);
|
|
1188
|
+
}
|
|
1189
|
+
function parseTime(ctx, c, endChr) {
|
|
1190
|
+
let start = ctx.p;
|
|
1191
|
+
if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
|
|
1192
|
+
return parseNumber(ctx, --ctx.p, c, 0, endChr);
|
|
1193
|
+
}
|
|
1194
|
+
if (ctx.s.charCodeAt(ctx.p += 4) === 58)
|
|
1195
|
+
ctx.p += 3;
|
|
1196
|
+
if (ctx.s.charCodeAt(ctx.p) === 46)
|
|
1197
|
+
while (isDigit(ctx.s.charCodeAt(++ctx.p)))
|
|
1198
|
+
;
|
|
1199
|
+
let t = ctx.s.slice(start, ctx.p);
|
|
1200
|
+
return readDate(ctx, t, 4, false, start);
|
|
1201
|
+
}
|
|
1202
|
+
function readDate(ctx, str2, type, unsafeDelim, errPtr, temporalSuffix) {
|
|
1203
|
+
if (ctx.ld) {
|
|
1204
|
+
let date = new TomlDate(str2, type, unsafeDelim);
|
|
1205
|
+
if (!date.isValid())
|
|
1206
|
+
TomlError.x("invalid date", ctx, errPtr);
|
|
1207
|
+
return date;
|
|
1208
|
+
}
|
|
1209
|
+
try {
|
|
1210
|
+
if (temporalSuffix)
|
|
1211
|
+
str2 += temporalSuffix;
|
|
1212
|
+
switch (type) {
|
|
1213
|
+
case 1:
|
|
1214
|
+
return Temporal.ZonedDateTime.from(str2);
|
|
1215
|
+
case 2:
|
|
1216
|
+
return Temporal.PlainDateTime.from(str2);
|
|
1217
|
+
case 3:
|
|
1218
|
+
return Temporal.PlainDate.from(str2);
|
|
1219
|
+
case 4:
|
|
1220
|
+
return Temporal.PlainTime.from(str2);
|
|
1221
|
+
}
|
|
1222
|
+
} catch (e) {
|
|
1223
|
+
TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/util.js
|
|
1228
|
+
function skipComment(ctx) {
|
|
1229
|
+
for (; ctx.p < ctx.s.length; ctx.p++) {
|
|
1230
|
+
let c = ctx.s.charCodeAt(ctx.p);
|
|
1231
|
+
if (c === 10)
|
|
1232
|
+
break;
|
|
1233
|
+
if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
|
|
1234
|
+
ctx.p++;
|
|
1235
|
+
break;
|
|
1236
|
+
}
|
|
1237
|
+
if (c < 32 && c !== 9 || c === 127) {
|
|
1238
|
+
TomlError.x("control characters are not allowed in comments", ctx);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
function skipVoid(ctx, banNewLines, banComments) {
|
|
1243
|
+
let c;
|
|
1244
|
+
while (ctx.p < ctx.s.length) {
|
|
1245
|
+
while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
|
|
1246
|
+
ctx.p++;
|
|
1247
|
+
if (banComments || c !== 35)
|
|
1248
|
+
break;
|
|
1249
|
+
skipComment(ctx);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/struct.js
|
|
1254
|
+
function parseKey(ctx, end = 61) {
|
|
1255
|
+
let startPtr;
|
|
1256
|
+
let state = 0;
|
|
1257
|
+
let parsed = [];
|
|
1258
|
+
let sliceStart;
|
|
1259
|
+
let c = ctx.s.charCodeAt(startPtr = ctx.p);
|
|
1260
|
+
do {
|
|
1261
|
+
if (c === end) {
|
|
1262
|
+
if (!state)
|
|
1263
|
+
TomlError.x("unexpected end of key", ctx);
|
|
1264
|
+
if (state === 1)
|
|
1265
|
+
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
|
1266
|
+
return ctx.p++, parsed;
|
|
1267
|
+
} else if (c === 46) {
|
|
1268
|
+
if (!state)
|
|
1269
|
+
TomlError.x("illegal empty bare key", ctx);
|
|
1270
|
+
if (state === 1)
|
|
1271
|
+
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
|
1272
|
+
state = 0;
|
|
1273
|
+
} else if (!state && (c === 34 || c === 39)) {
|
|
1274
|
+
if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
|
|
1275
|
+
TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
|
|
1276
|
+
parsed.push(parseString(ctx));
|
|
1277
|
+
state = 2;
|
|
1278
|
+
ctx.p--;
|
|
1279
|
+
} else if (c === 32 || c === 9) {
|
|
1280
|
+
if (state === 1) {
|
|
1281
|
+
parsed.push(ctx.s.slice(sliceStart, ctx.p));
|
|
1282
|
+
state = 2;
|
|
1283
|
+
}
|
|
1284
|
+
} else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
|
|
1285
|
+
TomlError.x("illegal character in key", ctx);
|
|
1286
|
+
} else if (!state) {
|
|
1287
|
+
state = 1;
|
|
1288
|
+
sliceStart = ctx.p;
|
|
1289
|
+
}
|
|
1290
|
+
} while (c = ctx.s.charCodeAt(++ctx.p));
|
|
1291
|
+
TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
|
|
1292
|
+
}
|
|
1293
|
+
function parseInlineTable(ctx) {
|
|
1294
|
+
let startPtr = ctx.p++;
|
|
1295
|
+
let res = /* @__PURE__ */ Object.create(null);
|
|
1296
|
+
let seen = /* @__PURE__ */ new Set();
|
|
1297
|
+
let c;
|
|
1298
|
+
while (ctx.p < ctx.s.length) {
|
|
1299
|
+
skipVoid(ctx);
|
|
1300
|
+
if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
|
|
1301
|
+
ctx.p++;
|
|
1302
|
+
return res;
|
|
1303
|
+
}
|
|
1304
|
+
let k;
|
|
1305
|
+
let t = res;
|
|
1306
|
+
let hasOwn = false;
|
|
1307
|
+
let errPtr = ctx.p;
|
|
1308
|
+
let key = parseKey(ctx);
|
|
1309
|
+
for (let i = 0; i < key.length; i++) {
|
|
1310
|
+
if (i)
|
|
1311
|
+
t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
|
|
1312
|
+
k = key[i];
|
|
1313
|
+
if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
|
|
1314
|
+
TomlError.x("trying to redefine an already defined value", ctx, errPtr);
|
|
1315
|
+
}
|
|
1316
|
+
let unsafe = k === "__proto__";
|
|
1317
|
+
if (ctx.uk && (unsafe || k === "constructor")) {
|
|
1318
|
+
t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
|
|
1319
|
+
break;
|
|
1320
|
+
}
|
|
1321
|
+
if (!hasOwn && unsafe) {
|
|
1322
|
+
Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
if (hasOwn) {
|
|
1326
|
+
TomlError.x("trying to redefine an already defined value", ctx, errPtr);
|
|
1327
|
+
}
|
|
1328
|
+
skipVoid(ctx, true, true);
|
|
1329
|
+
let value = extractValue(
|
|
1330
|
+
ctx,
|
|
1331
|
+
125
|
|
1332
|
+
/* } */
|
|
1333
|
+
);
|
|
1334
|
+
if (t && typeof (t[k] = value) === "object")
|
|
1335
|
+
seen.add(value);
|
|
1336
|
+
skipVoid(ctx);
|
|
1337
|
+
if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
|
|
1338
|
+
return res;
|
|
1339
|
+
}
|
|
1340
|
+
if (c !== 44)
|
|
1341
|
+
TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
|
|
1342
|
+
}
|
|
1343
|
+
TomlError.x("unfinished table", ctx, startPtr);
|
|
1344
|
+
}
|
|
1345
|
+
function parseArray(ctx) {
|
|
1346
|
+
let startPtr = ctx.p++;
|
|
1347
|
+
let res = [];
|
|
1348
|
+
let c;
|
|
1349
|
+
while (ctx.p < ctx.s.length) {
|
|
1350
|
+
skipVoid(ctx);
|
|
1351
|
+
if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
|
|
1352
|
+
ctx.p++;
|
|
1353
|
+
return res;
|
|
1354
|
+
}
|
|
1355
|
+
res.push(extractValue(
|
|
1356
|
+
ctx,
|
|
1357
|
+
93
|
|
1358
|
+
/* ] */
|
|
1359
|
+
));
|
|
1360
|
+
skipVoid(ctx);
|
|
1361
|
+
if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
|
|
1362
|
+
return res;
|
|
1363
|
+
}
|
|
1364
|
+
if (c !== 44)
|
|
1365
|
+
TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
|
|
1366
|
+
}
|
|
1367
|
+
TomlError.x("unfinished array", ctx, startPtr);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/parse.js
|
|
1371
|
+
function peekTable(ctx, key, table, meta, type) {
|
|
1372
|
+
let t = table;
|
|
1373
|
+
let m = meta;
|
|
1374
|
+
let k;
|
|
1375
|
+
let hasOwn = false;
|
|
1376
|
+
let state;
|
|
1377
|
+
for (let i = 0; i < key.length; i++) {
|
|
1378
|
+
if (i) {
|
|
1379
|
+
t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
|
|
1380
|
+
m = (state = m[k]).c;
|
|
1381
|
+
if (type === 0 && (state.t === 1 || state.t === 2)) {
|
|
1382
|
+
return null;
|
|
1383
|
+
}
|
|
1384
|
+
if (state.t === 2) {
|
|
1385
|
+
let l = t.length - 1;
|
|
1386
|
+
t = t[l];
|
|
1387
|
+
m = m[l].c;
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
k = key[i];
|
|
1391
|
+
if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
|
|
1392
|
+
return null;
|
|
1393
|
+
}
|
|
1394
|
+
if (!hasOwn) {
|
|
1395
|
+
let unsafe = k === "__proto__";
|
|
1396
|
+
if (ctx.uk && (unsafe || k === "constructor"))
|
|
1397
|
+
return false;
|
|
1398
|
+
if (unsafe) {
|
|
1399
|
+
Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
|
|
1400
|
+
Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
|
|
1401
|
+
}
|
|
1402
|
+
m[k] = {
|
|
1403
|
+
t: i < key.length - 1 && type === 2 ? 3 : type,
|
|
1404
|
+
d: false,
|
|
1405
|
+
i: 0,
|
|
1406
|
+
c: /* @__PURE__ */ Object.create(null)
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
state = m[k];
|
|
1411
|
+
if (state.t !== type && !(type === 1 && state.t === 3)) {
|
|
1412
|
+
return null;
|
|
1413
|
+
}
|
|
1414
|
+
if (type === 2) {
|
|
1415
|
+
if (!state.d) {
|
|
1416
|
+
state.d = true;
|
|
1417
|
+
t[k] = [];
|
|
1418
|
+
}
|
|
1419
|
+
t[k].push(t = /* @__PURE__ */ Object.create(null));
|
|
1420
|
+
state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
|
|
1421
|
+
}
|
|
1422
|
+
if (state.d) {
|
|
1423
|
+
return null;
|
|
1424
|
+
}
|
|
1425
|
+
state.d = true;
|
|
1426
|
+
if (type === 1) {
|
|
1427
|
+
t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
|
|
1428
|
+
} else if (type === 0 && hasOwn) {
|
|
1429
|
+
return null;
|
|
1430
|
+
}
|
|
1431
|
+
return [k, t, state.c];
|
|
1432
|
+
}
|
|
1433
|
+
function validateTablePeek(ctx, peek, ptr) {
|
|
1434
|
+
if (peek === null || ctx.uk === 2)
|
|
1435
|
+
TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
|
|
1436
|
+
}
|
|
1437
|
+
function parse(toml, options = {}) {
|
|
1438
|
+
let ctx = {
|
|
1439
|
+
s: toml,
|
|
1440
|
+
p: 0,
|
|
1441
|
+
d: options.maxDepth ?? 1e3,
|
|
1442
|
+
bi: options.integersAsBigInt ?? false,
|
|
1443
|
+
ld: options.useLegacyDate ?? true,
|
|
1444
|
+
uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
|
|
1445
|
+
};
|
|
1446
|
+
let res = /* @__PURE__ */ Object.create(null);
|
|
1447
|
+
let meta = /* @__PURE__ */ Object.create(null);
|
|
1448
|
+
let tmp;
|
|
1449
|
+
let skipping = false;
|
|
1450
|
+
let tbl = res;
|
|
1451
|
+
let m = meta;
|
|
1452
|
+
if (toml.charCodeAt(0) === 65279)
|
|
1453
|
+
ctx.p++;
|
|
1454
|
+
skipVoid(ctx);
|
|
1455
|
+
while (ctx.p < toml.length) {
|
|
1456
|
+
if (toml.charCodeAt(ctx.p) === 91) {
|
|
1457
|
+
let isTableArray = toml.charCodeAt(++ctx.p) === 91;
|
|
1458
|
+
tmp = ctx.p += +isTableArray;
|
|
1459
|
+
skipping = false;
|
|
1460
|
+
let k = parseKey(
|
|
1461
|
+
ctx,
|
|
1462
|
+
93
|
|
1463
|
+
/* ] */
|
|
1464
|
+
);
|
|
1465
|
+
if (isTableArray) {
|
|
1466
|
+
if (toml.charCodeAt(ctx.p) !== 93) {
|
|
1467
|
+
TomlError.x("expected end of table array declaration", ctx);
|
|
1468
|
+
}
|
|
1469
|
+
ctx.p++;
|
|
1470
|
+
}
|
|
1471
|
+
let p = peekTable(
|
|
1472
|
+
ctx,
|
|
1473
|
+
k,
|
|
1474
|
+
res,
|
|
1475
|
+
meta,
|
|
1476
|
+
isTableArray ? 2 : 1
|
|
1477
|
+
/* Type.EXPLICIT */
|
|
1478
|
+
);
|
|
1479
|
+
if (!p) {
|
|
1480
|
+
validateTablePeek(ctx, p, tmp);
|
|
1481
|
+
skipping = true;
|
|
1482
|
+
} else {
|
|
1483
|
+
m = p[2];
|
|
1484
|
+
tbl = p[1];
|
|
1485
|
+
}
|
|
1486
|
+
} else {
|
|
1487
|
+
tmp = ctx.p;
|
|
1488
|
+
let k = parseKey(ctx);
|
|
1489
|
+
let p = peekTable(
|
|
1490
|
+
ctx,
|
|
1491
|
+
k,
|
|
1492
|
+
tbl,
|
|
1493
|
+
m,
|
|
1494
|
+
0
|
|
1495
|
+
/* Type.DOTTED */
|
|
1496
|
+
);
|
|
1497
|
+
if (!p && !skipping)
|
|
1498
|
+
validateTablePeek(ctx, p, tmp);
|
|
1499
|
+
skipVoid(ctx, true, true);
|
|
1500
|
+
let v = extractValue(ctx, void 0);
|
|
1501
|
+
if (p && !skipping)
|
|
1502
|
+
p[1][p[0]] = v;
|
|
1503
|
+
}
|
|
1504
|
+
skipVoid(ctx, true);
|
|
1505
|
+
if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
|
|
1506
|
+
TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
|
|
1507
|
+
}
|
|
1508
|
+
skipVoid(ctx);
|
|
1509
|
+
}
|
|
1510
|
+
return res;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
// ../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/stringify.js
|
|
1514
|
+
var HAS_WELLFORMED = !!"".isWellFormed;
|
|
1515
|
+
|
|
1516
|
+
// ../connect/dist/lib/codex.js
|
|
1517
|
+
var TABLE = "mcp_servers.moneyswitch";
|
|
1518
|
+
function tomlEscape(value) {
|
|
1519
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
1520
|
+
}
|
|
1521
|
+
function buildMcpSection(server, key, mcpCommand) {
|
|
1522
|
+
const argsToml = mcpCommand.args.map((a) => `"${tomlEscape(a)}"`).join(", ");
|
|
1523
|
+
return [
|
|
1524
|
+
`[${TABLE}]`,
|
|
1525
|
+
`command = "${tomlEscape(mcpCommand.command)}"`,
|
|
1526
|
+
`args = [${argsToml}]`,
|
|
1527
|
+
"",
|
|
1528
|
+
`[${TABLE}.env]`,
|
|
1529
|
+
`MONEY_API_BASE = "${tomlEscape(server)}"`,
|
|
1530
|
+
`MONEY_API_KEY = "${tomlEscape(key)}"`
|
|
1531
|
+
].join("\n");
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// src/desktop/toml-edit.ts
|
|
1535
|
+
var HEADER_RE = /^\s*\[\[?\s*([^\]]*?)\s*\]\]?\s*(#.*)?$/;
|
|
1536
|
+
function tomlString(v) {
|
|
1537
|
+
return JSON.stringify(v);
|
|
1538
|
+
}
|
|
1539
|
+
function normName(raw) {
|
|
1540
|
+
return raw.split(".").map((p) => p.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1")).join(".");
|
|
1541
|
+
}
|
|
1542
|
+
function scan(text) {
|
|
1543
|
+
const out = [];
|
|
1544
|
+
let table = "";
|
|
1545
|
+
let inMulti = null;
|
|
1546
|
+
for (const text_ of text.split(/\r?\n/)) {
|
|
1547
|
+
const startsInString = inMulti !== null;
|
|
1548
|
+
let isHeader = false;
|
|
1549
|
+
if (!startsInString) {
|
|
1550
|
+
const m = HEADER_RE.exec(text_);
|
|
1551
|
+
if (m) {
|
|
1552
|
+
table = normName(m[1]);
|
|
1553
|
+
isHeader = true;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
let i = 0;
|
|
1557
|
+
while (i < text_.length) {
|
|
1558
|
+
if (inMulti) {
|
|
1559
|
+
const end = text_.indexOf(inMulti, i);
|
|
1560
|
+
if (end === -1) break;
|
|
1561
|
+
inMulti = null;
|
|
1562
|
+
i = end + 3;
|
|
1563
|
+
} else {
|
|
1564
|
+
const a = text_.indexOf('"""', i);
|
|
1565
|
+
const b = text_.indexOf("'''", i);
|
|
1566
|
+
const hash = text_.indexOf("#", i);
|
|
1567
|
+
const cands = [a, b].filter((x) => x !== -1);
|
|
1568
|
+
if (!cands.length) break;
|
|
1569
|
+
const first = Math.min(...cands);
|
|
1570
|
+
if (hash !== -1 && hash < first) break;
|
|
1571
|
+
inMulti = first === a ? '"""' : "'''";
|
|
1572
|
+
i = first + 3;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
out.push({ text: text_, header: table, isHeader, inString: startsInString });
|
|
1576
|
+
}
|
|
1577
|
+
return out;
|
|
1578
|
+
}
|
|
1579
|
+
function belongsTo(table, name) {
|
|
1580
|
+
return table === name || table.startsWith(`${name}.`);
|
|
1581
|
+
}
|
|
1582
|
+
function getTable(text, name) {
|
|
1583
|
+
const lines = scan(text).filter((l) => belongsTo(l.header ?? "", name));
|
|
1584
|
+
if (!lines.length) return null;
|
|
1585
|
+
return lines.map((l) => l.text).join("\n").replace(/\s+$/, "");
|
|
1586
|
+
}
|
|
1587
|
+
function removeTable(text, name) {
|
|
1588
|
+
const kept = scan(text).filter((l) => !belongsTo(l.header ?? "", name)).map((l) => l.text);
|
|
1589
|
+
return tidy(kept.join(eol(text)), eol(text));
|
|
1590
|
+
}
|
|
1591
|
+
function appendTable(text, block) {
|
|
1592
|
+
const nl = eol(text);
|
|
1593
|
+
const base = text.replace(/\s+$/, "");
|
|
1594
|
+
const b = block.replace(/\s+$/, "").replace(/\r?\n/g, nl);
|
|
1595
|
+
return base.length ? `${base}${nl}${nl}${b}${nl}` : `${b}${nl}`;
|
|
1596
|
+
}
|
|
1597
|
+
function tidy(s, nl) {
|
|
1598
|
+
const t = s.replace(/\s+$/, "");
|
|
1599
|
+
return t.length ? `${t}${nl}` : "";
|
|
1600
|
+
}
|
|
1601
|
+
function eol(text) {
|
|
1602
|
+
return text.includes("\r\n") ? "\r\n" : "\n";
|
|
1603
|
+
}
|
|
1604
|
+
var keyRe = (key) => new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=`);
|
|
1605
|
+
function getRootLine(text, key) {
|
|
1606
|
+
const re = keyRe(key);
|
|
1607
|
+
for (const l of scan(text)) {
|
|
1608
|
+
if (l.isHeader) return null;
|
|
1609
|
+
if (!l.inString && re.test(l.text)) return l.text;
|
|
1610
|
+
}
|
|
1611
|
+
return null;
|
|
1612
|
+
}
|
|
1613
|
+
function setRootLine(text, key, line) {
|
|
1614
|
+
const re = keyRe(key);
|
|
1615
|
+
const lines = scan(text);
|
|
1616
|
+
const firstHeader = lines.findIndex((l) => l.isHeader);
|
|
1617
|
+
const rootEnd = firstHeader === -1 ? lines.length : firstHeader;
|
|
1618
|
+
const idx = lines.slice(0, rootEnd).findIndex((l) => !l.inString && re.test(l.text));
|
|
1619
|
+
const texts = lines.map((l) => l.text);
|
|
1620
|
+
if (idx !== -1) {
|
|
1621
|
+
if (line === null) texts.splice(idx, 1);
|
|
1622
|
+
else texts[idx] = line;
|
|
1623
|
+
} else if (line !== null) {
|
|
1624
|
+
let at = rootEnd;
|
|
1625
|
+
while (at > 0 && texts[at - 1].trim() === "") at--;
|
|
1626
|
+
texts.splice(at, 0, line);
|
|
1627
|
+
}
|
|
1628
|
+
return tidy(texts.join(eol(text)), eol(text));
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
// src/desktop/codex.ts
|
|
1632
|
+
var PROVIDER_ID = "moneyswitch_brain";
|
|
1633
|
+
var PROVIDER_TABLE = `model_providers.${PROVIDER_ID}`;
|
|
1634
|
+
var MCP_TABLE = "mcp_servers.moneyswitch";
|
|
1635
|
+
function parse2(text, label) {
|
|
1636
|
+
try {
|
|
1637
|
+
return parse(text);
|
|
1638
|
+
} catch (e) {
|
|
1639
|
+
throw new AgentConfigError("PARSE_FAILED", `${label} is not valid TOML (${e.message.split("\n")[0]}); fix it by hand first \u2014 nothing was written.`);
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
function providerBlock(brain) {
|
|
1643
|
+
return [
|
|
1644
|
+
`[${PROVIDER_TABLE}]`,
|
|
1645
|
+
`name = ${tomlString(`MoneySwitch \xB7 ${brain.preset}`)}`,
|
|
1646
|
+
`base_url = ${tomlString(brain.baseUrl.replace(/\/+$/, ""))}`,
|
|
1647
|
+
`wire_api = "responses"`,
|
|
1648
|
+
`experimental_bearer_token = ${tomlString(brain.apiKey)}`
|
|
1649
|
+
].join("\n");
|
|
1650
|
+
}
|
|
1651
|
+
function stripManaged(doc) {
|
|
1652
|
+
const out = JSON.parse(JSON.stringify(doc));
|
|
1653
|
+
delete out.model;
|
|
1654
|
+
delete out.model_provider;
|
|
1655
|
+
const mp = out.model_providers;
|
|
1656
|
+
if (mp) {
|
|
1657
|
+
delete mp[PROVIDER_ID];
|
|
1658
|
+
if (Object.keys(mp).length === 0) delete out.model_providers;
|
|
1659
|
+
}
|
|
1660
|
+
const ms = out.mcp_servers;
|
|
1661
|
+
if (ms) {
|
|
1662
|
+
delete ms.moneyswitch;
|
|
1663
|
+
if (Object.keys(ms).length === 0) delete out.mcp_servers;
|
|
1664
|
+
}
|
|
1665
|
+
return out;
|
|
1666
|
+
}
|
|
1667
|
+
function get(doc, path7) {
|
|
1668
|
+
let cur = doc;
|
|
1669
|
+
for (const p of path7.split(".")) {
|
|
1670
|
+
if (!cur || typeof cur !== "object") return null;
|
|
1671
|
+
cur = cur[p];
|
|
1672
|
+
}
|
|
1673
|
+
if (cur === void 0 || cur === null) return null;
|
|
1674
|
+
return Array.isArray(cur) ? cur.map(String).join(" ") : String(cur);
|
|
1675
|
+
}
|
|
1676
|
+
function computeEdit(text, action, target, applied) {
|
|
1677
|
+
const prevRec = applied ? applied.previous : null;
|
|
1678
|
+
const previous = prevRec ? { fileExisted: prevRec.fileExisted, root: { ...prevRec.root }, tables: { ...prevRec.tables } } : { fileExisted: text.length > 0, root: {}, tables: {} };
|
|
1679
|
+
const wantRoot = {};
|
|
1680
|
+
const wantTables = {};
|
|
1681
|
+
if (action === "enable" && target) {
|
|
1682
|
+
if (target.brain) {
|
|
1683
|
+
if (target.brain.model.trim()) wantRoot.model = `model = ${tomlString(target.brain.model.trim())}`;
|
|
1684
|
+
wantRoot.model_provider = `model_provider = ${tomlString(PROVIDER_ID)}`;
|
|
1685
|
+
wantTables[PROVIDER_TABLE] = providerBlock(target.brain);
|
|
1686
|
+
}
|
|
1687
|
+
if (target.wallet) wantTables[MCP_TABLE] = buildMcpSection(target.wallet.server, target.wallet.key, target.mcpCommand);
|
|
1688
|
+
}
|
|
1689
|
+
for (const [k, v] of Object.entries(prevRec?.root ?? {})) if (!(k in wantRoot)) wantRoot[k] = v;
|
|
1690
|
+
for (const [k, v] of Object.entries(prevRec?.tables ?? {})) if (!(k in wantTables)) wantTables[k] = v;
|
|
1691
|
+
if (action === "enable") {
|
|
1692
|
+
for (const k of Object.keys(wantRoot)) if (!(k in previous.root)) previous.root[k] = getRootLine(text, k);
|
|
1693
|
+
for (const k of Object.keys(wantTables)) if (!(k in previous.tables)) previous.tables[k] = getTable(text, k);
|
|
1694
|
+
}
|
|
1695
|
+
let after = text;
|
|
1696
|
+
for (const [k, line] of Object.entries(wantRoot)) after = setRootLine(after, k, line);
|
|
1697
|
+
for (const [name, block] of Object.entries(wantTables)) {
|
|
1698
|
+
after = removeTable(after, name);
|
|
1699
|
+
if (block !== null) after = appendTable(after, block);
|
|
1700
|
+
}
|
|
1701
|
+
return { before: text, after, previous, managedRoot: Object.keys(wantRoot), managedTables: Object.keys(wantTables) };
|
|
1702
|
+
}
|
|
1703
|
+
function diffFields(before, after) {
|
|
1704
|
+
const fields = [
|
|
1705
|
+
["model", "model", false],
|
|
1706
|
+
["model_provider", "model_provider", false],
|
|
1707
|
+
[`[${PROVIDER_TABLE}].base_url`, `model_providers.${PROVIDER_ID}.base_url`, false],
|
|
1708
|
+
[`[${PROVIDER_TABLE}].wire_api`, `model_providers.${PROVIDER_ID}.wire_api`, false],
|
|
1709
|
+
[`[${PROVIDER_TABLE}].experimental_bearer_token`, `model_providers.${PROVIDER_ID}.experimental_bearer_token`, true],
|
|
1710
|
+
[`[${MCP_TABLE}].command`, "mcp_servers.moneyswitch.command", false],
|
|
1711
|
+
[`[${MCP_TABLE}].args`, "mcp_servers.moneyswitch.args", false],
|
|
1712
|
+
[`[${MCP_TABLE}.env].MONEY_API_BASE`, "mcp_servers.moneyswitch.env.MONEY_API_BASE", false],
|
|
1713
|
+
[`[${MCP_TABLE}.env].MONEY_API_KEY`, "mcp_servers.moneyswitch.env.MONEY_API_KEY", true]
|
|
1714
|
+
];
|
|
1715
|
+
return fields.map(([label, p, secret]) => fieldChange(label, get(before, p), get(after, p), secret)).filter((c) => c.op !== "same");
|
|
1716
|
+
}
|
|
1717
|
+
function assertOnlyManagedChanged(beforeDoc, afterText, label) {
|
|
1718
|
+
let afterDoc;
|
|
1719
|
+
try {
|
|
1720
|
+
afterDoc = parse(afterText);
|
|
1721
|
+
} catch {
|
|
1722
|
+
throw new AgentConfigError("VERIFY_FAILED", `refusing to write ${label}: the edited file would not parse (unusual file layout). Nothing was written.`);
|
|
1723
|
+
}
|
|
1724
|
+
if (!deepEqual(stripManaged(beforeDoc), stripManaged(afterDoc))) {
|
|
1725
|
+
throw new AgentConfigError("VERIFY_FAILED", `refusing to write ${label}: the edit would change settings MoneySwitch does not own (unusual file layout). Nothing was written.`);
|
|
1726
|
+
}
|
|
1727
|
+
return afterDoc;
|
|
1728
|
+
}
|
|
1729
|
+
function planCodex(env, action, target, applied) {
|
|
1730
|
+
const file = codexConfigFile(env);
|
|
1731
|
+
const label = displayPath(file, env);
|
|
1732
|
+
const raw = readIfExists(file);
|
|
1733
|
+
const text = raw ?? "";
|
|
1734
|
+
const beforeDoc = parse2(text, label);
|
|
1735
|
+
const edit = computeEdit(text, action, target, applied);
|
|
1736
|
+
const afterDoc = assertOnlyManagedChanged(beforeDoc, edit.after, label);
|
|
1737
|
+
const changes = diffFields(beforeDoc, afterDoc);
|
|
1738
|
+
const warnings = [];
|
|
1739
|
+
if (action === "enable" && target?.brain?.preset === "deepseek") warnings.push("codexNeedsResponsesApi");
|
|
1740
|
+
if (action === "enable" && target?.brain && get(beforeDoc, "model_provider") && get(beforeDoc, "model_provider") !== PROVIDER_ID) {
|
|
1741
|
+
warnings.push("codexReplacesProvider");
|
|
1742
|
+
}
|
|
1743
|
+
const files = changes.length ? [{ path: file, display: label, exists: raw !== null, writer: "moneyswitch", changes }] : [];
|
|
1744
|
+
return {
|
|
1745
|
+
plan: { agent: "codex", action, files, commands: [], warnings, noop: files.length === 0 },
|
|
1746
|
+
inputHash: sha256(text)
|
|
1747
|
+
};
|
|
1748
|
+
}
|
|
1749
|
+
function codexFingerprint(env, applied) {
|
|
1750
|
+
const prev = applied.previous;
|
|
1751
|
+
const text = readIfExists(codexConfigFile(env)) ?? "";
|
|
1752
|
+
const vals = {};
|
|
1753
|
+
for (const k of Object.keys(prev.root ?? {}).sort()) vals[`root:${k}`] = getRootLine(text, k);
|
|
1754
|
+
for (const k of Object.keys(prev.tables ?? {}).sort()) {
|
|
1755
|
+
const t = getTable(text, k);
|
|
1756
|
+
vals[`table:${k}`] = t === null ? null : t.replace(/\r\n/g, "\n");
|
|
1757
|
+
}
|
|
1758
|
+
return sha256(stableStringify(vals));
|
|
1759
|
+
}
|
|
1760
|
+
function applyCodexPlan(env, action, target, applied, now = /* @__PURE__ */ new Date()) {
|
|
1761
|
+
const file = codexConfigFile(env);
|
|
1762
|
+
const label = displayPath(file, env);
|
|
1763
|
+
const raw = readIfExists(file);
|
|
1764
|
+
const text = raw ?? "";
|
|
1765
|
+
const beforeDoc = parse2(text, label);
|
|
1766
|
+
const edit = computeEdit(text, action, target, applied);
|
|
1767
|
+
assertOnlyManagedChanged(beforeDoc, edit.after, label);
|
|
1768
|
+
const tx = new FileTransaction(now.getTime());
|
|
1769
|
+
try {
|
|
1770
|
+
if (edit.after !== text) {
|
|
1771
|
+
if (action === "disable" && !edit.previous.fileExisted && edit.after.trim() === "") {
|
|
1772
|
+
tx.remove(file);
|
|
1773
|
+
} else {
|
|
1774
|
+
tx.write(file, edit.after, (onDisk) => {
|
|
1775
|
+
const doc = assertOnlyManagedChanged(beforeDoc, onDisk, label);
|
|
1776
|
+
if (action === "enable" && target?.wallet && get(doc, "mcp_servers.moneyswitch.env.MONEY_API_KEY") !== target.wallet.key) {
|
|
1777
|
+
throw new AgentConfigError("VERIFY_FAILED", `${label} read-back: [mcp_servers.moneyswitch] is not what was written`);
|
|
1778
|
+
}
|
|
1779
|
+
if (action === "enable" && target?.brain && get(doc, "model_provider") !== PROVIDER_ID) {
|
|
1780
|
+
throw new AgentConfigError("VERIFY_FAILED", `${label} read-back: model_provider is not what was written`);
|
|
1781
|
+
}
|
|
1782
|
+
});
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
if (action === "disable") return { applied: null, backups: tx.backups };
|
|
1786
|
+
const record = {
|
|
1787
|
+
at: now.toISOString(),
|
|
1788
|
+
backups: [...applied?.backups ?? [], ...tx.backups],
|
|
1789
|
+
fingerprint: "",
|
|
1790
|
+
previous: edit.previous,
|
|
1791
|
+
parts: { brain: Boolean(target?.brain), wallet: Boolean(target?.wallet) },
|
|
1792
|
+
server: target?.wallet?.server
|
|
1793
|
+
};
|
|
1794
|
+
record.fingerprint = codexFingerprint(env, record);
|
|
1795
|
+
return { applied: record, backups: tx.backups };
|
|
1796
|
+
} catch (e) {
|
|
1797
|
+
const rb = tx.rollback();
|
|
1798
|
+
if (rb.length) e.message += ` (rollback problems: ${rb.join("; ")})`;
|
|
1799
|
+
throw e;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
// src/desktop/money-api.ts
|
|
1804
|
+
var MoneyApiError = class extends Error {
|
|
1805
|
+
constructor(httpStatus, code, message, body) {
|
|
1806
|
+
super(message);
|
|
1807
|
+
this.httpStatus = httpStatus;
|
|
1808
|
+
this.code = code;
|
|
1809
|
+
this.body = body;
|
|
1810
|
+
}
|
|
1811
|
+
httpStatus;
|
|
1812
|
+
code;
|
|
1813
|
+
body;
|
|
1814
|
+
};
|
|
1815
|
+
function normalizeServer(server) {
|
|
1816
|
+
const s = server.trim().replace(/\/+$/, "");
|
|
1817
|
+
const u = new URL(s);
|
|
1818
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("server must be an http(s) URL");
|
|
1819
|
+
return s.replace(/\/v1$/, "");
|
|
1820
|
+
}
|
|
1821
|
+
var MoneyApi = class {
|
|
1822
|
+
constructor(server, key, fetchImpl = fetch, timeoutMs = 1e4) {
|
|
1823
|
+
this.server = server;
|
|
1824
|
+
this.key = key;
|
|
1825
|
+
this.fetchImpl = fetchImpl;
|
|
1826
|
+
this.timeoutMs = timeoutMs;
|
|
1827
|
+
}
|
|
1828
|
+
server;
|
|
1829
|
+
key;
|
|
1830
|
+
fetchImpl;
|
|
1831
|
+
timeoutMs;
|
|
1832
|
+
async call(method, path7, body) {
|
|
1833
|
+
const ctrl = new AbortController();
|
|
1834
|
+
const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
|
|
1835
|
+
let res;
|
|
1836
|
+
try {
|
|
1837
|
+
res = await this.fetchImpl(`${this.server}${path7}`, {
|
|
1838
|
+
method,
|
|
1839
|
+
headers: { Authorization: `Bearer ${this.key}`, ...body !== void 0 ? { "Content-Type": "application/json" } : {} },
|
|
1840
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
1841
|
+
signal: ctrl.signal
|
|
1842
|
+
});
|
|
1843
|
+
} catch (e) {
|
|
1844
|
+
const msg = e.name === "AbortError" ? `timed out after ${this.timeoutMs} ms` : e.message;
|
|
1845
|
+
throw new MoneyApiError(0, "UNREACHABLE", `cannot reach ${this.server}: ${msg}`, null);
|
|
1846
|
+
} finally {
|
|
1847
|
+
clearTimeout(timer);
|
|
1848
|
+
}
|
|
1849
|
+
let json = null;
|
|
1850
|
+
try {
|
|
1851
|
+
json = await res.json();
|
|
1852
|
+
} catch {
|
|
1853
|
+
json = null;
|
|
1854
|
+
}
|
|
1855
|
+
if (!res.ok) {
|
|
1856
|
+
const b = json ?? {};
|
|
1857
|
+
const code = String(b.code ?? b.error ?? `HTTP_${res.status}`);
|
|
1858
|
+
const message = String(b.message ?? b.error ?? `HTTP ${res.status}`);
|
|
1859
|
+
throw new MoneyApiError(res.status, code, message, json);
|
|
1860
|
+
}
|
|
1861
|
+
return json;
|
|
1862
|
+
}
|
|
1863
|
+
status() {
|
|
1864
|
+
return this.call("GET", "/v1/status");
|
|
1865
|
+
}
|
|
1866
|
+
createChild(input) {
|
|
1867
|
+
return this.call("POST", "/v1/keys/children", { ...input, can_delegate: input.can_delegate ?? false });
|
|
1868
|
+
}
|
|
1869
|
+
async listChildren() {
|
|
1870
|
+
const r = await this.call("GET", "/v1/keys/children");
|
|
1871
|
+
return r.children ?? [];
|
|
1872
|
+
}
|
|
1873
|
+
revokeChild(id) {
|
|
1874
|
+
return this.call("POST", `/v1/keys/children/${encodeURIComponent(id)}/revoke`, {});
|
|
1875
|
+
}
|
|
1876
|
+
};
|
|
1877
|
+
function toMicros(v) {
|
|
1878
|
+
const m = /^\s*(\d+)(?:\.(\d{0,6}))?\s*$/.exec(v);
|
|
1879
|
+
if (!m) throw new Error(`not a USDC amount: ${v}`);
|
|
1880
|
+
return BigInt(m[1]) * 1000000n + BigInt((m[2] ?? "").padEnd(6, "0") || "0");
|
|
1881
|
+
}
|
|
1882
|
+
function fromMicros(m) {
|
|
1883
|
+
const neg = m < 0n;
|
|
1884
|
+
const a = neg ? -m : m;
|
|
1885
|
+
const whole = a / 1000000n;
|
|
1886
|
+
const frac = (a % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
1887
|
+
return `${neg ? "-" : ""}${whole}.${frac.length >= 2 ? frac : frac.padEnd(2, "0")}`;
|
|
1888
|
+
}
|
|
1889
|
+
function suggestChildBudgets(parent, n) {
|
|
1890
|
+
const share = (v) => {
|
|
1891
|
+
if (!v) return 0n;
|
|
1892
|
+
const each = toMicros(v) / BigInt(Math.max(1, n));
|
|
1893
|
+
return each / 10000n * 10000n;
|
|
1894
|
+
};
|
|
1895
|
+
const daily = share(parent.remaining_today);
|
|
1896
|
+
const total = share(parent.remaining_total);
|
|
1897
|
+
const perParent = parent.per_request_limit ? toMicros(parent.per_request_limit) : daily;
|
|
1898
|
+
const per = [daily, perParent].reduce((a, b) => a < b ? a : b);
|
|
1899
|
+
return { daily_budget: fromMicros(daily), per_request_limit: fromMicros(per), total_budget: fromMicros(total) };
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// src/desktop/model-test.ts
|
|
1903
|
+
async function testBrain(agent, brain, fetchImpl = fetch, timeoutMs = 2e4) {
|
|
1904
|
+
const base = brain.baseUrl.replace(/\/+$/, "");
|
|
1905
|
+
let url;
|
|
1906
|
+
let init;
|
|
1907
|
+
if (agent === "claude") {
|
|
1908
|
+
url = `${base}/v1/messages`;
|
|
1909
|
+
const authVar = claudeAuthVar(brain.preset);
|
|
1910
|
+
init = {
|
|
1911
|
+
method: "POST",
|
|
1912
|
+
headers: {
|
|
1913
|
+
"content-type": "application/json",
|
|
1914
|
+
"anthropic-version": "2023-06-01",
|
|
1915
|
+
...authVar === "ANTHROPIC_API_KEY" ? { "x-api-key": brain.apiKey } : { authorization: `Bearer ${brain.apiKey}` }
|
|
1916
|
+
},
|
|
1917
|
+
body: JSON.stringify({ model: brain.model || "claude-sonnet-4-5", max_tokens: 1, messages: [{ role: "user", content: "ping" }] })
|
|
1918
|
+
};
|
|
1919
|
+
} else {
|
|
1920
|
+
url = `${base}/responses`;
|
|
1921
|
+
init = {
|
|
1922
|
+
method: "POST",
|
|
1923
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${brain.apiKey}` },
|
|
1924
|
+
body: JSON.stringify({ model: brain.model, input: "ping", max_output_tokens: 16 })
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
const started = Date.now();
|
|
1928
|
+
const ctrl = new AbortController();
|
|
1929
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
1930
|
+
try {
|
|
1931
|
+
const res = await fetchImpl(url, { ...init, signal: ctrl.signal });
|
|
1932
|
+
const text = await res.text().catch(() => "");
|
|
1933
|
+
let message = res.ok ? "OK" : `HTTP ${res.status}`;
|
|
1934
|
+
if (!res.ok) {
|
|
1935
|
+
try {
|
|
1936
|
+
const j = JSON.parse(text);
|
|
1937
|
+
const m = typeof j.error === "string" ? j.error : j.error?.message ?? j.message;
|
|
1938
|
+
if (m) message = `HTTP ${res.status}: ${m}`;
|
|
1939
|
+
} catch {
|
|
1940
|
+
if (text) message = `HTTP ${res.status}: ${text.slice(0, 160)}`;
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
return { ok: res.ok, httpStatus: res.status, message: message.slice(0, 300), ms: Date.now() - started, url };
|
|
1944
|
+
} catch (e) {
|
|
1945
|
+
const err = e;
|
|
1946
|
+
const reason = err.name === "AbortError" ? `timed out after ${timeoutMs} ms` : err.cause?.code ?? err.cause?.message ?? err.message;
|
|
1947
|
+
return { ok: false, httpStatus: null, message: `network error: ${reason}`, ms: Date.now() - started, url };
|
|
1948
|
+
} finally {
|
|
1949
|
+
clearTimeout(timer);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
// src/desktop/store.ts
|
|
1954
|
+
import fs3 from "node:fs";
|
|
1955
|
+
import path4 from "node:path";
|
|
1956
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
1957
|
+
function emptyStore() {
|
|
1958
|
+
return { version: 1, agents: {} };
|
|
1959
|
+
}
|
|
1960
|
+
function loadStore(env) {
|
|
1961
|
+
const p = desktopStorePath(env);
|
|
1962
|
+
if (!fs3.existsSync(p)) return emptyStore();
|
|
1963
|
+
try {
|
|
1964
|
+
const parsed = JSON.parse(fs3.readFileSync(p, "utf8"));
|
|
1965
|
+
if (!parsed || typeof parsed !== "object") return emptyStore();
|
|
1966
|
+
return { version: 1, server: parsed.server, key: parsed.key, agents: parsed.agents ?? {} };
|
|
1967
|
+
} catch {
|
|
1968
|
+
fs3.copyFileSync(p, `${p}.corrupt-${Date.now()}`);
|
|
1969
|
+
return emptyStore();
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
function restrictToCurrentUser(file, env = process.env) {
|
|
1973
|
+
if (process.platform !== "win32") {
|
|
1974
|
+
try {
|
|
1975
|
+
fs3.chmodSync(file, 384);
|
|
1976
|
+
return { ok: true, how: "chmod 600" };
|
|
1977
|
+
} catch (e) {
|
|
1978
|
+
return { ok: false, how: `chmod failed: ${e.message}` };
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
const user = env.USERNAME ?? process.env.USERNAME;
|
|
1982
|
+
if (!user) return { ok: false, how: "USERNAME unknown" };
|
|
1983
|
+
const domain = env.USERDOMAIN ?? process.env.USERDOMAIN;
|
|
1984
|
+
const principal = domain ? `${domain}\\${user}` : user;
|
|
1985
|
+
const res = spawnSync2("icacls", [file, "/inheritance:r", "/grant:r", `${principal}:F`], {
|
|
1986
|
+
encoding: "utf8",
|
|
1987
|
+
windowsHide: true
|
|
1988
|
+
});
|
|
1989
|
+
return res.status === 0 ? { ok: true, how: `icacls ${principal}:F (inheritance removed)` } : { ok: false, how: `icacls failed: ${res.stderr || res.stdout}` };
|
|
1990
|
+
}
|
|
1991
|
+
function saveStore(env, store) {
|
|
1992
|
+
const p = desktopStorePath(env);
|
|
1993
|
+
fs3.mkdirSync(path4.dirname(p), { recursive: true });
|
|
1994
|
+
const tmp = `${p}.tmp-${process.pid}`;
|
|
1995
|
+
fs3.writeFileSync(tmp, JSON.stringify(store, null, 2) + "\n", { encoding: "utf8", mode: 384 });
|
|
1996
|
+
restrictToCurrentUser(tmp, env);
|
|
1997
|
+
fs3.renameSync(tmp, p);
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
// src/desktop/service.ts
|
|
2001
|
+
var NEW_CHILD_PLACEHOLDER = "mk_live_NEWCHILDKEY_WILL_BE_CREATED";
|
|
2002
|
+
var NEW_CHILD_MARK = "@@NEW_CHILD@@";
|
|
2003
|
+
var UserError = class extends Error {
|
|
2004
|
+
constructor(status, code, message, detail) {
|
|
2005
|
+
super(message);
|
|
2006
|
+
this.status = status;
|
|
2007
|
+
this.code = code;
|
|
2008
|
+
this.detail = detail;
|
|
2009
|
+
}
|
|
2010
|
+
status;
|
|
2011
|
+
code;
|
|
2012
|
+
detail;
|
|
2013
|
+
};
|
|
2014
|
+
function isAuto(agent) {
|
|
2015
|
+
return AUTO_AGENTS.includes(agent);
|
|
2016
|
+
}
|
|
2017
|
+
function maskBrain(b) {
|
|
2018
|
+
if (!b) return null;
|
|
2019
|
+
return { preset: b.preset, baseUrl: b.baseUrl, model: b.model, apiKeyMasked: b.apiKey ? maskSecret(b.apiKey) : "", hasApiKey: Boolean(b.apiKey) };
|
|
2020
|
+
}
|
|
2021
|
+
function maskWallet(w) {
|
|
2022
|
+
if (!w) return null;
|
|
2023
|
+
const { key, ...rest } = w;
|
|
2024
|
+
return { ...rest, keyMasked: maskSecret(key) };
|
|
2025
|
+
}
|
|
2026
|
+
function validateUsd(v, field) {
|
|
2027
|
+
if (typeof v !== "string" && typeof v !== "number") throw new UserError(400, "INVALID_AMOUNT", `${field} is required`, { field });
|
|
2028
|
+
const s = String(v).trim();
|
|
2029
|
+
if (!/^\d+(\.\d{1,6})?$/.test(s) || toMicros(s) <= 0n) throw new UserError(400, "INVALID_AMOUNT", `${field} must be a positive amount like 1.50`, { field });
|
|
2030
|
+
return s;
|
|
2031
|
+
}
|
|
2032
|
+
var DesktopService = class {
|
|
2033
|
+
env;
|
|
2034
|
+
runner;
|
|
2035
|
+
fetchImpl;
|
|
2036
|
+
now;
|
|
2037
|
+
detection = null;
|
|
2038
|
+
mcpCache = /* @__PURE__ */ new Map();
|
|
2039
|
+
fixedMcp;
|
|
2040
|
+
/** Serialise every write: one config change at a time. */
|
|
2041
|
+
chain = Promise.resolve();
|
|
2042
|
+
constructor(deps) {
|
|
2043
|
+
this.env = deps.env;
|
|
2044
|
+
this.runner = deps.runner;
|
|
2045
|
+
this.fetchImpl = deps.fetchImpl ?? fetch;
|
|
2046
|
+
this.fixedMcp = deps.mcpCommand;
|
|
2047
|
+
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
2048
|
+
}
|
|
2049
|
+
exclusive(fn) {
|
|
2050
|
+
const run = this.chain.then(fn, fn);
|
|
2051
|
+
this.chain = run.catch(() => void 0);
|
|
2052
|
+
return run;
|
|
2053
|
+
}
|
|
2054
|
+
store() {
|
|
2055
|
+
return loadStore(this.env);
|
|
2056
|
+
}
|
|
2057
|
+
save(s) {
|
|
2058
|
+
saveStore(this.env, s);
|
|
2059
|
+
}
|
|
2060
|
+
agentState(s, agent) {
|
|
2061
|
+
s.agents[agent] ??= {};
|
|
2062
|
+
return s.agents[agent];
|
|
2063
|
+
}
|
|
2064
|
+
detect(force = false) {
|
|
2065
|
+
if (!this.detection || force) this.detection = detectAgents(this.env, this.runner);
|
|
2066
|
+
return this.detection;
|
|
2067
|
+
}
|
|
2068
|
+
async mcpCommand(server) {
|
|
2069
|
+
if (this.fixedMcp) return this.fixedMcp;
|
|
2070
|
+
const cached = this.mcpCache.get(server);
|
|
2071
|
+
if (cached) return cached;
|
|
2072
|
+
let cmd = resolveMcpCommand(import.meta.url);
|
|
2073
|
+
if (isNpmRegistryFallback(cmd)) cmd = await resolvePortableMcpCommand(server, this.fetchImpl);
|
|
2074
|
+
this.mcpCache.set(server, cmd);
|
|
2075
|
+
return cmd;
|
|
2076
|
+
}
|
|
2077
|
+
api(s) {
|
|
2078
|
+
if (!s.server || !s.key) throw new UserError(400, "NO_ACCOUNT", "connect your MoneySwitch account first");
|
|
2079
|
+
return new MoneyApi(s.server, s.key, this.fetchImpl);
|
|
2080
|
+
}
|
|
2081
|
+
// ---------------------------------------------------------------- status
|
|
2082
|
+
agentStatus(agent, st) {
|
|
2083
|
+
const applied = st?.applied;
|
|
2084
|
+
if (!applied || !isAuto(agent)) return "disabled";
|
|
2085
|
+
try {
|
|
2086
|
+
const fp = agent === "claude" ? claudeFingerprint(this.env, claudeManagedKeys(applied), applied.parts.wallet) : codexFingerprint(this.env, applied);
|
|
2087
|
+
return fp === applied.fingerprint ? "enabled" : "drifted";
|
|
2088
|
+
} catch {
|
|
2089
|
+
return "drifted";
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
async state() {
|
|
2093
|
+
const s = this.store();
|
|
2094
|
+
const det = this.detect();
|
|
2095
|
+
const mcp = s.server ? await this.mcpCommand(s.server).catch(() => ({ command: "npx", args: ["-y", "moneyswitch", "mcp"] })) : { command: "npx", args: ["-y", "moneyswitch", "mcp"] };
|
|
2096
|
+
const agents = ALL_AGENTS.map((id) => {
|
|
2097
|
+
const st = s.agents[id];
|
|
2098
|
+
return {
|
|
2099
|
+
id,
|
|
2100
|
+
name: AGENT_INFO[id].name,
|
|
2101
|
+
mode: AGENT_INFO[id].mode,
|
|
2102
|
+
detection: det[id],
|
|
2103
|
+
brain: maskBrain(st?.brain),
|
|
2104
|
+
wallet: maskWallet(st?.wallet),
|
|
2105
|
+
status: this.agentStatus(id, st),
|
|
2106
|
+
applied: st?.applied ? { at: st.applied.at, backups: st.applied.backups, parts: st.applied.parts } : null,
|
|
2107
|
+
presets: presetsFor(id),
|
|
2108
|
+
manual: AGENT_INFO[id].mode === "manual" ? manualSteps(id, { server: s.server ?? null, walletKey: st?.wallet?.key ?? null, brain: st?.brain ?? null, mcp }) : []
|
|
2109
|
+
};
|
|
2110
|
+
});
|
|
2111
|
+
return {
|
|
2112
|
+
account: s.server && s.key ? { server: s.server, keyMasked: maskSecret(s.key) } : null,
|
|
2113
|
+
agents,
|
|
2114
|
+
host: os2.hostname()
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
/** Live numbers from the server: my budget + today's spend of each agent's key. Never throws. */
|
|
2118
|
+
async usage() {
|
|
2119
|
+
const s = this.store();
|
|
2120
|
+
if (!s.server || !s.key) return { account: null, agents: {}, error: null };
|
|
2121
|
+
const api = this.api(s);
|
|
2122
|
+
let account = null;
|
|
2123
|
+
let error = null;
|
|
2124
|
+
try {
|
|
2125
|
+
account = await api.status();
|
|
2126
|
+
} catch (e) {
|
|
2127
|
+
const err = e;
|
|
2128
|
+
error = { code: err.code ?? "ERROR", message: err.message };
|
|
2129
|
+
}
|
|
2130
|
+
const agents = {};
|
|
2131
|
+
let children = [];
|
|
2132
|
+
if (account) children = await api.listChildren().catch(() => []);
|
|
2133
|
+
for (const id of ALL_AGENTS) {
|
|
2134
|
+
const w = s.agents[id]?.wallet;
|
|
2135
|
+
if (!w) continue;
|
|
2136
|
+
const child = w.childId ? children.find((c) => c.id === w.childId) : void 0;
|
|
2137
|
+
if (child) {
|
|
2138
|
+
agents[id] = { used_today: child.used_today ?? null, status: child.status ?? null };
|
|
2139
|
+
} else {
|
|
2140
|
+
try {
|
|
2141
|
+
const st = await new MoneyApi(s.server, w.key, this.fetchImpl).status();
|
|
2142
|
+
agents[id] = { used_today: st.used_today ?? null, status: "active" };
|
|
2143
|
+
} catch (e) {
|
|
2144
|
+
agents[id] = { used_today: null, status: null, error: e.code };
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
return { account, agents, error };
|
|
2149
|
+
}
|
|
2150
|
+
// --------------------------------------------------------------- account
|
|
2151
|
+
setAccount(server, key) {
|
|
2152
|
+
return this.exclusive(async () => {
|
|
2153
|
+
if (typeof server !== "string" || !server.trim()) throw new UserError(400, "INVALID_SERVER", "server URL is required");
|
|
2154
|
+
if (typeof key !== "string" || !/^mk_live_[A-Za-z0-9_-]{8,}$/.test(key.trim())) throw new UserError(400, "INVALID_KEY", "paste a MoneyKey that starts with mk_live_");
|
|
2155
|
+
let norm;
|
|
2156
|
+
try {
|
|
2157
|
+
norm = normalizeServer(server);
|
|
2158
|
+
} catch {
|
|
2159
|
+
throw new UserError(400, "INVALID_SERVER", "server must be an http(s) URL");
|
|
2160
|
+
}
|
|
2161
|
+
let status;
|
|
2162
|
+
try {
|
|
2163
|
+
status = await new MoneyApi(norm, key.trim(), this.fetchImpl).status();
|
|
2164
|
+
} catch (e) {
|
|
2165
|
+
const err = e;
|
|
2166
|
+
throw new UserError(err.httpStatus === 401 ? 401 : 502, err.code, err.message);
|
|
2167
|
+
}
|
|
2168
|
+
const s = this.store();
|
|
2169
|
+
s.server = norm;
|
|
2170
|
+
s.key = key.trim();
|
|
2171
|
+
this.save(s);
|
|
2172
|
+
return { server: norm, keyMasked: maskSecret(s.key), status };
|
|
2173
|
+
});
|
|
2174
|
+
}
|
|
2175
|
+
clearAccount() {
|
|
2176
|
+
return this.exclusive(() => {
|
|
2177
|
+
const s = this.store();
|
|
2178
|
+
delete s.server;
|
|
2179
|
+
delete s.key;
|
|
2180
|
+
this.save(s);
|
|
2181
|
+
return { ok: true };
|
|
2182
|
+
});
|
|
2183
|
+
}
|
|
2184
|
+
// ----------------------------------------------------------------- brain
|
|
2185
|
+
saveBrain(agent, body) {
|
|
2186
|
+
return this.exclusive(() => {
|
|
2187
|
+
if (!isAuto(agent)) throw new UserError(400, "NOT_SUPPORTED", "model settings for this agent are manual in v0.4");
|
|
2188
|
+
const s = this.store();
|
|
2189
|
+
const st = this.agentState(s, agent);
|
|
2190
|
+
if (body.clear === true) {
|
|
2191
|
+
st.brain = null;
|
|
2192
|
+
this.save(s);
|
|
2193
|
+
return { brain: null };
|
|
2194
|
+
}
|
|
2195
|
+
const brain = this.parseBrain(agent, body, st.brain ?? null);
|
|
2196
|
+
st.brain = brain;
|
|
2197
|
+
this.save(s);
|
|
2198
|
+
return { brain: maskBrain(brain) };
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
parseBrain(agent, body, existing) {
|
|
2202
|
+
const presets = presetsFor(agent);
|
|
2203
|
+
const preset = presets.find((p) => p.id === body.preset);
|
|
2204
|
+
if (!preset) throw new UserError(400, "INVALID_PRESET", "unknown provider preset");
|
|
2205
|
+
const baseUrl = String(body.baseUrl ?? preset.baseUrl).trim();
|
|
2206
|
+
try {
|
|
2207
|
+
const u = new URL(baseUrl);
|
|
2208
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error();
|
|
2209
|
+
} catch {
|
|
2210
|
+
throw new UserError(400, "INVALID_BASE_URL", "Base URL must be an http(s) URL", { field: "baseUrl" });
|
|
2211
|
+
}
|
|
2212
|
+
const model = String(body.model ?? "").trim();
|
|
2213
|
+
if (agent === "codex" && !model) throw new UserError(400, "MODEL_REQUIRED", "Codex needs a model name", { field: "model" });
|
|
2214
|
+
let apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
|
|
2215
|
+
if (!apiKey && existing) apiKey = existing.apiKey;
|
|
2216
|
+
if (!apiKey) throw new UserError(400, "API_KEY_REQUIRED", "API key is required", { field: "apiKey" });
|
|
2217
|
+
if (/[\r\n"]/.test(apiKey) || /[\r\n"]/.test(model)) throw new UserError(400, "INVALID_INPUT", "unexpected characters");
|
|
2218
|
+
return { preset: preset.id, baseUrl, apiKey, model };
|
|
2219
|
+
}
|
|
2220
|
+
async testBrain(agent, body) {
|
|
2221
|
+
if (!isAuto(agent)) throw new UserError(400, "NOT_SUPPORTED", "not supported for this agent");
|
|
2222
|
+
const s = this.store();
|
|
2223
|
+
const brain = this.parseBrain(agent, body, s.agents[agent]?.brain ?? null);
|
|
2224
|
+
return testBrain(agent, brain, this.fetchImpl);
|
|
2225
|
+
}
|
|
2226
|
+
// ---------------------------------------------------------------- wallet
|
|
2227
|
+
createChild(agent, body) {
|
|
2228
|
+
return this.exclusive(async () => {
|
|
2229
|
+
const s = this.store();
|
|
2230
|
+
const api = this.api(s);
|
|
2231
|
+
const daily = validateUsd(body.daily_budget, "daily_budget");
|
|
2232
|
+
const per = validateUsd(body.per_request_limit, "per_request_limit");
|
|
2233
|
+
const total = validateUsd(body.total_budget, "total_budget");
|
|
2234
|
+
if (toMicros(per) > toMicros(daily)) throw new UserError(400, "PER_REQUEST_ABOVE_DAILY", "the per-request limit cannot be above the daily limit", { field: "per_request_limit" });
|
|
2235
|
+
const name = `${AGENT_INFO[agent].name} @ ${os2.hostname()}`.slice(0, 80);
|
|
2236
|
+
let child;
|
|
2237
|
+
try {
|
|
2238
|
+
child = await api.createChild({ name, daily_budget: daily, total_budget: total, per_request_limit: per });
|
|
2239
|
+
} catch (e) {
|
|
2240
|
+
const err = e;
|
|
2241
|
+
throw new UserError(err.httpStatus >= 400 && err.httpStatus < 500 ? err.httpStatus : 502, err.code, err.message, err.body);
|
|
2242
|
+
}
|
|
2243
|
+
const st = this.agentState(s, agent);
|
|
2244
|
+
st.wallet = {
|
|
2245
|
+
key: child.key,
|
|
2246
|
+
source: "child",
|
|
2247
|
+
childId: child.id,
|
|
2248
|
+
keyPrefix: child.key_prefix,
|
|
2249
|
+
name: child.name,
|
|
2250
|
+
dailyBudget: child.daily_budget,
|
|
2251
|
+
perRequestLimit: child.per_request_limit,
|
|
2252
|
+
totalBudget: child.total_budget,
|
|
2253
|
+
createdAt: this.now().toISOString()
|
|
2254
|
+
};
|
|
2255
|
+
this.save(s);
|
|
2256
|
+
return { wallet: maskWallet(st.wallet) };
|
|
2257
|
+
});
|
|
2258
|
+
}
|
|
2259
|
+
pasteWallet(agent, body) {
|
|
2260
|
+
return this.exclusive(async () => {
|
|
2261
|
+
const s = this.store();
|
|
2262
|
+
if (!s.server) throw new UserError(400, "NO_ACCOUNT", "connect your MoneySwitch account first");
|
|
2263
|
+
const key = typeof body.key === "string" ? body.key.trim() : "";
|
|
2264
|
+
if (!/^mk_live_[A-Za-z0-9_-]{8,}$/.test(key)) throw new UserError(400, "INVALID_KEY", "paste a MoneyKey that starts with mk_live_");
|
|
2265
|
+
let st;
|
|
2266
|
+
try {
|
|
2267
|
+
st = await new MoneyApi(s.server, key, this.fetchImpl).status();
|
|
2268
|
+
} catch (e) {
|
|
2269
|
+
const err = e;
|
|
2270
|
+
throw new UserError(err.httpStatus === 401 ? 400 : 502, err.code, err.message);
|
|
2271
|
+
}
|
|
2272
|
+
const a = this.agentState(s, agent);
|
|
2273
|
+
a.wallet = {
|
|
2274
|
+
key,
|
|
2275
|
+
source: "pasted",
|
|
2276
|
+
keyPrefix: st.key_prefix,
|
|
2277
|
+
name: st.key_name,
|
|
2278
|
+
dailyBudget: st.daily_budget,
|
|
2279
|
+
perRequestLimit: st.per_request_limit,
|
|
2280
|
+
totalBudget: st.total_budget,
|
|
2281
|
+
createdAt: this.now().toISOString()
|
|
2282
|
+
};
|
|
2283
|
+
this.save(s);
|
|
2284
|
+
return { wallet: maskWallet(a.wallet) };
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
/** Forget the wallet key locally; optionally revoke the child on the server. Refused while it is written into the agent. */
|
|
2288
|
+
clearWallet(agent, body) {
|
|
2289
|
+
return this.exclusive(async () => {
|
|
2290
|
+
const s = this.store();
|
|
2291
|
+
const st = this.agentState(s, agent);
|
|
2292
|
+
if (st.applied?.parts.wallet) throw new UserError(409, "STILL_ENABLED", "turn this agent off first, then remove its key");
|
|
2293
|
+
const w = st.wallet;
|
|
2294
|
+
let revoked = false;
|
|
2295
|
+
if (w && body.revoke === true && w.childId) {
|
|
2296
|
+
try {
|
|
2297
|
+
await this.api(s).revokeChild(w.childId);
|
|
2298
|
+
revoked = true;
|
|
2299
|
+
} catch (e) {
|
|
2300
|
+
const err = e;
|
|
2301
|
+
throw new UserError(502, err.code, err.message);
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
st.wallet = null;
|
|
2305
|
+
this.save(s);
|
|
2306
|
+
return { revoked };
|
|
2307
|
+
});
|
|
2308
|
+
}
|
|
2309
|
+
// ------------------------------------------------------- preview / apply
|
|
2310
|
+
async target(s, agent, walletOverride) {
|
|
2311
|
+
const st = s.agents[agent] ?? {};
|
|
2312
|
+
const wallet = walletOverride !== void 0 ? walletOverride : st.wallet;
|
|
2313
|
+
if (wallet && !s.server) throw new UserError(400, "NO_ACCOUNT", "connect your MoneySwitch account first");
|
|
2314
|
+
const mcp = await this.mcpCommand(s.server ?? "");
|
|
2315
|
+
return { brain: st.brain ?? null, wallet: wallet && s.server ? { server: s.server, key: wallet.key } : null, mcpCommand: mcp };
|
|
2316
|
+
}
|
|
2317
|
+
planFor(agent, action, target, st) {
|
|
2318
|
+
try {
|
|
2319
|
+
return agent === "claude" ? planClaude(this.env, action, target, st.applied) : planCodex(this.env, action, target, st.applied);
|
|
2320
|
+
} catch (e) {
|
|
2321
|
+
if (e instanceof AgentConfigError) throw new UserError(422, e.code, e.message);
|
|
2322
|
+
throw e;
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
planId(agent, action, inputHash, target, st) {
|
|
2326
|
+
return sha256(
|
|
2327
|
+
stableStringify({
|
|
2328
|
+
agent,
|
|
2329
|
+
action,
|
|
2330
|
+
inputHash,
|
|
2331
|
+
brain: target?.brain ? { ...target.brain, apiKey: sha256(target.brain.apiKey) } : null,
|
|
2332
|
+
wallet: target?.wallet ? { server: target.wallet.server, key: sha256(target.wallet.key) } : null,
|
|
2333
|
+
mcp: target?.mcpCommand ?? null,
|
|
2334
|
+
appliedAt: st.applied?.at ?? null
|
|
2335
|
+
})
|
|
2336
|
+
).slice(0, 32);
|
|
2337
|
+
}
|
|
2338
|
+
async preview(agent, action) {
|
|
2339
|
+
if (!isAuto(agent)) throw new UserError(400, "NOT_SUPPORTED", "this agent is configured by hand (see the steps on its card)");
|
|
2340
|
+
if (action !== "enable" && action !== "disable") throw new UserError(400, "INVALID_ACTION", "action must be enable or disable");
|
|
2341
|
+
const s = this.store();
|
|
2342
|
+
const st = s.agents[agent] ?? {};
|
|
2343
|
+
if (action === "enable" && !st.brain && !st.wallet) throw new UserError(400, "NOTHING_TO_ENABLE", "set a model or a MoneyKey for this agent first");
|
|
2344
|
+
if (action === "disable" && !st.applied) throw new UserError(400, "NOT_ENABLED", "nothing to turn off");
|
|
2345
|
+
const target = action === "enable" ? await this.target(s, agent) : null;
|
|
2346
|
+
const { plan, inputHash } = this.planFor(agent, action, target, st);
|
|
2347
|
+
return { plan, planId: this.planId(agent, action, inputHash, target, st) };
|
|
2348
|
+
}
|
|
2349
|
+
apply(agent, action, planId) {
|
|
2350
|
+
return this.exclusive(async () => {
|
|
2351
|
+
const { planId: current } = await this.preview(agent, action);
|
|
2352
|
+
if (planId !== current) throw new UserError(409, "PLAN_CHANGED", "the configuration changed since the preview; review the new diff and confirm again");
|
|
2353
|
+
return this.applyNow(agent, action);
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
async applyNow(agent, action) {
|
|
2357
|
+
const s = this.store();
|
|
2358
|
+
const st = this.agentState(s, agent);
|
|
2359
|
+
const target = action === "enable" ? await this.target(s, agent) : null;
|
|
2360
|
+
let result;
|
|
2361
|
+
try {
|
|
2362
|
+
result = agent === "claude" ? applyClaudePlan(this.env, action, target, st.applied, this.runner, this.now()) : applyCodexPlan(this.env, action, target, st.applied, this.now());
|
|
2363
|
+
} catch (e) {
|
|
2364
|
+
if (e instanceof AgentConfigError) throw new UserError(e.code === "NOT_INSTALLED" ? 424 : 500, e.code, e.message);
|
|
2365
|
+
throw e;
|
|
2366
|
+
}
|
|
2367
|
+
st.applied = result.applied;
|
|
2368
|
+
this.save(s);
|
|
2369
|
+
return { status: this.agentStatus(agent, st), backups: result.backups, applied: st.applied ? { at: st.applied.at, backups: st.applied.backups, parts: st.applied.parts } : null };
|
|
2370
|
+
}
|
|
2371
|
+
// ---------------------------------------------------------------- bulk
|
|
2372
|
+
bulkAgents() {
|
|
2373
|
+
const det = this.detect();
|
|
2374
|
+
return AUTO_AGENTS.filter((a) => det[a].installed);
|
|
2375
|
+
}
|
|
2376
|
+
async bulkPreview() {
|
|
2377
|
+
const s = this.store();
|
|
2378
|
+
const api = this.api(s);
|
|
2379
|
+
const agents = this.bulkAgents();
|
|
2380
|
+
if (!agents.length) throw new UserError(400, "NO_AGENTS", "no Claude Code or Codex found on this computer");
|
|
2381
|
+
let parent;
|
|
2382
|
+
try {
|
|
2383
|
+
parent = await api.status();
|
|
2384
|
+
} catch (e) {
|
|
2385
|
+
const err = e;
|
|
2386
|
+
throw new UserError(502, err.code, err.message);
|
|
2387
|
+
}
|
|
2388
|
+
if (parent.can_create_children === false) throw new UserError(403, "CANNOT_DELEGATE", "this MoneyKey is not allowed to create child keys");
|
|
2389
|
+
const budgets = suggestChildBudgets(parent, agents.length);
|
|
2390
|
+
if (toMicros(budgets.daily_budget) <= 0n) throw new UserError(400, "NO_BUDGET_LEFT", "nothing left to split today");
|
|
2391
|
+
const items = [];
|
|
2392
|
+
const ids = [];
|
|
2393
|
+
for (const agent of agents) {
|
|
2394
|
+
const st = s.agents[agent] ?? {};
|
|
2395
|
+
const target = await this.target(s, agent, { key: NEW_CHILD_PLACEHOLDER, source: "child" });
|
|
2396
|
+
const { plan, inputHash } = this.planFor(agent, "enable", target, st);
|
|
2397
|
+
for (const f of plan.files) for (const c of f.changes) if (c.after === maskSecret(NEW_CHILD_PLACEHOLDER)) c.after = NEW_CHILD_MARK;
|
|
2398
|
+
for (const c of plan.commands) c.display = c.display.replace(maskSecret(NEW_CHILD_PLACEHOLDER), NEW_CHILD_MARK);
|
|
2399
|
+
ids.push(this.planId(agent, "bulk", inputHash, target, st));
|
|
2400
|
+
items.push({ agent, budgets, plan, replacesWallet: Boolean(st.wallet) });
|
|
2401
|
+
}
|
|
2402
|
+
return { planId: sha256(stableStringify({ ids, budgets })).slice(0, 32), budgets, items };
|
|
2403
|
+
}
|
|
2404
|
+
bulkApply(planId) {
|
|
2405
|
+
return this.exclusive(async () => {
|
|
2406
|
+
const pv = await this.bulkPreview();
|
|
2407
|
+
if (pv.planId !== planId) throw new UserError(409, "PLAN_CHANGED", "something changed since the preview; review the new diff and confirm again");
|
|
2408
|
+
const done = [];
|
|
2409
|
+
for (const item of pv.items) {
|
|
2410
|
+
try {
|
|
2411
|
+
const s = this.store();
|
|
2412
|
+
const child = await this.api(s).createChild({
|
|
2413
|
+
name: `${AGENT_INFO[item.agent].name} @ ${os2.hostname()}`.slice(0, 80),
|
|
2414
|
+
...item.budgets
|
|
2415
|
+
});
|
|
2416
|
+
const st = this.agentState(s, item.agent);
|
|
2417
|
+
st.wallet = {
|
|
2418
|
+
key: child.key,
|
|
2419
|
+
source: "child",
|
|
2420
|
+
childId: child.id,
|
|
2421
|
+
keyPrefix: child.key_prefix,
|
|
2422
|
+
name: child.name,
|
|
2423
|
+
dailyBudget: child.daily_budget,
|
|
2424
|
+
perRequestLimit: child.per_request_limit,
|
|
2425
|
+
totalBudget: child.total_budget,
|
|
2426
|
+
createdAt: this.now().toISOString()
|
|
2427
|
+
};
|
|
2428
|
+
this.save(s);
|
|
2429
|
+
const r = await this.applyNow(item.agent, "enable");
|
|
2430
|
+
done.push({ agent: item.agent, status: r.status, backups: r.backups });
|
|
2431
|
+
} catch (e) {
|
|
2432
|
+
const err = e;
|
|
2433
|
+
throw new UserError(
|
|
2434
|
+
err.status ?? 502,
|
|
2435
|
+
err.code ?? "BULK_FAILED",
|
|
2436
|
+
`${AGENT_INFO[item.agent].name}: ${err.message}`,
|
|
2437
|
+
{ done }
|
|
2438
|
+
);
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
return { done };
|
|
2442
|
+
});
|
|
2443
|
+
}
|
|
2444
|
+
};
|
|
2445
|
+
|
|
2446
|
+
// src/desktop/server.ts
|
|
2447
|
+
var MAX_BODY = 64 * 1024;
|
|
2448
|
+
var SECURITY_HEADERS = {
|
|
2449
|
+
"X-Content-Type-Options": "nosniff",
|
|
2450
|
+
"X-Frame-Options": "DENY",
|
|
2451
|
+
"Referrer-Policy": "no-referrer",
|
|
2452
|
+
"Cache-Control": "no-store",
|
|
2453
|
+
"Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"
|
|
2454
|
+
};
|
|
2455
|
+
function send(res, status, body, extra = {}) {
|
|
2456
|
+
const text = JSON.stringify(body);
|
|
2457
|
+
res.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra });
|
|
2458
|
+
res.end(text);
|
|
2459
|
+
}
|
|
2460
|
+
function readBody(req) {
|
|
2461
|
+
return new Promise((resolve, reject) => {
|
|
2462
|
+
let size = 0;
|
|
2463
|
+
const chunks = [];
|
|
2464
|
+
req.on("data", (c) => {
|
|
2465
|
+
size += c.length;
|
|
2466
|
+
if (size > MAX_BODY) {
|
|
2467
|
+
reject(new UserError(413, "TOO_LARGE", "request body too large"));
|
|
2468
|
+
req.destroy();
|
|
2469
|
+
return;
|
|
2470
|
+
}
|
|
2471
|
+
chunks.push(c);
|
|
2472
|
+
});
|
|
2473
|
+
req.on("end", () => {
|
|
2474
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
2475
|
+
if (!raw) return resolve({});
|
|
2476
|
+
try {
|
|
2477
|
+
const v = JSON.parse(raw);
|
|
2478
|
+
resolve(v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
2479
|
+
} catch {
|
|
2480
|
+
reject(new UserError(400, "BAD_JSON", "invalid JSON body"));
|
|
2481
|
+
}
|
|
2482
|
+
});
|
|
2483
|
+
req.on("error", reject);
|
|
2484
|
+
});
|
|
2485
|
+
}
|
|
2486
|
+
var MIME = {
|
|
2487
|
+
".html": "text/html; charset=utf-8",
|
|
2488
|
+
".js": "text/javascript; charset=utf-8",
|
|
2489
|
+
".css": "text/css; charset=utf-8",
|
|
2490
|
+
".svg": "image/svg+xml"
|
|
2491
|
+
};
|
|
2492
|
+
function serveAsset(res, assetsDir, urlPath) {
|
|
2493
|
+
const rel = urlPath === "/" ? "index.html" : urlPath.replace(/^\/+/, "");
|
|
2494
|
+
if (!/^[A-Za-z0-9._-]+$/.test(rel)) return send(res, 404, { error: "NOT_FOUND" });
|
|
2495
|
+
const file = path5.join(assetsDir, rel);
|
|
2496
|
+
if (!fs4.existsSync(file)) return send(res, 404, { error: "NOT_FOUND" });
|
|
2497
|
+
res.writeHead(200, { ...SECURITY_HEADERS, "Content-Type": MIME[path5.extname(file)] ?? "application/octet-stream" });
|
|
2498
|
+
fs4.createReadStream(file).pipe(res);
|
|
2499
|
+
}
|
|
2500
|
+
function agentParam(v) {
|
|
2501
|
+
if (!ALL_AGENTS.includes(v)) throw new UserError(404, "UNKNOWN_AGENT", "unknown agent");
|
|
2502
|
+
return v;
|
|
2503
|
+
}
|
|
2504
|
+
function createUiServer(opts) {
|
|
2505
|
+
const sessions = opts.sessions ?? new SessionManager(opts.port);
|
|
2506
|
+
const svc = opts.service;
|
|
2507
|
+
const log = opts.log ?? (() => void 0);
|
|
2508
|
+
const server = http.createServer(async (req, res) => {
|
|
2509
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
2510
|
+
const p = url.pathname;
|
|
2511
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
2512
|
+
try {
|
|
2513
|
+
const denied = guardRequest(sessions, { method, headers: req.headers, url: p });
|
|
2514
|
+
if (denied) return send(res, denied.status, { error: denied.code, message: denied.message });
|
|
2515
|
+
if (!p.startsWith("/api/")) {
|
|
2516
|
+
if (method !== "GET" && method !== "HEAD") return send(res, 405, { error: "METHOD_NOT_ALLOWED" });
|
|
2517
|
+
return serveAsset(res, opts.assetsDir, p);
|
|
2518
|
+
}
|
|
2519
|
+
log(`${method} ${p}`);
|
|
2520
|
+
const body = method === "GET" ? {} : await readBody(req);
|
|
2521
|
+
const m = (re) => re.exec(p);
|
|
2522
|
+
let r;
|
|
2523
|
+
if (method === "POST" && p === "/api/session") {
|
|
2524
|
+
const sid = sessions.exchange(body.token);
|
|
2525
|
+
if (!sid) return send(res, 401, { error: "BAD_TOKEN", message: "this link was already used or is wrong; run `moneyswitch ui` again" });
|
|
2526
|
+
return send(res, 200, { ok: true }, { "Set-Cookie": sessions.cookieHeader(sid) });
|
|
2527
|
+
}
|
|
2528
|
+
if (method === "POST" && p === "/api/logout") {
|
|
2529
|
+
const sid = readCookie(req.headers.cookie, COOKIE_NAME);
|
|
2530
|
+
if (sid) sessions.revoke(sid);
|
|
2531
|
+
return send(res, 200, { ok: true }, { "Set-Cookie": `${COOKIE_NAME}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0` });
|
|
2532
|
+
}
|
|
2533
|
+
if (method === "GET" && p === "/api/state") return send(res, 200, await svc.state());
|
|
2534
|
+
if (method === "GET" && p === "/api/usage") return send(res, 200, await svc.usage());
|
|
2535
|
+
if (method === "POST" && p === "/api/detect") {
|
|
2536
|
+
svc.detect(true);
|
|
2537
|
+
return send(res, 200, await svc.state());
|
|
2538
|
+
}
|
|
2539
|
+
if (method === "PUT" && p === "/api/account") return send(res, 200, await svc.setAccount(body.server, body.key));
|
|
2540
|
+
if (method === "DELETE" && p === "/api/account") return send(res, 200, await svc.clearAccount());
|
|
2541
|
+
if (method === "POST" && p === "/api/bulk/preview") return send(res, 200, await svc.bulkPreview());
|
|
2542
|
+
if (method === "POST" && p === "/api/bulk/apply") return send(res, 200, await svc.bulkApply(body.planId));
|
|
2543
|
+
if (r = m(/^\/api\/agents\/([a-z]+)\/(brain|brain\/test|wallet|wallet\/child|preview|apply)$/)) {
|
|
2544
|
+
const agent = agentParam(r[1]);
|
|
2545
|
+
const what = r[2];
|
|
2546
|
+
if (method === "PUT" && what === "brain") return send(res, 200, await svc.saveBrain(agent, body));
|
|
2547
|
+
if (method === "POST" && what === "brain/test") return send(res, 200, await svc.testBrain(agent, body));
|
|
2548
|
+
if (method === "POST" && what === "wallet/child") return send(res, 200, await svc.createChild(agent, body));
|
|
2549
|
+
if (method === "PUT" && what === "wallet") return send(res, 200, await svc.pasteWallet(agent, body));
|
|
2550
|
+
if (method === "DELETE" && what === "wallet") return send(res, 200, await svc.clearWallet(agent, body));
|
|
2551
|
+
if (method === "POST" && what === "preview") return send(res, 200, await svc.preview(agent, body.action));
|
|
2552
|
+
if (method === "POST" && what === "apply") return send(res, 200, await svc.apply(agent, body.action, body.planId));
|
|
2553
|
+
}
|
|
2554
|
+
return send(res, 404, { error: "NOT_FOUND" });
|
|
2555
|
+
} catch (e) {
|
|
2556
|
+
if (e instanceof UserError) return send(res, e.status, { error: e.code, message: e.message, detail: e.detail ?? null });
|
|
2557
|
+
log(`error ${method} ${p}: ${e.message}`);
|
|
2558
|
+
return send(res, 500, { error: "INTERNAL", message: e.message });
|
|
2559
|
+
}
|
|
2560
|
+
});
|
|
2561
|
+
return { server, sessions };
|
|
2562
|
+
}
|
|
2563
|
+
|
|
2564
|
+
// src/desktop/ui.ts
|
|
2565
|
+
var UI_HELP = `moneyswitch ui - local desktop console (SPEC-v0.4 \xA7B)
|
|
2566
|
+
|
|
2567
|
+
Usage:
|
|
2568
|
+
moneyswitch ui [--port 4318] [--no-open]
|
|
2569
|
+
|
|
2570
|
+
Starts a web console on http://127.0.0.1:<port> (loopback only) and opens it
|
|
2571
|
+
with a one-time login link. Configure Claude Code / Codex: model key ("brain")
|
|
2572
|
+
+ MoneyKey ("wallet"), preview the exact config diff, then enable.
|
|
2573
|
+
|
|
2574
|
+
Environment: MONEYSWITCH_UI_PORT, MONEYSWITCH_UI_NO_OPEN=1.
|
|
2575
|
+
All paths follow HOME/USERPROFILE, CLAUDE_CONFIG_DIR and CODEX_HOME.`;
|
|
2576
|
+
function parseUiArgs(argv, env = process.env) {
|
|
2577
|
+
let port = env.MONEYSWITCH_UI_PORT ? Number(env.MONEYSWITCH_UI_PORT) : 4318;
|
|
2578
|
+
let open = env.MONEYSWITCH_UI_NO_OPEN !== "1";
|
|
2579
|
+
let help = false;
|
|
2580
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2581
|
+
const a = argv[i];
|
|
2582
|
+
if (a === "--port") {
|
|
2583
|
+
port = Number(argv[++i]);
|
|
2584
|
+
} else if (a.startsWith("--port=")) {
|
|
2585
|
+
port = Number(a.slice(7));
|
|
2586
|
+
} else if (a === "--no-open") {
|
|
2587
|
+
open = false;
|
|
2588
|
+
} else if (a === "--help" || a === "-h") {
|
|
2589
|
+
help = true;
|
|
2590
|
+
} else {
|
|
2591
|
+
return { error: `unknown argument: ${a}` };
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return { error: "--port must be 1-65535" };
|
|
2595
|
+
return { port, open, help };
|
|
2596
|
+
}
|
|
2597
|
+
function openBrowser(url) {
|
|
2598
|
+
const opts = { detached: true, stdio: "ignore", windowsHide: true };
|
|
2599
|
+
const child = process.platform === "win32" ? spawn("cmd", ["/c", "start", '""', `"${url}"`], { ...opts, windowsVerbatimArguments: true }) : spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], opts);
|
|
2600
|
+
child.on("error", () => void 0);
|
|
2601
|
+
child.unref();
|
|
2602
|
+
}
|
|
2603
|
+
async function runUi(argv) {
|
|
2604
|
+
const parsed = parseUiArgs(argv);
|
|
2605
|
+
if ("error" in parsed) {
|
|
2606
|
+
process.stderr.write(`moneyswitch ui: ${parsed.error}
|
|
2607
|
+
|
|
2608
|
+
${UI_HELP}
|
|
2609
|
+
`);
|
|
2610
|
+
return 2;
|
|
2611
|
+
}
|
|
2612
|
+
if (parsed.help) {
|
|
2613
|
+
process.stdout.write(UI_HELP + "\n");
|
|
2614
|
+
return 0;
|
|
2615
|
+
}
|
|
2616
|
+
const env = process.env;
|
|
2617
|
+
const service = new DesktopService({ env, runner: new RealCommandRunner({ env, timeoutMs: 6e4 }) });
|
|
2618
|
+
const sessions = new SessionManager(parsed.port);
|
|
2619
|
+
const assetsDir = path6.join(path6.dirname(fileURLToPath(import.meta.url)), "ui");
|
|
2620
|
+
const { server } = createUiServer({
|
|
2621
|
+
port: parsed.port,
|
|
2622
|
+
service,
|
|
2623
|
+
assetsDir,
|
|
2624
|
+
sessions,
|
|
2625
|
+
log: env.MONEYSWITCH_UI_DEBUG ? (l) => process.stderr.write(`[ui] ${l}
|
|
2626
|
+
`) : void 0
|
|
2627
|
+
});
|
|
2628
|
+
await new Promise((resolve, reject) => {
|
|
2629
|
+
server.once("error", reject);
|
|
2630
|
+
server.listen(parsed.port, "127.0.0.1", () => resolve());
|
|
2631
|
+
}).catch((e) => {
|
|
2632
|
+
if (e.code === "EADDRINUSE") {
|
|
2633
|
+
process.stderr.write(`moneyswitch ui: port ${parsed.port} is already in use (another console running?). Try --port ${parsed.port + 1}.
|
|
2634
|
+
`);
|
|
2635
|
+
} else {
|
|
2636
|
+
process.stderr.write(`moneyswitch ui: ${e.message}
|
|
2637
|
+
`);
|
|
2638
|
+
}
|
|
2639
|
+
process.exit(1);
|
|
2640
|
+
});
|
|
2641
|
+
const url = `http://127.0.0.1:${parsed.port}/#${sessions.pendingToken}`;
|
|
2642
|
+
process.stdout.write(
|
|
2643
|
+
`MoneySwitch desktop console: http://127.0.0.1:${parsed.port}
|
|
2644
|
+
One-time login link (do not share): ${url}
|
|
2645
|
+
Press Ctrl+C to stop.
|
|
2646
|
+
`
|
|
2647
|
+
);
|
|
2648
|
+
if (parsed.open) openBrowser(url);
|
|
2649
|
+
await new Promise((resolve) => {
|
|
2650
|
+
const stop = () => server.close(() => resolve());
|
|
2651
|
+
process.once("SIGINT", stop);
|
|
2652
|
+
process.once("SIGTERM", stop);
|
|
2653
|
+
});
|
|
2654
|
+
return 0;
|
|
2655
|
+
}
|
|
2656
|
+
export {
|
|
2657
|
+
UI_HELP,
|
|
2658
|
+
parseUiArgs,
|
|
2659
|
+
runUi
|
|
2660
|
+
};
|
|
2661
|
+
/*! Bundled license information:
|
|
2662
|
+
|
|
2663
|
+
smol-toml/dist/error.js:
|
|
2664
|
+
smol-toml/dist/primitive.js:
|
|
2665
|
+
smol-toml/dist/date.js:
|
|
2666
|
+
smol-toml/dist/extract.js:
|
|
2667
|
+
smol-toml/dist/util.js:
|
|
2668
|
+
smol-toml/dist/struct.js:
|
|
2669
|
+
smol-toml/dist/parse.js:
|
|
2670
|
+
smol-toml/dist/stringify.js:
|
|
2671
|
+
smol-toml/dist/index.js:
|
|
2672
|
+
(*!
|
|
2673
|
+
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
2674
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
2675
|
+
*
|
|
2676
|
+
* Redistribution and use in source and binary forms, with or without
|
|
2677
|
+
* modification, are permitted provided that the following conditions are met:
|
|
2678
|
+
*
|
|
2679
|
+
* 1. Redistributions of source code must retain the above copyright notice, this
|
|
2680
|
+
* list of conditions and the following disclaimer.
|
|
2681
|
+
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
2682
|
+
* this list of conditions and the following disclaimer in the
|
|
2683
|
+
* documentation and/or other materials provided with the distribution.
|
|
2684
|
+
* 3. Neither the name of the copyright holder nor the names of its contributors
|
|
2685
|
+
* may be used to endorse or promote products derived from this software without
|
|
2686
|
+
* specific prior written permission.
|
|
2687
|
+
*
|
|
2688
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
2689
|
+
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
2690
|
+
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
2691
|
+
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
2692
|
+
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
2693
|
+
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
2694
|
+
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
2695
|
+
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
2696
|
+
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
2697
|
+
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
2698
|
+
*)
|
|
2699
|
+
*/
|