aimc-host 0.2.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 +21 -0
- package/README.md +164 -0
- package/dist/auth.js +202 -0
- package/dist/cli.js +285 -0
- package/dist/config.js +123 -0
- package/dist/ollama.js +145 -0
- package/dist/runner.js +293 -0
- package/dist/server-client.js +76 -0
- package/dist/service.js +342 -0
- package/dist/telemetry.js +27 -0
- package/dist/version.js +71 -0
- package/package.json +42 -0
package/dist/service.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
3
|
+
import { chmod, chown, copyFile, cp, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, relative, sep } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { AgentFiles, configDir } from "./config.js";
|
|
8
|
+
import { PACKAGE_NAME } from "./version.js";
|
|
9
|
+
// The agent as a systemd service (Linux): `install-service`, `uninstall-service` and `service`.
|
|
10
|
+
//
|
|
11
|
+
// The service runs as its own unprivileged user with ProtectHome=yes, so neither Node nor the
|
|
12
|
+
// agent may live in a home folder. A Node from nvm and a global npm install under nvm both do.
|
|
13
|
+
// So install-service copies the agent (and its two dependencies) to /opt/aimc-host, and Node too
|
|
14
|
+
// when it lives in a home folder. Re-run it after every update: it replaces the copy and
|
|
15
|
+
// restarts the service.
|
|
16
|
+
//
|
|
17
|
+
// Settings and the sign-in of the service live in /var/lib/ai-my-card-host/ai-my-card-host
|
|
18
|
+
// (XDG_CONFIG_HOME=/var/lib/ai-my-card-host), readable only by the service user.
|
|
19
|
+
export const SERVICE_NAME = "ai-my-card-host-agent";
|
|
20
|
+
export const SERVICE_USER = "ai-my-card-host";
|
|
21
|
+
export const STATE_DIR = "/var/lib/ai-my-card-host";
|
|
22
|
+
export const INSTALL_DIR = "/opt/aimc-host";
|
|
23
|
+
export const UNIT_PATH = `/etc/systemd/system/${SERVICE_NAME}.service`;
|
|
24
|
+
/** Written by install-service: which Node and which agent the service runs. */
|
|
25
|
+
const INSTALL_INFO = join(INSTALL_DIR, "install.json");
|
|
26
|
+
/** The systemd unit. Exit code 3 means retrying is pointless (host retired, signed out...). */
|
|
27
|
+
export function renderUnit({ nodePath, cliPath }) {
|
|
28
|
+
return `# aimc-host: lends this GPU to an aimc server. Written by \`${PACKAGE_NAME} install-service\`;
|
|
29
|
+
# run it again after an update instead of editing this file.
|
|
30
|
+
#
|
|
31
|
+
# Runs as its own unprivileged user. Its settings and sign-in live in
|
|
32
|
+
# ${STATE_DIR}/ai-my-card-host (XDG_CONFIG_HOME below), readable only by that user.
|
|
33
|
+
|
|
34
|
+
[Unit]
|
|
35
|
+
Description=aimc host agent (lends this GPU to an aimc server)
|
|
36
|
+
Documentation=https://www.npmjs.com/package/${PACKAGE_NAME}
|
|
37
|
+
After=network-online.target ollama.service
|
|
38
|
+
Wants=network-online.target
|
|
39
|
+
|
|
40
|
+
[Service]
|
|
41
|
+
Type=simple
|
|
42
|
+
User=${SERVICE_USER}
|
|
43
|
+
Group=${SERVICE_USER}
|
|
44
|
+
WorkingDirectory=${INSTALL_DIR}
|
|
45
|
+
Environment=XDG_CONFIG_HOME=${STATE_DIR}
|
|
46
|
+
ExecStart=${nodePath} ${cliPath} start
|
|
47
|
+
Restart=on-failure
|
|
48
|
+
RestartSec=30
|
|
49
|
+
RestartPreventExitStatus=3
|
|
50
|
+
KillSignal=SIGTERM
|
|
51
|
+
TimeoutStopSec=20
|
|
52
|
+
|
|
53
|
+
# Hardening: it only needs the network, Ollama, nvidia-smi and its own folder.
|
|
54
|
+
StateDirectory=ai-my-card-host
|
|
55
|
+
StateDirectoryMode=0700
|
|
56
|
+
NoNewPrivileges=yes
|
|
57
|
+
ProtectSystem=strict
|
|
58
|
+
ProtectHome=yes
|
|
59
|
+
PrivateTmp=yes
|
|
60
|
+
ProtectKernelTunables=yes
|
|
61
|
+
ProtectKernelModules=yes
|
|
62
|
+
ProtectKernelLogs=yes
|
|
63
|
+
ProtectControlGroups=yes
|
|
64
|
+
ProtectClock=yes
|
|
65
|
+
ProtectHostname=yes
|
|
66
|
+
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
|
67
|
+
RestrictNamespaces=yes
|
|
68
|
+
RestrictRealtime=yes
|
|
69
|
+
RestrictSUIDSGID=yes
|
|
70
|
+
LockPersonality=yes
|
|
71
|
+
SystemCallArchitectures=native
|
|
72
|
+
# Not PrivateDevices: nvidia-smi needs /dev/nvidia* for the GPU telemetry.
|
|
73
|
+
|
|
74
|
+
[Install]
|
|
75
|
+
WantedBy=multi-user.target
|
|
76
|
+
`;
|
|
77
|
+
}
|
|
78
|
+
/** True for paths the service can't see (ProtectHome=yes): /home, /root, /run/user. */
|
|
79
|
+
export function inHomeFolder(path, home = homedir()) {
|
|
80
|
+
const p = path.replace(/\/+$/, "");
|
|
81
|
+
return ["/home", "/root", "/run/user", home].some((h) => h && h !== "/" && (p === h || p.startsWith(`${h}/`)));
|
|
82
|
+
}
|
|
83
|
+
/** Where this running agent's package is (the folder with its package.json). */
|
|
84
|
+
export function ownPackageDir() {
|
|
85
|
+
return dirname(dirname(fileURLToPath(import.meta.url)));
|
|
86
|
+
}
|
|
87
|
+
const readPackage = (dir) => JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
88
|
+
/** Node's lookup: <dir>/node_modules/<name>, then the same in each parent folder. */
|
|
89
|
+
function findDependency(fromDir, name) {
|
|
90
|
+
for (let dir = fromDir;; dir = dirname(dir)) {
|
|
91
|
+
const candidate = join(dir, "node_modules", ...name.split("/"));
|
|
92
|
+
if (existsSync(join(candidate, "package.json")))
|
|
93
|
+
return realpathSync(candidate);
|
|
94
|
+
if (dirname(dir) === dir)
|
|
95
|
+
throw new Error(`Can't find ${name} (needed by the agent). Reinstall: npm install -g ${PACKAGE_NAME}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** The agent's package and every package it needs, by name: what goes to /opt/aimc-host/node_modules. */
|
|
99
|
+
export function packagesToCopy(rootDir = ownPackageDir()) {
|
|
100
|
+
const found = new Map();
|
|
101
|
+
const visit = (name, dir) => {
|
|
102
|
+
const pkg = readPackage(dir);
|
|
103
|
+
const seen = found.get(name);
|
|
104
|
+
if (seen) {
|
|
105
|
+
if (readPackage(seen).version !== pkg.version)
|
|
106
|
+
throw new Error(`Two versions of ${name} are installed; reinstall the agent.`);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
found.set(name, dir);
|
|
110
|
+
for (const dep of Object.keys(pkg.dependencies ?? {}))
|
|
111
|
+
visit(dep, findDependency(dir, dep));
|
|
112
|
+
};
|
|
113
|
+
visit(readPackage(rootDir).name, realpathSync(rootDir));
|
|
114
|
+
return found;
|
|
115
|
+
}
|
|
116
|
+
const run = (cmd, args) => execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" }).trim();
|
|
117
|
+
const tryRun = (cmd, args) => {
|
|
118
|
+
try {
|
|
119
|
+
return run(cmd, args);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
function isRoot() {
|
|
126
|
+
return typeof process.getuid === "function" && process.getuid() === 0;
|
|
127
|
+
}
|
|
128
|
+
function requireLinux(command) {
|
|
129
|
+
if (process.platform !== "linux") {
|
|
130
|
+
throw new Error(`${command} is for Linux with systemd. On Windows, keep \`${PACKAGE_NAME} start\` running in a terminal, or start it at login with a shortcut in your Startup folder.`);
|
|
131
|
+
}
|
|
132
|
+
if (!existsSync("/run/systemd/system"))
|
|
133
|
+
throw new Error(`${command} needs systemd, which isn't running on this machine.`);
|
|
134
|
+
}
|
|
135
|
+
/** Runs this same command again as root, through sudo (asks for your password). */
|
|
136
|
+
function elevate(args) {
|
|
137
|
+
const cli = realpathSync(process.argv[1] ?? "");
|
|
138
|
+
console.log(`This needs root: running it with sudo.`);
|
|
139
|
+
const result = spawnSync("sudo", [process.execPath, ...process.execArgv, cli, ...args], { stdio: "inherit" });
|
|
140
|
+
if (result.error)
|
|
141
|
+
throw new Error(`Couldn't run sudo: ${result.error.message}`);
|
|
142
|
+
return result.status ?? 1;
|
|
143
|
+
}
|
|
144
|
+
function serviceIds() {
|
|
145
|
+
const uid = tryRun("id", ["-u", SERVICE_USER]);
|
|
146
|
+
const gid = tryRun("id", ["-g", SERVICE_USER]);
|
|
147
|
+
return uid && gid ? { uid: Number(uid), gid: Number(gid) } : null;
|
|
148
|
+
}
|
|
149
|
+
/** The service's settings: are sign-in, host and models there, so it can start? */
|
|
150
|
+
async function serviceReady() {
|
|
151
|
+
const files = new AgentFiles(join(STATE_DIR, "ai-my-card-host"), "linux");
|
|
152
|
+
const missing = [];
|
|
153
|
+
try {
|
|
154
|
+
const config = await files.loadConfig();
|
|
155
|
+
if (!config.serverUrl || !(await files.loadCredentials()))
|
|
156
|
+
missing.push("login");
|
|
157
|
+
if (!config.hostId)
|
|
158
|
+
missing.push("register");
|
|
159
|
+
if (config.models.length === 0)
|
|
160
|
+
missing.push("config --models");
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
missing.push("login");
|
|
164
|
+
}
|
|
165
|
+
return { ready: missing.length === 0, missing };
|
|
166
|
+
}
|
|
167
|
+
export async function installService(o) {
|
|
168
|
+
const packages = packagesToCopy();
|
|
169
|
+
const execNode = realpathSync(process.execPath);
|
|
170
|
+
const copyNode = inHomeFolder(execNode, process.env.SUDO_USER ? `/home/${process.env.SUDO_USER}` : homedir());
|
|
171
|
+
const nodePath = copyNode ? join(INSTALL_DIR, "bin", "node") : execNode;
|
|
172
|
+
const cliPath = join(INSTALL_DIR, "node_modules", PACKAGE_NAME, "dist", "cli.js");
|
|
173
|
+
const version = readPackage(packages.get(PACKAGE_NAME) ?? ownPackageDir()).version;
|
|
174
|
+
if (o.dryRun) {
|
|
175
|
+
console.log(`install-service would, as root:
|
|
176
|
+
1. create the system user ${SERVICE_USER} (if missing) and ${STATE_DIR} (mode 700)
|
|
177
|
+
2. copy ${PACKAGE_NAME} ${version} and its packages to ${INSTALL_DIR}/node_modules:
|
|
178
|
+
${[...packages].map(([name, dir]) => ` ${name} from ${dir}`).join("\n")}
|
|
179
|
+
3. ${copyNode ? `copy Node ${process.version} from ${execNode} to ${nodePath} (it lives in a home folder, which the service can't see)` : `use Node ${process.version} at ${nodePath}`}
|
|
180
|
+
4. ${o.copySettings ? `copy your settings and sign-in from ${configDir()} to ${STATE_DIR}/ai-my-card-host (if the service has none yet)` : "keep the service's own settings (add --copy-settings to bring yours)"}
|
|
181
|
+
5. write ${UNIT_PATH}, enable it${o.noStart ? "" : " and (re)start it once signed in, registered and configured"}
|
|
182
|
+
|
|
183
|
+
The unit:
|
|
184
|
+
`);
|
|
185
|
+
console.log(renderUnit({ nodePath, cliPath }));
|
|
186
|
+
return 0;
|
|
187
|
+
}
|
|
188
|
+
requireLinux("install-service");
|
|
189
|
+
if (!isRoot()) {
|
|
190
|
+
const args = ["install-service"];
|
|
191
|
+
if (o.copySettings)
|
|
192
|
+
args.push("--copy-settings", "--settings-from", configDir());
|
|
193
|
+
if (o.noStart)
|
|
194
|
+
args.push("--no-start");
|
|
195
|
+
return elevate(args);
|
|
196
|
+
}
|
|
197
|
+
// 1. The service user and its private folder.
|
|
198
|
+
if (!serviceIds()) {
|
|
199
|
+
run("useradd", ["--system", "--home-dir", STATE_DIR, "--shell", "/usr/sbin/nologin", SERVICE_USER]);
|
|
200
|
+
console.log(`Created the system user ${SERVICE_USER}.`);
|
|
201
|
+
}
|
|
202
|
+
const ids = serviceIds();
|
|
203
|
+
if (!ids)
|
|
204
|
+
throw new Error(`Couldn't create the user ${SERVICE_USER}.`);
|
|
205
|
+
const settingsDir = join(STATE_DIR, "ai-my-card-host");
|
|
206
|
+
for (const dir of [STATE_DIR, settingsDir]) {
|
|
207
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
208
|
+
await chown(dir, ids.uid, ids.gid);
|
|
209
|
+
await chmod(dir, 0o700);
|
|
210
|
+
}
|
|
211
|
+
// 2 + 3. A fresh copy of the agent (and Node), swapped in at once.
|
|
212
|
+
const staging = `${INSTALL_DIR}.new`;
|
|
213
|
+
await rm(staging, { recursive: true, force: true });
|
|
214
|
+
for (const [name, dir] of packages) {
|
|
215
|
+
const target = join(staging, "node_modules", ...name.split("/"));
|
|
216
|
+
await cp(dir, target, {
|
|
217
|
+
recursive: true,
|
|
218
|
+
dereference: true,
|
|
219
|
+
// Not the package's own node_modules: its dependencies are copied next to it.
|
|
220
|
+
filter: (src) => !relative(dir, src).split(sep).includes("node_modules"),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
if (copyNode) {
|
|
224
|
+
await mkdir(join(staging, "bin"), { recursive: true, mode: 0o755 });
|
|
225
|
+
await copyFile(execNode, join(staging, "bin", "node"));
|
|
226
|
+
await chmod(join(staging, "bin", "node"), 0o755);
|
|
227
|
+
}
|
|
228
|
+
await writeFile(join(staging, "install.json"), `${JSON.stringify({ version, nodePath, cliPath, installedAt: new Date().toISOString() }, null, 2)}\n`);
|
|
229
|
+
await chmod(staging, 0o755);
|
|
230
|
+
const old = `${INSTALL_DIR}.old`;
|
|
231
|
+
await rm(old, { recursive: true, force: true });
|
|
232
|
+
if (existsSync(INSTALL_DIR))
|
|
233
|
+
await rename(INSTALL_DIR, old);
|
|
234
|
+
await rename(staging, INSTALL_DIR);
|
|
235
|
+
await rm(old, { recursive: true, force: true });
|
|
236
|
+
console.log(`Installed ${PACKAGE_NAME} ${version} in ${INSTALL_DIR}${copyNode ? `, with Node ${process.version}` : ""}.`);
|
|
237
|
+
// 4. Your settings, if asked and the service has none yet.
|
|
238
|
+
if (o.copySettings && o.settingsFrom) {
|
|
239
|
+
for (const file of ["config.json", "credentials.json"]) {
|
|
240
|
+
const from = join(o.settingsFrom, file);
|
|
241
|
+
const to = join(settingsDir, file);
|
|
242
|
+
if (!existsSync(from))
|
|
243
|
+
continue;
|
|
244
|
+
if (existsSync(to)) {
|
|
245
|
+
console.log(`Kept the service's own ${file} (delete ${to} first to replace it).`);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
await copyFile(from, to);
|
|
249
|
+
await chown(to, ids.uid, ids.gid);
|
|
250
|
+
await chmod(to, 0o600);
|
|
251
|
+
console.log(`Copied your ${file} to the service.`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
// 5. The unit.
|
|
255
|
+
await writeFile(UNIT_PATH, renderUnit({ nodePath, cliPath }), { mode: 0o644 });
|
|
256
|
+
run("systemctl", ["daemon-reload"]);
|
|
257
|
+
run("systemctl", ["enable", SERVICE_NAME]);
|
|
258
|
+
console.log(`Wrote ${UNIT_PATH} and enabled it (it starts at boot).`);
|
|
259
|
+
const { ready, missing } = await serviceReady();
|
|
260
|
+
if (!ready) {
|
|
261
|
+
console.log(`\nThe service isn't set up yet. Do these once, as the service:`);
|
|
262
|
+
for (const step of missing) {
|
|
263
|
+
const example = step === "login" ? "login --server https://your-server.example" : step === "register" ? "register --name <a name for this machine>" : "config --models <models, comma-separated>";
|
|
264
|
+
console.log(` ${PACKAGE_NAME} service ${example}`);
|
|
265
|
+
}
|
|
266
|
+
console.log(`Then: sudo systemctl start ${SERVICE_NAME}`);
|
|
267
|
+
if (!o.copySettings && existsSync(join(configDir(), "credentials.json"))) {
|
|
268
|
+
console.log(`(Or bring the settings you already have: ${PACKAGE_NAME} install-service --copy-settings)`);
|
|
269
|
+
}
|
|
270
|
+
return 0;
|
|
271
|
+
}
|
|
272
|
+
if (o.noStart) {
|
|
273
|
+
console.log(`Start it with: sudo systemctl start ${SERVICE_NAME}`);
|
|
274
|
+
return 0;
|
|
275
|
+
}
|
|
276
|
+
run("systemctl", ["restart", SERVICE_NAME]);
|
|
277
|
+
console.log(`Started. Its log: journalctl -u ${SERVICE_NAME} -f`);
|
|
278
|
+
console.log(`Don't also run \`${PACKAGE_NAME} start\` for the same host elsewhere: one connection per host.`);
|
|
279
|
+
return 0;
|
|
280
|
+
}
|
|
281
|
+
export async function uninstallService(o) {
|
|
282
|
+
if (o.dryRun) {
|
|
283
|
+
console.log(`uninstall-service would stop and disable ${SERVICE_NAME}, delete ${UNIT_PATH} and ${INSTALL_DIR}${o.purge ? `, and delete the service's settings and sign-in (${STATE_DIR}) and the user ${SERVICE_USER}` : `. The service's settings and sign-in in ${STATE_DIR} stay (--purge deletes them).`}`);
|
|
284
|
+
return 0;
|
|
285
|
+
}
|
|
286
|
+
requireLinux("uninstall-service");
|
|
287
|
+
if (!isRoot())
|
|
288
|
+
return elevate(["uninstall-service", ...(o.purge ? ["--purge"] : [])]);
|
|
289
|
+
tryRun("systemctl", ["disable", "--now", SERVICE_NAME]);
|
|
290
|
+
await rm(UNIT_PATH, { force: true });
|
|
291
|
+
tryRun("systemctl", ["daemon-reload"]);
|
|
292
|
+
await rm(INSTALL_DIR, { recursive: true, force: true });
|
|
293
|
+
console.log(`Removed the service ${SERVICE_NAME} and ${INSTALL_DIR}.`);
|
|
294
|
+
if (o.purge) {
|
|
295
|
+
await rm(STATE_DIR, { recursive: true, force: true });
|
|
296
|
+
tryRun("userdel", [SERVICE_USER]);
|
|
297
|
+
console.log(`Deleted the service's settings and sign-in, and the user ${SERVICE_USER}. The host stays registered on the server until you retire it there.`);
|
|
298
|
+
}
|
|
299
|
+
else {
|
|
300
|
+
console.log(`The service's settings and sign-in stay in ${STATE_DIR} (uninstall-service --purge deletes them).`);
|
|
301
|
+
}
|
|
302
|
+
return 0;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* `service <command>`: runs an agent command as the service user, with the service's settings
|
|
306
|
+
* (e.g. `service login --server ...`, `service status`). Uses the copy in /opt/aimc-host.
|
|
307
|
+
*/
|
|
308
|
+
export async function runAsService(args) {
|
|
309
|
+
requireLinux("service");
|
|
310
|
+
if (args[0] === "start") {
|
|
311
|
+
throw new Error(`The service runs the agent itself: sudo systemctl start ${SERVICE_NAME} (log: journalctl -u ${SERVICE_NAME} -f).`);
|
|
312
|
+
}
|
|
313
|
+
if (!isRoot())
|
|
314
|
+
return elevate(["service", ...args]);
|
|
315
|
+
let info;
|
|
316
|
+
try {
|
|
317
|
+
info = JSON.parse(await readFile(INSTALL_INFO, "utf8"));
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
throw new Error(`The service isn't installed. Run: ${PACKAGE_NAME} install-service`);
|
|
321
|
+
}
|
|
322
|
+
const ids = serviceIds();
|
|
323
|
+
if (!ids)
|
|
324
|
+
throw new Error(`The user ${SERVICE_USER} doesn't exist. Run: ${PACKAGE_NAME} install-service`);
|
|
325
|
+
const result = spawnSync(info.nodePath, [info.cliPath, ...args], {
|
|
326
|
+
stdio: "inherit",
|
|
327
|
+
cwd: INSTALL_DIR,
|
|
328
|
+
uid: ids.uid,
|
|
329
|
+
gid: ids.gid,
|
|
330
|
+
env: {
|
|
331
|
+
PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
|
332
|
+
HOME: STATE_DIR,
|
|
333
|
+
XDG_CONFIG_HOME: STATE_DIR,
|
|
334
|
+
AIMC_RUN: `${PACKAGE_NAME} service`,
|
|
335
|
+
...(process.env.LANG ? { LANG: process.env.LANG } : {}),
|
|
336
|
+
...(process.env.TERM ? { TERM: process.env.TERM } : {}),
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
if (result.error)
|
|
340
|
+
throw new Error(`Couldn't run the agent as ${SERVICE_USER}: ${result.error.message}`);
|
|
341
|
+
return result.status ?? 1;
|
|
342
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
/** Parses `nvidia-smi --query-gpu=... --format=csv,noheader,nounits` (the first GPU). */
|
|
3
|
+
export function parseNvidiaSmi(output) {
|
|
4
|
+
const line = output.split(/\r?\n/).find((l) => l.trim());
|
|
5
|
+
if (!line)
|
|
6
|
+
return null;
|
|
7
|
+
const parts = line.split(",").map((p) => p.trim());
|
|
8
|
+
if (parts.length < 5)
|
|
9
|
+
return null;
|
|
10
|
+
const [name, total, used, util, temp] = parts;
|
|
11
|
+
const numbers = [total, used, util, temp].map((v) => Number(v));
|
|
12
|
+
if (!name || numbers.some((n) => !Number.isFinite(n)))
|
|
13
|
+
return null;
|
|
14
|
+
const [vramTotalMb, vramUsedMb, utilizationPct, temperatureC] = numbers;
|
|
15
|
+
return {
|
|
16
|
+
name: name.slice(0, 100),
|
|
17
|
+
vramTotalMb: Math.round(vramTotalMb),
|
|
18
|
+
vramUsedMb: Math.round(vramUsedMb),
|
|
19
|
+
utilizationPct: Math.min(100, Math.max(0, utilizationPct)),
|
|
20
|
+
temperatureC,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function readGpu() {
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
execFile("nvidia-smi", ["--query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu", "--format=csv,noheader,nounits"], { timeout: 3000, windowsHide: true }, (err, stdout) => resolve(err ? null : parseNvidiaSmi(stdout)));
|
|
26
|
+
});
|
|
27
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
// This agent's version (from its package.json) and the update notice the server can trigger.
|
|
3
|
+
export const PACKAGE_NAME = "aimc-host";
|
|
4
|
+
export const AGENT_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
5
|
+
/**
|
|
6
|
+
* Compares two versions like 0.2.0 or 1.4.0-beta.1: negative when a < b, 0 when equal, positive
|
|
7
|
+
* when a > b. Pre-releases sort before their release. Null when either isn't a version.
|
|
8
|
+
*/
|
|
9
|
+
export function compareVersions(a, b) {
|
|
10
|
+
const parse = (v) => /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(v.trim());
|
|
11
|
+
const x = parse(a);
|
|
12
|
+
const y = parse(b);
|
|
13
|
+
if (!x || !y)
|
|
14
|
+
return null;
|
|
15
|
+
for (let i = 1; i <= 3; i++) {
|
|
16
|
+
const d = Number(x[i]) - Number(y[i]);
|
|
17
|
+
if (d !== 0)
|
|
18
|
+
return d;
|
|
19
|
+
}
|
|
20
|
+
const [px, py] = [x[4], y[4]];
|
|
21
|
+
if (px === py)
|
|
22
|
+
return 0;
|
|
23
|
+
if (px === undefined)
|
|
24
|
+
return 1;
|
|
25
|
+
if (py === undefined)
|
|
26
|
+
return -1;
|
|
27
|
+
const ax = px.split(".");
|
|
28
|
+
const ay = py.split(".");
|
|
29
|
+
for (let i = 0; i < Math.max(ax.length, ay.length); i++) {
|
|
30
|
+
const [p, q] = [ax[i], ay[i]];
|
|
31
|
+
if (p === undefined)
|
|
32
|
+
return -1;
|
|
33
|
+
if (q === undefined)
|
|
34
|
+
return 1;
|
|
35
|
+
if (p === q)
|
|
36
|
+
continue;
|
|
37
|
+
const [np, nq] = [Number(p), Number(q)];
|
|
38
|
+
if (Number.isInteger(np) && Number.isInteger(nq))
|
|
39
|
+
return np - nq;
|
|
40
|
+
if (Number.isInteger(np))
|
|
41
|
+
return -1;
|
|
42
|
+
if (Number.isInteger(nq))
|
|
43
|
+
return 1;
|
|
44
|
+
return p < q ? -1 : 1;
|
|
45
|
+
}
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
/** Running under systemd (it sets INVOCATION_ID for every service it starts). */
|
|
49
|
+
export function runsAsService(env = process.env) {
|
|
50
|
+
return Boolean(env.INVOCATION_ID);
|
|
51
|
+
}
|
|
52
|
+
/** How to update to `version`, for the way this agent runs. */
|
|
53
|
+
export function updateCommand(version, env = process.env) {
|
|
54
|
+
if (runsAsService(env))
|
|
55
|
+
return `npm install -g ${PACKAGE_NAME}@${version}, then: ${PACKAGE_NAME} install-service`;
|
|
56
|
+
if (env.npm_command === "exec")
|
|
57
|
+
return `npx ${PACKAGE_NAME}@${version} start`;
|
|
58
|
+
return `npm install -g ${PACKAGE_NAME}@${version}`;
|
|
59
|
+
}
|
|
60
|
+
/** What the server's hello says about this agent's version. */
|
|
61
|
+
export function versionAdvice(current, hello) {
|
|
62
|
+
const min = hello.minAgentVersion;
|
|
63
|
+
if (min && (compareVersions(current, min) ?? 0) < 0) {
|
|
64
|
+
return { kind: "too_old", message: `This server needs host agent ${min} or newer; this is ${current}. Update: ${updateCommand(hello.latestAgentVersion ?? min)}` };
|
|
65
|
+
}
|
|
66
|
+
const latest = hello.latestAgentVersion;
|
|
67
|
+
if (latest && (compareVersions(current, latest) ?? 0) < 0) {
|
|
68
|
+
return { kind: "update", message: `A newer host agent is available: ${latest} (this is ${current}). Update: ${updateCommand(latest)}` };
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "aimc-host",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Lend your GPU: connects your local Ollama to an aimc server. Outgoing HTTPS only, no open ports",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ollama",
|
|
7
|
+
"gpu",
|
|
8
|
+
"llm",
|
|
9
|
+
"host",
|
|
10
|
+
"agent",
|
|
11
|
+
"cli"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"homepage": "https://github.com/alkapa-com/aimc-host/tree/main/packages/host#readme",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/alkapa-com/aimc-host.git",
|
|
18
|
+
"directory": "packages/host"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/alkapa-com/aimc-host/issues"
|
|
22
|
+
},
|
|
23
|
+
"author": "alkapa.com <info@alkapa.com>",
|
|
24
|
+
"type": "module",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22.12"
|
|
27
|
+
},
|
|
28
|
+
"bin": {
|
|
29
|
+
"aimc-host": "dist/cli.js"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "node ../../scripts/clean.mjs dist && tsc -p tsconfig.build.json",
|
|
36
|
+
"prepack": "npm run build"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"aimc-protocol": "1.0.0",
|
|
40
|
+
"zod": "4.6.7"
|
|
41
|
+
}
|
|
42
|
+
}
|