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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 alkapa.com
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# aimc-host
|
|
2
|
+
|
|
3
|
+
Lend your GPU to an aimc server. `aimc-host` connects the [Ollama](https://ollama.com) on your
|
|
4
|
+
machine to the server: the server sends chat requests for the models you offer, your Ollama
|
|
5
|
+
answers them. The server's admin approves your machine and sets what you earn for it.
|
|
6
|
+
|
|
7
|
+
- **Outgoing HTTPS only.** You open no ports; the agent connects to the server.
|
|
8
|
+
- **Only what you offer.** It runs only the models you list, and calls only four Ollama
|
|
9
|
+
endpoints: chat, the installed models, the loaded models, and the version. The server can't
|
|
10
|
+
make it pull, delete or change anything on your machine.
|
|
11
|
+
- **Nothing private in the log.** It logs job ids, models, token counts and times; never
|
|
12
|
+
prompts, answers or images.
|
|
13
|
+
|
|
14
|
+
## What you need
|
|
15
|
+
|
|
16
|
+
- An account on an aimc server, approved by its admin, and the server's address
|
|
17
|
+
(`https://...`).
|
|
18
|
+
- [Node.js](https://nodejs.org) 22.12 or newer.
|
|
19
|
+
- Ollama, with the models you want to offer (`ollama pull <model>`). An NVIDIA GPU is
|
|
20
|
+
optional; with `nvidia-smi` the agent reports its name, memory, load and temperature.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install -g aimc-host
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or run it without installing: put `npx` in front of every command below
|
|
29
|
+
(`npx aimc-host login ...`).
|
|
30
|
+
|
|
31
|
+
## First time: sign in, register, choose models
|
|
32
|
+
|
|
33
|
+
These three are needed once per machine. The agent remembers your sign-in and settings.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
aimc-host login --server https://your-server.example
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
It prints a link and a short code. Open the link on any device (your phone works), sign in and
|
|
40
|
+
confirm the code. The agent says **Signed in**.
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
aimc-host register --name my-desktop
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
This adds your machine as a host, **waiting for an admin's approval**.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
aimc-host config --models llama3.2:3b,gemma3:12b
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The models you offer, comma-separated, as `ollama list` names them. It warns about any that
|
|
53
|
+
aren't installed.
|
|
54
|
+
|
|
55
|
+
## Run
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
aimc-host start
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
While the host waits for approval, the agent says so and checks once a minute. Once approved it
|
|
62
|
+
prints **Connected** and takes requests; each finished job shows one line (model, tokens, time).
|
|
63
|
+
Ctrl+C stops it cleanly within a few seconds.
|
|
64
|
+
|
|
65
|
+
`aimc-host status` shows your settings, Ollama, the GPU, whether the server is reachable, and
|
|
66
|
+
your sign-in. `aimc-host help` lists every command.
|
|
67
|
+
|
|
68
|
+
## Keep it running
|
|
69
|
+
|
|
70
|
+
### Linux (systemd)
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
aimc-host install-service --copy-settings
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
It asks for your password (sudo), then:
|
|
77
|
+
1. creates a system user `ai-my-card-host` with a private folder `/var/lib/ai-my-card-host`;
|
|
78
|
+
2. copies the agent to `/opt/aimc-host`, and Node too if yours lives in your home folder (nvm).
|
|
79
|
+
The service may not read home folders;
|
|
80
|
+
3. with `--copy-settings`, gives the service a copy of your sign-in and settings;
|
|
81
|
+
4. installs, enables and starts the unit `ai-my-card-host-agent` (started at boot, restarted
|
|
82
|
+
30 s after a crash or a network problem).
|
|
83
|
+
|
|
84
|
+
Then stop running `aimc-host start` yourself: one connection per host. Watch the service with
|
|
85
|
+
`journalctl -u ai-my-card-host-agent -f`.
|
|
86
|
+
|
|
87
|
+
Without `--copy-settings`, set the service up as the service itself:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
aimc-host service login --server https://your-server.example
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Then the same with `register --name ...` and `config --models ...`, and
|
|
94
|
+
`sudo systemctl start ai-my-card-host-agent`. `aimc-host service status` shows the service's
|
|
95
|
+
settings and sign-in.
|
|
96
|
+
|
|
97
|
+
`aimc-host install-service --dry-run` shows what it would do, without changing anything.
|
|
98
|
+
`aimc-host uninstall-service` removes it (`--purge` also deletes its sign-in and settings).
|
|
99
|
+
|
|
100
|
+
If the server said retrying is pointless (host retired, account suspended, signed out, agent too
|
|
101
|
+
old), the agent exits with code 3 and the service doesn't restart it; the log says why.
|
|
102
|
+
|
|
103
|
+
### Windows
|
|
104
|
+
|
|
105
|
+
Keep `aimc-host start` running in a terminal. To start it at login, put a shortcut to
|
|
106
|
+
`aimc-host start` in your Startup folder (Win+R, `shell:startup`).
|
|
107
|
+
|
|
108
|
+
If PowerShell says *running scripts is disabled on this system*, run `aimc-host.cmd` instead
|
|
109
|
+
of `aimc-host`, or allow signed scripts for your user:
|
|
110
|
+
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`.
|
|
111
|
+
|
|
112
|
+
## Update
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
npm install -g aimc-host@latest
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Then restart the agent. As a service, run `aimc-host install-service` again (it replaces the
|
|
119
|
+
copy and restarts the service). Your sign-in and settings stay.
|
|
120
|
+
|
|
121
|
+
When the server recommends a newer agent, the agent says so once, with the command to run. When
|
|
122
|
+
the server needs a newer one, the agent stops and says which version.
|
|
123
|
+
|
|
124
|
+
## Sign out
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
aimc-host logout
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
It revokes the sign-in at the sign-in server, then deletes it from this machine.
|
|
131
|
+
|
|
132
|
+
## Your sign-in is a secret
|
|
133
|
+
|
|
134
|
+
`login` stores a long-lived sign-in (an OAuth refresh token) in `credentials.json`:
|
|
135
|
+
|
|
136
|
+
| | Folder |
|
|
137
|
+
|---|---|
|
|
138
|
+
| Windows | `%APPDATA%\ai-my-card-host` |
|
|
139
|
+
| Linux, macOS | `~/.config/ai-my-card-host` (or `$XDG_CONFIG_HOME/ai-my-card-host`), mode 600 |
|
|
140
|
+
| The Linux service | `/var/lib/ai-my-card-host/ai-my-card-host`, readable only by the service user |
|
|
141
|
+
|
|
142
|
+
Anyone with that file can act as your host. Don't copy it around, don't commit it; if it
|
|
143
|
+
leaked, run `aimc-host logout` (or ask the admin to revoke it). It ends by itself when unused
|
|
144
|
+
for 30 days.
|
|
145
|
+
|
|
146
|
+
## Troubleshooting
|
|
147
|
+
|
|
148
|
+
- **"... doesn't look like an aimc server":** check the address (`https://`, no path).
|
|
149
|
+
- **"Is Ollama running?":** start Ollama; if it listens elsewhere,
|
|
150
|
+
`aimc-host config --ollama http://<host>:11434`.
|
|
151
|
+
- **The server refuses the sign-in:** `aimc-host status` shows a **Problem** line; send it to
|
|
152
|
+
the server's admin.
|
|
153
|
+
- **Jobs fail for one model:** check `ollama list` has exactly the name you offer.
|
|
154
|
+
|
|
155
|
+
## How it works
|
|
156
|
+
|
|
157
|
+
`start` says hello to the server (versions, offered models, GPU), opens a job stream
|
|
158
|
+
(Server-Sent Events), and runs each job on your Ollama, sending the answer back in small
|
|
159
|
+
numbered batches. A heartbeat with GPU telemetry goes out every 15 seconds. The messages are
|
|
160
|
+
defined in [aimc-protocol](https://www.npmjs.com/package/aimc-protocol).
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
MIT
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { agentConfigResponse } from "aimc-protocol/agent";
|
|
2
|
+
async function getJson(fetchFn, url, init) {
|
|
3
|
+
const res = await fetchFn(url, { ...init, signal: init?.signal ?? AbortSignal.timeout(15_000) });
|
|
4
|
+
let body = null;
|
|
5
|
+
try {
|
|
6
|
+
body = await res.json();
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
// not JSON
|
|
10
|
+
}
|
|
11
|
+
return { status: res.status, body };
|
|
12
|
+
}
|
|
13
|
+
export async function fetchServerConfig(fetchFn, serverUrl) {
|
|
14
|
+
let result;
|
|
15
|
+
try {
|
|
16
|
+
result = await getJson(fetchFn, `${serverUrl}/api/agent/v1/config`);
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
throw new Error(`Can't reach ${serverUrl}: ${err.message}`);
|
|
20
|
+
}
|
|
21
|
+
const parsed = agentConfigResponse.safeParse(result.body);
|
|
22
|
+
if (result.status !== 200 || !parsed.success)
|
|
23
|
+
throw new Error(`${serverUrl} doesn't look like an aimc server (GET /api/agent/v1/config).`);
|
|
24
|
+
return parsed.data;
|
|
25
|
+
}
|
|
26
|
+
async function discover(fetchFn, issuer) {
|
|
27
|
+
const { status, body } = await getJson(fetchFn, `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`);
|
|
28
|
+
const doc = body;
|
|
29
|
+
if (status !== 200 || !doc?.token_endpoint || !doc.device_authorization_endpoint) {
|
|
30
|
+
throw new Error("The sign-in server doesn't offer device sign-in. Ask the admin to enable it for the host agent client.");
|
|
31
|
+
}
|
|
32
|
+
return doc;
|
|
33
|
+
}
|
|
34
|
+
const form = (fields) => ({
|
|
35
|
+
method: "POST",
|
|
36
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
37
|
+
body: new URLSearchParams(fields).toString(),
|
|
38
|
+
});
|
|
39
|
+
/**
|
|
40
|
+
* The whole device flow. `show` tells the user where to go; `sleep` is injectable for tests.
|
|
41
|
+
* Returns the credentials to store (never printed).
|
|
42
|
+
*/
|
|
43
|
+
export async function deviceLogin(opts) {
|
|
44
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
45
|
+
const config = await fetchServerConfig(opts.fetchFn, opts.serverUrl);
|
|
46
|
+
const endpoints = await discover(opts.fetchFn, config.issuer);
|
|
47
|
+
const start = await getJson(opts.fetchFn, endpoints.device_authorization_endpoint, form({ client_id: config.clientId, scope: config.scope }));
|
|
48
|
+
const device = start.body;
|
|
49
|
+
if (start.status !== 200 || !device?.device_code || !device.user_code || !device.verification_uri) {
|
|
50
|
+
const error = device?.error ?? `HTTP ${start.status}`;
|
|
51
|
+
const hint = error === "invalid_client" || error === "unauthorized_client"
|
|
52
|
+
? ` The host agent client "${config.clientId}" doesn't exist or doesn't allow device sign-in yet: ask the server's admin.`
|
|
53
|
+
: "";
|
|
54
|
+
throw new Error(`The sign-in server refused to start a device sign-in (${error}).${hint}`);
|
|
55
|
+
}
|
|
56
|
+
opts.show({
|
|
57
|
+
verificationUri: device.verification_uri,
|
|
58
|
+
verificationUriComplete: device.verification_uri_complete ?? null,
|
|
59
|
+
userCode: device.user_code,
|
|
60
|
+
expiresInSec: device.expires_in ?? 600,
|
|
61
|
+
});
|
|
62
|
+
let intervalMs = Math.max(1, device.interval ?? 5) * 1000;
|
|
63
|
+
const deadline = Date.now() + (device.expires_in ?? 600) * 1000;
|
|
64
|
+
while (Date.now() < deadline) {
|
|
65
|
+
await sleep(intervalMs);
|
|
66
|
+
const poll = await getJson(opts.fetchFn, endpoints.token_endpoint, form({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: device.device_code, client_id: config.clientId }));
|
|
67
|
+
const body = poll.body;
|
|
68
|
+
if (poll.status === 200 && body?.refresh_token) {
|
|
69
|
+
return { issuer: config.issuer, clientId: config.clientId, refreshToken: body.refresh_token };
|
|
70
|
+
}
|
|
71
|
+
switch (body?.error) {
|
|
72
|
+
case "authorization_pending":
|
|
73
|
+
continue;
|
|
74
|
+
case "slow_down":
|
|
75
|
+
intervalMs += 5000; // the server asks us to poll less often
|
|
76
|
+
continue;
|
|
77
|
+
case "access_denied":
|
|
78
|
+
throw new Error("The sign-in was declined.");
|
|
79
|
+
case "expired_token":
|
|
80
|
+
throw new Error("The code expired before it was confirmed. Run `login` again.");
|
|
81
|
+
default:
|
|
82
|
+
throw new Error(`The sign-in failed (${body?.error ?? `HTTP ${poll.status}`}).`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
throw new Error("The code expired before it was confirmed. Run `login` again.");
|
|
86
|
+
}
|
|
87
|
+
export class NotSignedInError extends Error {
|
|
88
|
+
constructor(message = "Not signed in. Run `login` first.") {
|
|
89
|
+
super(message);
|
|
90
|
+
this.name = "NotSignedInError";
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Hands out access tokens, refreshing them shortly before they expire. The sign-in server may send a new
|
|
95
|
+
* refresh token with each refresh ("rotation"); it is saved at once, so a restart keeps working.
|
|
96
|
+
*/
|
|
97
|
+
export class TokenSource {
|
|
98
|
+
fetchFn;
|
|
99
|
+
files;
|
|
100
|
+
creds = null;
|
|
101
|
+
access = null;
|
|
102
|
+
endpoints = null;
|
|
103
|
+
refreshing = null;
|
|
104
|
+
constructor(fetchFn, files) {
|
|
105
|
+
this.fetchFn = fetchFn;
|
|
106
|
+
this.files = files;
|
|
107
|
+
}
|
|
108
|
+
/** A valid access token (refreshed when less than 30 seconds are left). */
|
|
109
|
+
async get() {
|
|
110
|
+
if (this.access && this.access.expiresAt - Date.now() > 30_000)
|
|
111
|
+
return this.access.token;
|
|
112
|
+
this.refreshing ??= this.refresh().finally(() => {
|
|
113
|
+
this.refreshing = null;
|
|
114
|
+
});
|
|
115
|
+
return this.refreshing;
|
|
116
|
+
}
|
|
117
|
+
/** Forget the current access token (the server refused it): the next get() refreshes. */
|
|
118
|
+
invalidate() {
|
|
119
|
+
this.access = null;
|
|
120
|
+
}
|
|
121
|
+
async refresh() {
|
|
122
|
+
this.creds ??= await this.files.loadCredentials();
|
|
123
|
+
if (!this.creds)
|
|
124
|
+
throw new NotSignedInError();
|
|
125
|
+
this.endpoints ??= await discover(this.fetchFn, this.creds.issuer);
|
|
126
|
+
const { status, body } = await getJson(this.fetchFn, this.endpoints.token_endpoint, form({ grant_type: "refresh_token", refresh_token: this.creds.refreshToken, client_id: this.creds.clientId }));
|
|
127
|
+
const tokens = body;
|
|
128
|
+
if (status !== 200 || !tokens?.access_token) {
|
|
129
|
+
if (tokens?.error === "invalid_grant") {
|
|
130
|
+
throw new NotSignedInError("Your sign-in has ended (logged out, expired or revoked by an admin). Run `login` again.");
|
|
131
|
+
}
|
|
132
|
+
throw new Error(`Couldn't refresh the sign-in (${tokens?.error ?? `HTTP ${status}`}).`);
|
|
133
|
+
}
|
|
134
|
+
if (tokens.refresh_token && tokens.refresh_token !== this.creds.refreshToken) {
|
|
135
|
+
this.creds = { ...this.creds, refreshToken: tokens.refresh_token };
|
|
136
|
+
await this.files.saveCredentials(this.creds);
|
|
137
|
+
}
|
|
138
|
+
this.access = { token: tokens.access_token, expiresAt: Date.now() + (tokens.expires_in ?? 300) * 1000 };
|
|
139
|
+
return tokens.access_token;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Logs out: revokes the refresh token at the sign-in server (so a copy of the file is useless too), then
|
|
144
|
+
* deletes the local file. The file is deleted even if the sign-in server can't be reached.
|
|
145
|
+
*/
|
|
146
|
+
export async function logout(fetchFn, files) {
|
|
147
|
+
const creds = await files.loadCredentials();
|
|
148
|
+
if (!creds)
|
|
149
|
+
return { revoked: false, wasSignedIn: false };
|
|
150
|
+
let revoked = false;
|
|
151
|
+
try {
|
|
152
|
+
const endpoints = await discover(fetchFn, creds.issuer);
|
|
153
|
+
if (endpoints.revocation_endpoint) {
|
|
154
|
+
const res = await fetchFn(endpoints.revocation_endpoint, {
|
|
155
|
+
...form({ token: creds.refreshToken, token_type_hint: "refresh_token", client_id: creds.clientId }),
|
|
156
|
+
signal: AbortSignal.timeout(15_000),
|
|
157
|
+
});
|
|
158
|
+
revoked = res.ok;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
revoked = false;
|
|
163
|
+
}
|
|
164
|
+
await files.deleteCredentials();
|
|
165
|
+
return { revoked, wasSignedIn: true };
|
|
166
|
+
}
|
|
167
|
+
export function readTokenClaims(accessToken) {
|
|
168
|
+
const part = accessToken.split(".")[1];
|
|
169
|
+
if (!part)
|
|
170
|
+
return null;
|
|
171
|
+
try {
|
|
172
|
+
const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
173
|
+
const aud = Array.isArray(claims.aud) ? claims.aud.filter((a) => typeof a === "string") : typeof claims.aud === "string" ? [claims.aud] : [];
|
|
174
|
+
return {
|
|
175
|
+
aud,
|
|
176
|
+
scope: typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [],
|
|
177
|
+
azp: typeof claims.azp === "string" ? claims.azp : null,
|
|
178
|
+
sub: typeof claims.sub === "string" ? claims.sub : null,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Checks the claims the agent API needs. Returns problems in plain words (empty when fine).
|
|
187
|
+
* The server decides for real; this only explains a refusal.
|
|
188
|
+
*/
|
|
189
|
+
export function tokenProblems(claims, hostAudience = "ai-my-card-host-api", apiAudience = "ai-my-card-api") {
|
|
190
|
+
const problems = [];
|
|
191
|
+
if (!claims.aud.includes(hostAudience)) {
|
|
192
|
+
problems.push(claims.scope.includes("host")
|
|
193
|
+
? `aud lacks "${hostAudience}" although "host" is in scope: the sign-in server doesn't add the host API audience for the "host" scope. Ask the server's admin.`
|
|
194
|
+
: `aud lacks "${hostAudience}": the "host" scope isn't granted to the agent's sign-in client, or it doesn't add the host API audience. Ask the server's admin.`);
|
|
195
|
+
}
|
|
196
|
+
if (claims.aud.includes(apiAudience)) {
|
|
197
|
+
problems.push(`aud also contains "${apiAudience}", so the server refuses it (a token may not be valid for both): the agent's sign-in client also receives the inference API audience. Ask the server's admin.`);
|
|
198
|
+
}
|
|
199
|
+
if (!claims.scope.includes("host"))
|
|
200
|
+
problems.push(`scope lacks "host": the sign-in server doesn't put the "host" scope into the token. Ask the server's admin.`);
|
|
201
|
+
return problems;
|
|
202
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { PROTOCOL_VERSION } from "aimc-protocol/agent";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { deviceLogin, fetchServerConfig, logout, NotSignedInError, readTokenClaims, tokenProblems, TokenSource } from "./auth.js";
|
|
5
|
+
import { AgentFiles, agentConfig, checkOllamaUrl, checkServerUrl } from "./config.js";
|
|
6
|
+
import { OllamaClient } from "./ollama.js";
|
|
7
|
+
import { FatalError, Runner } from "./runner.js";
|
|
8
|
+
import { ServerClient, ServerError } from "./server-client.js";
|
|
9
|
+
import { installService, runAsService, uninstallService } from "./service.js";
|
|
10
|
+
import { readGpu } from "./telemetry.js";
|
|
11
|
+
import { AGENT_VERSION, PACKAGE_NAME } from "./version.js";
|
|
12
|
+
// aimc-host: lend your GPU to an aimc server. Run: aimc-host <command> (or npx aimc-host ...).
|
|
13
|
+
/** How you started the agent, for the hints below ("Next: aimc-host register ..."). */
|
|
14
|
+
const RUN = process.env.AIMC_RUN || (process.env.npm_command === "exec" ? `npx ${PACKAGE_NAME}` : PACKAGE_NAME);
|
|
15
|
+
const HELP = `aimc-host ${AGENT_VERSION}: lend your GPU to an aimc server
|
|
16
|
+
|
|
17
|
+
Usage: ${RUN} <command> [options]
|
|
18
|
+
|
|
19
|
+
login [--server] URL sign in (shows a code you confirm in any browser)
|
|
20
|
+
config [options] show or change settings:
|
|
21
|
+
--server URL the server, e.g. https://your-server.example
|
|
22
|
+
--ollama URL your Ollama (default http://127.0.0.1:11434)
|
|
23
|
+
--models a,b the local models you offer (only these are ever run)
|
|
24
|
+
--max-concurrent N jobs at once on this machine (default 1)
|
|
25
|
+
register --name NAME add this machine as a host (an admin approves it)
|
|
26
|
+
start run: take jobs until Ctrl+C
|
|
27
|
+
status show settings, sign-in, Ollama and server
|
|
28
|
+
logout sign out and revoke the sign-in
|
|
29
|
+
version show this agent's version
|
|
30
|
+
|
|
31
|
+
Linux (systemd), asks for sudo:
|
|
32
|
+
install-service run the agent as a service, started at boot
|
|
33
|
+
--copy-settings bring your sign-in and settings to the service
|
|
34
|
+
--no-start install and enable, but don't (re)start it
|
|
35
|
+
--dry-run only show what it would do
|
|
36
|
+
service <command> run a command as the service, e.g. service status
|
|
37
|
+
uninstall-service remove the service (--purge: its sign-in and settings too)
|
|
38
|
+
|
|
39
|
+
Settings and the sign-in live in ${new AgentFiles().dir}
|
|
40
|
+
The sign-in file (credentials.json) is a secret: anyone with it can act as this host.`;
|
|
41
|
+
const log = (message) => console.log(`${new Date().toISOString().slice(11, 19)} ${message}`);
|
|
42
|
+
function requireServer(config) {
|
|
43
|
+
if (!config.serverUrl)
|
|
44
|
+
throw new Error(`No server set. Run: ${RUN} login --server https://your-server.example`);
|
|
45
|
+
return config.serverUrl;
|
|
46
|
+
}
|
|
47
|
+
async function main(argv) {
|
|
48
|
+
const [command, ...rest] = argv;
|
|
49
|
+
// Everything after `service` belongs to the command run as the service.
|
|
50
|
+
if (command === "service") {
|
|
51
|
+
if (rest.length === 0)
|
|
52
|
+
throw new Error(`Which command? E.g. ${RUN} service status`);
|
|
53
|
+
return runAsService(rest);
|
|
54
|
+
}
|
|
55
|
+
const { values, positionals } = parseArgs({
|
|
56
|
+
args: rest,
|
|
57
|
+
allowPositionals: true,
|
|
58
|
+
options: {
|
|
59
|
+
server: { type: "string" },
|
|
60
|
+
ollama: { type: "string" },
|
|
61
|
+
models: { type: "string" },
|
|
62
|
+
"max-concurrent": { type: "string" },
|
|
63
|
+
name: { type: "string" },
|
|
64
|
+
force: { type: "boolean" },
|
|
65
|
+
"copy-settings": { type: "boolean" },
|
|
66
|
+
"no-start": { type: "boolean" },
|
|
67
|
+
"dry-run": { type: "boolean" },
|
|
68
|
+
purge: { type: "boolean" },
|
|
69
|
+
"settings-from": { type: "string" },
|
|
70
|
+
},
|
|
71
|
+
strict: true,
|
|
72
|
+
});
|
|
73
|
+
const serviceOptions = {
|
|
74
|
+
dryRun: values["dry-run"] ?? false,
|
|
75
|
+
copySettings: values["copy-settings"] ?? false,
|
|
76
|
+
noStart: values["no-start"] ?? false,
|
|
77
|
+
purge: values.purge ?? false,
|
|
78
|
+
settingsFrom: values["settings-from"],
|
|
79
|
+
};
|
|
80
|
+
// Only login takes a plain argument (the server). Anything else stray is a typo.
|
|
81
|
+
if (positionals.length > (command === "login" ? 1 : 0)) {
|
|
82
|
+
throw new Error(`Unexpected argument '${positionals.at(-1)}'. Options start with --, e.g. --models a,b. See: ${RUN} help`);
|
|
83
|
+
}
|
|
84
|
+
const files = new AgentFiles();
|
|
85
|
+
const config = await files.loadConfig();
|
|
86
|
+
switch (command) {
|
|
87
|
+
case "login": {
|
|
88
|
+
const serverArg = values.server ?? positionals[0];
|
|
89
|
+
if (serverArg)
|
|
90
|
+
config.serverUrl = checkServerUrl(serverArg);
|
|
91
|
+
const server = requireServer(config);
|
|
92
|
+
await files.saveConfig(config);
|
|
93
|
+
const creds = await deviceLogin({
|
|
94
|
+
fetchFn: fetch,
|
|
95
|
+
serverUrl: server,
|
|
96
|
+
show: (p) => {
|
|
97
|
+
console.log("\nTo sign in, open this link on any device and confirm the code:\n");
|
|
98
|
+
console.log(` ${p.verificationUriComplete ?? p.verificationUri}`);
|
|
99
|
+
console.log(` code: ${p.userCode}\n`);
|
|
100
|
+
console.log(`Waiting for you to confirm (the code is valid for ${Math.round(p.expiresInSec / 60)} minutes)...`);
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
await files.saveCredentials(creds);
|
|
104
|
+
console.log(`Signed in. The sign-in is stored in ${files.credentialsPath()} (keep it secret).`);
|
|
105
|
+
if (!config.hostId)
|
|
106
|
+
console.log(`Next: ${RUN} register --name <a name for this machine>`);
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
case "config": {
|
|
110
|
+
let changed = false;
|
|
111
|
+
if (values.server) {
|
|
112
|
+
config.serverUrl = checkServerUrl(values.server);
|
|
113
|
+
changed = true;
|
|
114
|
+
}
|
|
115
|
+
if (values.ollama) {
|
|
116
|
+
config.ollamaUrl = checkOllamaUrl(values.ollama);
|
|
117
|
+
changed = true;
|
|
118
|
+
}
|
|
119
|
+
if (values.models !== undefined) {
|
|
120
|
+
config.models = [...new Set(values.models.split(",").map((m) => m.trim()).filter(Boolean))];
|
|
121
|
+
changed = true;
|
|
122
|
+
}
|
|
123
|
+
if (values["max-concurrent"] !== undefined) {
|
|
124
|
+
const n = Number(values["max-concurrent"]);
|
|
125
|
+
if (!Number.isInteger(n) || n < 1 || n > 32)
|
|
126
|
+
throw new Error("--max-concurrent must be a whole number from 1 to 32.");
|
|
127
|
+
config.maxConcurrent = n;
|
|
128
|
+
changed = true;
|
|
129
|
+
}
|
|
130
|
+
if (changed) {
|
|
131
|
+
const parsed = agentConfig.safeParse(config);
|
|
132
|
+
if (!parsed.success)
|
|
133
|
+
throw new Error("Model names look like gemma3:12b (letters, digits, . _ : / -).");
|
|
134
|
+
await files.saveConfig(parsed.data);
|
|
135
|
+
console.log("Saved. If the agent is running, restart it to apply.");
|
|
136
|
+
}
|
|
137
|
+
console.log(JSON.stringify(config, null, 2));
|
|
138
|
+
if (values.models !== undefined) {
|
|
139
|
+
const installed = await new OllamaClient(fetch, config.ollamaUrl).installed().catch(() => null);
|
|
140
|
+
const missing = installed ? config.models.filter((m) => !installed.includes(m)) : [];
|
|
141
|
+
if (missing.length)
|
|
142
|
+
console.log(`Warning: not installed in Ollama: ${missing.join(", ")} (ollama pull <model>).`);
|
|
143
|
+
}
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
case "register": {
|
|
147
|
+
const server = requireServer(config);
|
|
148
|
+
if (!values.name)
|
|
149
|
+
throw new Error("Give the host a name: register --name my-desktop");
|
|
150
|
+
if (config.hostId && !values.force) {
|
|
151
|
+
throw new Error(`This machine is already registered as host ${config.hostId}. Use --force to register a new host instead.`);
|
|
152
|
+
}
|
|
153
|
+
const client = new ServerClient(fetch, server, new TokenSource(fetch, files));
|
|
154
|
+
const result = await client.register(values.name);
|
|
155
|
+
config.hostId = result.hostId;
|
|
156
|
+
await files.saveConfig(config);
|
|
157
|
+
console.log(`Registered as host ${result.hostId}, waiting for an admin's approval.`);
|
|
158
|
+
if (config.models.length === 0)
|
|
159
|
+
console.log(`Next: ${RUN} config --models <the models you offer>, then start.`);
|
|
160
|
+
else
|
|
161
|
+
console.log(`Next: ${RUN} start (it waits until the host is approved).`);
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
case "start": {
|
|
165
|
+
const server = requireServer(config);
|
|
166
|
+
if (!config.hostId)
|
|
167
|
+
throw new Error(`Not registered yet. Run: ${RUN} register --name <name>`);
|
|
168
|
+
if (config.models.length === 0)
|
|
169
|
+
throw new Error(`No models offered. Run: ${RUN} config --models gemma3:12b`);
|
|
170
|
+
const ollama = new OllamaClient(fetch, config.ollamaUrl);
|
|
171
|
+
const installed = await ollama.installed().catch((err) => {
|
|
172
|
+
throw new Error(`${err.message} Is Ollama running?`);
|
|
173
|
+
});
|
|
174
|
+
const missing = config.models.filter((m) => !installed.includes(m));
|
|
175
|
+
if (missing.length)
|
|
176
|
+
log(`Warning: offered but not installed in Ollama: ${missing.join(", ")}. Jobs for them will fail.`);
|
|
177
|
+
const stop = new AbortController();
|
|
178
|
+
const onSignal = () => {
|
|
179
|
+
log("Stopping...");
|
|
180
|
+
stop.abort();
|
|
181
|
+
};
|
|
182
|
+
process.once("SIGINT", onSignal);
|
|
183
|
+
process.once("SIGTERM", onSignal);
|
|
184
|
+
log(`Starting host ${config.hostId} against ${server}.`);
|
|
185
|
+
await new Runner({
|
|
186
|
+
server: new ServerClient(fetch, server, new TokenSource(fetch, files)),
|
|
187
|
+
ollama,
|
|
188
|
+
hostId: config.hostId,
|
|
189
|
+
models: config.models,
|
|
190
|
+
maxConcurrent: config.maxConcurrent,
|
|
191
|
+
agentVersion: AGENT_VERSION,
|
|
192
|
+
readGpu,
|
|
193
|
+
log,
|
|
194
|
+
signal: stop.signal,
|
|
195
|
+
}).run();
|
|
196
|
+
log("Stopped.");
|
|
197
|
+
return 0;
|
|
198
|
+
}
|
|
199
|
+
case "status": {
|
|
200
|
+
console.log(`Agent: ${PACKAGE_NAME} ${AGENT_VERSION}`);
|
|
201
|
+
console.log(`Settings: ${files.dir}`);
|
|
202
|
+
console.log(`Server: ${config.serverUrl ?? "not set"}`);
|
|
203
|
+
console.log(`Host id: ${config.hostId ?? "not registered"}`);
|
|
204
|
+
console.log(`Offering: ${config.models.join(", ") || "nothing"} (up to ${config.maxConcurrent} at once)`);
|
|
205
|
+
const ollama = new OllamaClient(fetch, config.ollamaUrl);
|
|
206
|
+
try {
|
|
207
|
+
const [version, installed] = await Promise.all([ollama.version(), ollama.installed()]);
|
|
208
|
+
const missing = config.models.filter((m) => !installed.includes(m));
|
|
209
|
+
console.log(`Ollama: ${config.ollamaUrl}, version ${version}${missing.length ? `; NOT installed: ${missing.join(", ")}` : ""}`);
|
|
210
|
+
}
|
|
211
|
+
catch (err) {
|
|
212
|
+
console.log(`Ollama: ${err.message}`);
|
|
213
|
+
}
|
|
214
|
+
const gpu = await readGpu();
|
|
215
|
+
console.log(`GPU: ${gpu ? `${gpu.name}, ${(gpu.vramTotalMb / 1024).toFixed(1)} GB` : "no NVIDIA GPU found (nvidia-smi)"}`);
|
|
216
|
+
if (config.serverUrl) {
|
|
217
|
+
try {
|
|
218
|
+
await fetchServerConfig(fetch, config.serverUrl);
|
|
219
|
+
console.log("Server: reachable");
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
console.log(`Server: ${err.message}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (!(await files.loadCredentials()))
|
|
226
|
+
console.log(`Sign-in: not signed in (${RUN} login --server <url>)`);
|
|
227
|
+
else {
|
|
228
|
+
try {
|
|
229
|
+
const claims = readTokenClaims(await new TokenSource(fetch, files).get());
|
|
230
|
+
console.log("Sign-in: signed in");
|
|
231
|
+
if (claims) {
|
|
232
|
+
// The token's labels, to explain a refusal by the server (never the token itself).
|
|
233
|
+
console.log(`Token: aud ${claims.aud.join(", ") || "-"}; scope ${claims.scope.join(" ") || "-"}; client ${claims.azp ?? "-"}`);
|
|
234
|
+
for (const problem of tokenProblems(claims))
|
|
235
|
+
console.log(`Problem: ${problem}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
console.log(`Sign-in: ${err.message}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return 0;
|
|
243
|
+
}
|
|
244
|
+
case "logout": {
|
|
245
|
+
const result = await logout(fetch, files);
|
|
246
|
+
if (!result.wasSignedIn)
|
|
247
|
+
console.log("Not signed in.");
|
|
248
|
+
else if (result.revoked)
|
|
249
|
+
console.log("Signed out: the sign-in was revoked and the local file deleted.");
|
|
250
|
+
else
|
|
251
|
+
console.log("Signed out locally. The sign-in server couldn't be reached to revoke it; it expires unused after 30 days.");
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
case "install-service":
|
|
255
|
+
return installService(serviceOptions);
|
|
256
|
+
case "uninstall-service":
|
|
257
|
+
return uninstallService(serviceOptions);
|
|
258
|
+
case "version":
|
|
259
|
+
case "--version":
|
|
260
|
+
case "-v":
|
|
261
|
+
console.log(`${PACKAGE_NAME} ${AGENT_VERSION} (protocol ${PROTOCOL_VERSION}, Node ${process.version})`);
|
|
262
|
+
return 0;
|
|
263
|
+
case undefined:
|
|
264
|
+
case "help":
|
|
265
|
+
case "--help":
|
|
266
|
+
case "-h":
|
|
267
|
+
console.log(HELP);
|
|
268
|
+
return 0;
|
|
269
|
+
default:
|
|
270
|
+
console.error(`Unknown command: ${command}\n\n${HELP}`);
|
|
271
|
+
return 2;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
main(process.argv.slice(2)).then((code) => {
|
|
275
|
+
process.exitCode = code;
|
|
276
|
+
}, (err) => {
|
|
277
|
+
if (err instanceof ServerError)
|
|
278
|
+
console.error(`Error: ${err.message} (${err.code})`);
|
|
279
|
+
else if (err instanceof NotSignedInError)
|
|
280
|
+
console.error(err.message);
|
|
281
|
+
else
|
|
282
|
+
console.error(`Error: ${err.message}`);
|
|
283
|
+
// 3 = retrying won't help (retired, rejected, not signed in...): systemd doesn't restart it.
|
|
284
|
+
process.exitCode = err instanceof FatalError || err instanceof NotSignedInError ? 3 : 1;
|
|
285
|
+
});
|