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/dist/config.js ADDED
@@ -0,0 +1,123 @@
1
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { z } from "zod";
5
+ // The agent keeps two files in its own folder:
6
+ // config.json server URL, Ollama URL, offered models, jobs at once, the host id
7
+ // credentials.json the refresh token from `login`: a SECRET, like a password
8
+ // Windows: %APPDATA%\ai-my-card-host. Linux: ~/.config/ai-my-card-host, readable only by you
9
+ // (folder 700, files 600).
10
+ export function configDir(env = process.env, platform = process.platform) {
11
+ if (platform === "win32")
12
+ return join(env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "ai-my-card-host");
13
+ return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "ai-my-card-host");
14
+ }
15
+ export const DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434";
16
+ const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
17
+ export const agentConfig = z.object({
18
+ serverUrl: z.string().optional(),
19
+ ollamaUrl: z.string().default(DEFAULT_OLLAMA_URL),
20
+ /** Local Ollama models you offer. Only these are ever run. */
21
+ models: z.array(z.string().regex(MODEL_NAME)).default([]),
22
+ /** Jobs at once on this machine. The server may give fewer (its own limit for your host). */
23
+ maxConcurrent: z.number().int().min(1).max(32).default(1),
24
+ hostId: z.uuid().optional(),
25
+ });
26
+ export const credentials = z.object({
27
+ issuer: z.string(),
28
+ clientId: z.string(),
29
+ refreshToken: z.string(),
30
+ });
31
+ /**
32
+ * The server must be HTTPS. Plain http only for this machine (local development), so the
33
+ * tokens and your users' prompts never cross a network unencrypted.
34
+ */
35
+ export function checkServerUrl(raw) {
36
+ let url;
37
+ try {
38
+ url = new URL(raw.trim());
39
+ }
40
+ catch {
41
+ throw new Error(`Not a URL: ${raw}`);
42
+ }
43
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
44
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
45
+ throw new Error("The server URL must start with https:// (plain http only for localhost).");
46
+ }
47
+ if (url.username || url.password || url.search || url.hash)
48
+ throw new Error("The server URL must be a plain address, like https://your-server.example");
49
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
50
+ }
51
+ /**
52
+ * Where your Ollama listens: this machine by default, or another machine on your network. It is
53
+ * only ever called by this agent; keep it bound to localhost or your LAN, never the internet.
54
+ */
55
+ export function checkOllamaUrl(raw) {
56
+ let url;
57
+ try {
58
+ url = new URL(raw.trim());
59
+ }
60
+ catch {
61
+ throw new Error(`Not a URL: ${raw}`);
62
+ }
63
+ if (url.protocol !== "http:" && url.protocol !== "https:")
64
+ throw new Error("The Ollama URL must start with http://");
65
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
66
+ }
67
+ export class AgentFiles {
68
+ dir;
69
+ platform;
70
+ constructor(dir = configDir(), platform = process.platform) {
71
+ this.dir = dir;
72
+ this.platform = platform;
73
+ }
74
+ path(name) {
75
+ return join(this.dir, name);
76
+ }
77
+ async readJson(name) {
78
+ try {
79
+ return JSON.parse(await readFile(this.path(name), "utf8"));
80
+ }
81
+ catch (err) {
82
+ if (err.code === "ENOENT")
83
+ return null;
84
+ throw new Error(`Couldn't read ${this.path(name)}: ${err.message}`);
85
+ }
86
+ }
87
+ async writeJson(name, value) {
88
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
89
+ const file = this.path(name);
90
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
91
+ if (this.platform !== "win32") {
92
+ // mode only applies when the file is created; make sure an older file is private too.
93
+ await chmod(this.dir, 0o700);
94
+ await chmod(file, 0o600);
95
+ }
96
+ }
97
+ async loadConfig() {
98
+ const raw = await this.readJson("config.json");
99
+ const parsed = agentConfig.safeParse(raw ?? {});
100
+ if (!parsed.success)
101
+ throw new Error(`${this.path("config.json")} is not valid. Fix or delete it.`);
102
+ return parsed.data;
103
+ }
104
+ saveConfig(config) {
105
+ return this.writeJson("config.json", config);
106
+ }
107
+ async loadCredentials() {
108
+ const raw = await this.readJson("credentials.json");
109
+ if (raw === null)
110
+ return null;
111
+ const parsed = credentials.safeParse(raw);
112
+ return parsed.success ? parsed.data : null;
113
+ }
114
+ saveCredentials(value) {
115
+ return this.writeJson("credentials.json", value);
116
+ }
117
+ async deleteCredentials() {
118
+ await rm(this.path("credentials.json"), { force: true });
119
+ }
120
+ credentialsPath() {
121
+ return this.path("credentials.json");
122
+ }
123
+ }
package/dist/ollama.js ADDED
@@ -0,0 +1,145 @@
1
+ export class OllamaError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.name = "OllamaError";
6
+ this.code = code;
7
+ }
8
+ }
9
+ /** Ollama reports durations in nanoseconds; the protocol uses milliseconds. */
10
+ function nsToMs(ns) {
11
+ return typeof ns === "number" && Number.isFinite(ns) && ns >= 0 ? Math.round(ns / 1e6) : undefined;
12
+ }
13
+ export class OllamaClient {
14
+ fetchFn;
15
+ baseUrl;
16
+ constructor(fetchFn, baseUrl) {
17
+ this.fetchFn = fetchFn;
18
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
19
+ }
20
+ async call(path, init = {}, signal) {
21
+ let res;
22
+ try {
23
+ res = await this.fetchFn(`${this.baseUrl}${path}`, { ...init, signal: signal ?? AbortSignal.timeout(5000) });
24
+ }
25
+ catch (err) {
26
+ if (signal?.aborted)
27
+ throw err;
28
+ throw new OllamaError("ollama_unreachable", `Ollama at ${this.baseUrl} is not reachable (${err.message}).`);
29
+ }
30
+ if (!res.ok) {
31
+ let reason = "";
32
+ try {
33
+ reason = (await res.json()).error ?? "";
34
+ }
35
+ catch {
36
+ // no JSON body
37
+ }
38
+ // Ollama's refusals of the request itself: another host would refuse it too.
39
+ const code = res.status === 400 && /does not support thinking/i.test(reason)
40
+ ? "thinking_not_supported"
41
+ : res.status === 400 && /does not support (multimodal|images?|vision)/i.test(reason)
42
+ ? "images_not_supported"
43
+ : "ollama_error";
44
+ throw new OllamaError(code, `Ollama ${path} answered HTTP ${res.status}${reason ? `: ${reason.slice(0, 200)}` : ""}`);
45
+ }
46
+ return res;
47
+ }
48
+ async version() {
49
+ const body = (await (await this.call("/api/version")).json());
50
+ return body.version ?? "unknown";
51
+ }
52
+ /** The models installed in Ollama. */
53
+ async installed() {
54
+ const body = (await (await this.call("/api/tags")).json());
55
+ return (body.models ?? []).map((m) => m.name);
56
+ }
57
+ /** The models loaded in GPU memory right now. */
58
+ async loaded() {
59
+ const body = (await (await this.call("/api/ps")).json());
60
+ return (body.models ?? []).map((m) => ({
61
+ name: m.name,
62
+ vramMb: Math.round((m.size_vram ?? 0) / 1024 / 1024),
63
+ ...(m.expires_at ? { expiresAt: m.expires_at.slice(0, 40) } : {}),
64
+ }));
65
+ }
66
+ /**
67
+ * Runs a job and yields its events: deltas, then one "done". Throws OllamaError on failure.
68
+ * Aborting `signal` stops the generation (closing the HTTP response makes Ollama stop).
69
+ */
70
+ async *chat(job, signal) {
71
+ const o = job.options;
72
+ const res = await this.call("/api/chat", {
73
+ method: "POST",
74
+ headers: { "content-type": "application/json" },
75
+ body: JSON.stringify({
76
+ model: job.model,
77
+ messages: job.messages.map((m) => (m.images?.length ? { role: m.role, content: m.content, images: m.images } : { role: m.role, content: m.content })),
78
+ stream: true,
79
+ ...(o.format !== undefined ? { format: o.format } : {}),
80
+ ...(o.think !== undefined ? { think: o.think } : {}),
81
+ options: {
82
+ num_predict: o.numPredict,
83
+ ...(o.numCtx !== undefined ? { num_ctx: o.numCtx } : {}),
84
+ ...(o.temperature !== undefined ? { temperature: o.temperature } : {}),
85
+ ...(o.topP !== undefined ? { top_p: o.topP } : {}),
86
+ ...(o.stop?.length ? { stop: o.stop } : {}),
87
+ ...(o.seed !== undefined ? { seed: o.seed } : {}),
88
+ },
89
+ }),
90
+ }, signal);
91
+ if (!res.body)
92
+ throw new OllamaError("ollama_error", "Ollama sent an empty response.");
93
+ const reader = res.body.getReader();
94
+ const decoder = new TextDecoder();
95
+ let buffer = "";
96
+ try {
97
+ for (;;) {
98
+ const { done, value } = await reader.read();
99
+ // At the end, a last line without a newline still counts.
100
+ if (done)
101
+ buffer += `${decoder.decode()}\n`;
102
+ else
103
+ buffer += decoder.decode(value, { stream: true });
104
+ let newline;
105
+ while ((newline = buffer.indexOf("\n")) >= 0) {
106
+ const line = buffer.slice(0, newline).trim();
107
+ buffer = buffer.slice(newline + 1);
108
+ if (!line)
109
+ continue;
110
+ let data;
111
+ try {
112
+ data = JSON.parse(line);
113
+ }
114
+ catch {
115
+ throw new OllamaError("ollama_error", "Ollama sent a line that is not JSON.");
116
+ }
117
+ if (data.error)
118
+ throw new OllamaError("ollama_error", `Ollama error: ${data.error.slice(0, 200)}`);
119
+ if (data.message?.content)
120
+ yield { type: "delta", text: data.message.content };
121
+ if (data.done) {
122
+ const hasUsage = typeof data.prompt_eval_count === "number" || typeof data.eval_count === "number";
123
+ yield {
124
+ type: "done",
125
+ finishReason: data.done_reason === "length" ? "length" : "stop",
126
+ ...(hasUsage ? { usage: { promptTokens: data.prompt_eval_count ?? 0, completionTokens: data.eval_count ?? 0 } } : {}),
127
+ timings: {
128
+ ...(nsToMs(data.load_duration) !== undefined ? { loadMs: nsToMs(data.load_duration) } : {}),
129
+ ...(nsToMs(data.prompt_eval_duration) !== undefined ? { promptEvalMs: nsToMs(data.prompt_eval_duration) } : {}),
130
+ ...(nsToMs(data.eval_duration) !== undefined ? { evalMs: nsToMs(data.eval_duration) } : {}),
131
+ },
132
+ };
133
+ return;
134
+ }
135
+ }
136
+ if (done)
137
+ break;
138
+ }
139
+ throw new OllamaError("ollama_error", "Ollama closed the stream before it was done.");
140
+ }
141
+ finally {
142
+ await reader.cancel().catch(() => { });
143
+ }
144
+ }
145
+ }
package/dist/runner.js ADDED
@@ -0,0 +1,293 @@
1
+ import { parseStreamEvent, PROTOCOL_VERSION } from "aimc-protocol/agent";
2
+ import { readSseData } from "aimc-protocol/sse";
3
+ import { NotSignedInError } from "./auth.js";
4
+ import { OllamaError } from "./ollama.js";
5
+ import { ServerError } from "./server-client.js";
6
+ import { versionAdvice } from "./version.js";
7
+ // `start`: what the agent does all day.
8
+ //
9
+ // hello -> open the job stream -> run jobs as they come -> the stream closes (every ~5 min,
10
+ // when the access token expires) -> hello again -> open the stream again ...
11
+ //
12
+ // Each job runs on the local Ollama. Its events go back to the server in small batches
13
+ // (every ~200 ms), numbered, so a retried batch is never counted twice. The server can cancel a
14
+ // job on the stream or in its answer to a batch. A heartbeat with telemetry goes out every 15 s.
15
+ //
16
+ // Never logged: prompts, answers, images, tokens. Logged: job ids, models, token counts, times.
17
+ /** Errors after which retrying makes no sense: the agent stops and says why. */
18
+ const FATAL = new Set([
19
+ "host_not_found",
20
+ "host_rejected",
21
+ "host_retired",
22
+ "account_not_found",
23
+ "account_not_approved",
24
+ "unsupported_protocol",
25
+ "insufficient_scope",
26
+ "agent_outdated",
27
+ ]);
28
+ /** The agent should stop and not be restarted: the host was retired, the account suspended... */
29
+ export class FatalError extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = "FatalError";
33
+ }
34
+ }
35
+ const sleep = (ms, signal) => new Promise((resolve) => {
36
+ if (signal.aborted)
37
+ return resolve();
38
+ const t = setTimeout(resolve, ms);
39
+ signal.addEventListener("abort", () => {
40
+ clearTimeout(t);
41
+ resolve();
42
+ }, { once: true });
43
+ });
44
+ export class Runner {
45
+ o;
46
+ jobs = new Map();
47
+ limit;
48
+ heartbeat = null;
49
+ lastNotice = "";
50
+ lastUpdateNotice = "";
51
+ constructor(options) {
52
+ this.o = options;
53
+ this.limit = options.maxConcurrent;
54
+ }
55
+ notice(message) {
56
+ // Don't repeat "waiting for approval" every minute.
57
+ if (message !== this.lastNotice)
58
+ this.o.log(message);
59
+ this.lastNotice = message;
60
+ }
61
+ /** Runs until `signal` aborts (Ctrl+C) or a fatal error (thrown, with a message for the owner). */
62
+ async run() {
63
+ const { signal } = this.o;
64
+ let backoff = 1000;
65
+ try {
66
+ while (!signal.aborted) {
67
+ try {
68
+ const hello = await this.hello();
69
+ const advice = versionAdvice(this.o.agentVersion, hello);
70
+ if (advice?.kind === "too_old")
71
+ throw new FatalError(advice.message);
72
+ if (advice && advice.message !== this.lastUpdateNotice) {
73
+ // Once per new version: hello repeats every few minutes.
74
+ this.o.log(advice.message);
75
+ this.lastUpdateNotice = advice.message;
76
+ }
77
+ this.limit = hello.maxConcurrent;
78
+ this.startHeartbeat(hello.heartbeatIntervalMs);
79
+ if (hello.status === "pending_approval") {
80
+ this.notice("Registered and waiting for an admin to approve this host. Checking again every minute.");
81
+ await sleep(this.o.idleRetryMs ?? 60_000, signal);
82
+ continue;
83
+ }
84
+ if (hello.status === "paused") {
85
+ this.notice("This host is paused. Resume it to get jobs again. Checking every minute.");
86
+ await sleep(this.o.idleRetryMs ?? 60_000, signal);
87
+ continue;
88
+ }
89
+ await this.stream();
90
+ backoff = 1000;
91
+ await sleep(500, signal); // the server closed the stream (token expiry, deploy): reconnect
92
+ }
93
+ catch (err) {
94
+ if (signal.aborted)
95
+ break;
96
+ if (err instanceof NotSignedInError || err instanceof FatalError)
97
+ throw err;
98
+ if (err instanceof ServerError) {
99
+ if (FATAL.has(err.code))
100
+ throw new FatalError(err.message);
101
+ if (err.code === "host_pending" || err.code === "host_paused") {
102
+ this.notice(err.message);
103
+ await sleep(this.o.idleRetryMs ?? 60_000, signal);
104
+ continue;
105
+ }
106
+ if (err.code === "hello_required")
107
+ continue;
108
+ }
109
+ this.o.log(`Connection problem: ${err.message}. Retrying in ${Math.round(backoff / 1000)} s.`);
110
+ await sleep(backoff, signal);
111
+ backoff = Math.min(backoff * 2, this.o.maxBackoffMs ?? 60_000);
112
+ }
113
+ }
114
+ }
115
+ finally {
116
+ if (this.heartbeat)
117
+ clearInterval(this.heartbeat);
118
+ this.heartbeat = null;
119
+ for (const job of this.jobs.values()) {
120
+ job.reason = "cancelled";
121
+ job.abort.abort();
122
+ }
123
+ }
124
+ }
125
+ async hello() {
126
+ const [gpu, ollamaVersion] = await Promise.all([this.o.readGpu(), this.o.ollama.version().catch(() => undefined)]);
127
+ return this.o.server.hello(this.o.hostId, {
128
+ protocolVersion: PROTOCOL_VERSION,
129
+ agentVersion: this.o.agentVersion,
130
+ offeredModels: this.o.models,
131
+ maxConcurrent: this.o.maxConcurrent,
132
+ hardware: gpu ? { gpuName: gpu.name, vramMb: gpu.vramTotalMb } : {},
133
+ ...(ollamaVersion ? { ollamaVersion } : {}),
134
+ });
135
+ }
136
+ startHeartbeat(intervalMs) {
137
+ if (this.heartbeat)
138
+ return;
139
+ this.heartbeat = setInterval(() => {
140
+ void this.sendHeartbeat();
141
+ }, intervalMs);
142
+ }
143
+ async sendHeartbeat() {
144
+ try {
145
+ const [gpu, loaded, ollamaVersion] = await Promise.all([
146
+ this.o.readGpu(),
147
+ this.o.ollama.loaded().catch(() => []),
148
+ this.o.ollama.version().catch(() => undefined),
149
+ ]);
150
+ await this.o.server.heartbeat(this.o.hostId, {
151
+ ...(gpu ? { gpu } : {}),
152
+ loadedModels: loaded,
153
+ ...(ollamaVersion ? { ollamaVersion } : {}),
154
+ });
155
+ }
156
+ catch {
157
+ // A missed heartbeat is fine; the stream loop notices real connection problems.
158
+ }
159
+ }
160
+ async stream() {
161
+ const control = new AbortController();
162
+ const stop = () => control.abort();
163
+ this.o.signal.addEventListener("abort", stop, { once: true });
164
+ try {
165
+ const body = await this.o.server.openStream(this.o.hostId, control.signal);
166
+ this.lastNotice = "";
167
+ this.o.log(`Connected. Offering ${this.o.models.join(", ")}; up to ${this.limit} job(s) at once.`);
168
+ for await (const data of readSseData(body)) {
169
+ const event = parseStreamEvent(data);
170
+ if (!event)
171
+ continue; // unknown or broken: ignore
172
+ if (event.type === "job")
173
+ this.startJob(event);
174
+ else if (event.type === "cancel")
175
+ this.cancel(event.jobId, "cancelled");
176
+ else if (event.type === "config")
177
+ this.limit = Math.min(event.maxConcurrent, this.o.maxConcurrent);
178
+ }
179
+ }
180
+ catch (err) {
181
+ if (!control.signal.aborted)
182
+ throw err;
183
+ }
184
+ finally {
185
+ this.o.signal.removeEventListener("abort", stop);
186
+ }
187
+ }
188
+ cancel(jobId, reason) {
189
+ const job = this.jobs.get(jobId);
190
+ if (!job)
191
+ return;
192
+ job.reason ??= reason;
193
+ job.abort.abort();
194
+ }
195
+ startJob(job) {
196
+ const refuse = (code, retryable) => this.o.server.jobEvents(this.o.hostId, job.jobId, 0, [{ type: "error", code, retryable }]).catch(() => false);
197
+ if (!this.o.models.includes(job.model)) {
198
+ this.o.log(`Refused job ${job.jobId}: ${job.model} is not on your offered list.`);
199
+ void refuse("model_not_offered", false);
200
+ return;
201
+ }
202
+ if (this.jobs.size >= this.limit) {
203
+ void refuse("busy", true);
204
+ return;
205
+ }
206
+ const entry = { abort: new AbortController(), reason: null };
207
+ this.jobs.set(job.jobId, entry);
208
+ void this.runJob(job, entry).finally(() => this.jobs.delete(job.jobId));
209
+ }
210
+ async runJob(job, entry) {
211
+ const started = Date.now();
212
+ const deadline = setTimeout(() => this.cancel(job.jobId, "deadline"), job.deadlineMs);
213
+ let seq = 0;
214
+ let pending = [];
215
+ let chain = Promise.resolve();
216
+ let serverGone = false;
217
+ // Sends what is pending, one batch at a time, in order. Merges consecutive deltas.
218
+ const flush = () => {
219
+ chain = chain.then(async () => {
220
+ if (pending.length === 0 || serverGone)
221
+ return;
222
+ const batch = [];
223
+ for (const e of pending) {
224
+ const last = batch.at(-1);
225
+ if (e.type === "delta" && last?.type === "delta" && last.text.length + e.text.length <= 50_000)
226
+ last.text += e.text;
227
+ else
228
+ batch.push(e.type === "delta" ? { ...e } : e);
229
+ }
230
+ pending = [];
231
+ const mySeq = seq++;
232
+ for (let attempt = 0;; attempt++) {
233
+ try {
234
+ if (await this.o.server.jobEvents(this.o.hostId, job.jobId, mySeq, batch)) {
235
+ entry.reason ??= "cancelled";
236
+ entry.abort.abort();
237
+ }
238
+ return;
239
+ }
240
+ catch (err) {
241
+ // The server refused the batch (job gone, host paused...): stop. Network: retry the SAME seq.
242
+ if (err instanceof ServerError || attempt >= 3) {
243
+ serverGone = true;
244
+ entry.reason ??= "cancelled";
245
+ entry.abort.abort();
246
+ return;
247
+ }
248
+ await sleep(500 * (attempt + 1), this.o.signal);
249
+ }
250
+ }
251
+ });
252
+ return chain;
253
+ };
254
+ const ticker = setInterval(() => void flush(), this.o.batchMs ?? 200);
255
+ let completionTokens;
256
+ let outcome = "done";
257
+ try {
258
+ for await (const event of this.o.ollama.chat(job, entry.abort.signal)) {
259
+ pending.push(event);
260
+ if (event.type === "done")
261
+ completionTokens = event.usage?.completionTokens;
262
+ }
263
+ }
264
+ catch (err) {
265
+ if (entry.abort.signal.aborted) {
266
+ outcome = entry.reason ?? "cancelled";
267
+ if (entry.reason === "deadline")
268
+ pending.push({ type: "error", code: "deadline_exceeded", retryable: false });
269
+ else
270
+ pending = []; // cancelled: the server isn't waiting for anything more
271
+ }
272
+ else if (err instanceof OllamaError) {
273
+ outcome = err.code;
274
+ pending.push({ type: "error", code: err.code, retryable: err.code === "ollama_unreachable" });
275
+ }
276
+ else {
277
+ outcome = "internal";
278
+ pending.push({ type: "error", code: "internal", retryable: true });
279
+ }
280
+ }
281
+ finally {
282
+ clearInterval(ticker);
283
+ clearTimeout(deadline);
284
+ await flush();
285
+ }
286
+ const seconds = ((Date.now() - started) / 1000).toFixed(1);
287
+ this.o.log(`Job ${job.jobId} ${job.model}: ${outcome}${completionTokens !== undefined ? `, ${completionTokens} tokens` : ""}, ${seconds} s`);
288
+ }
289
+ /** Jobs running now (for tests). */
290
+ running() {
291
+ return this.jobs.size;
292
+ }
293
+ }
@@ -0,0 +1,76 @@
1
+ import { agentApiError, helloResponse, jobEventsResponse, registerHostResponse, } from "aimc-protocol/agent";
2
+ // Calls to the server's agent API. Every call carries a fresh access token; a 401 refreshes the
3
+ // token once and retries (it may have expired a moment ago).
4
+ /** The server answered with an error: a fixed code and a message written for you. */
5
+ export class ServerError extends Error {
6
+ status;
7
+ code;
8
+ constructor(status, code, message) {
9
+ super(message);
10
+ this.name = "ServerError";
11
+ this.status = status;
12
+ this.code = code;
13
+ }
14
+ }
15
+ export class ServerClient {
16
+ fetchFn;
17
+ serverUrl;
18
+ tokens;
19
+ constructor(fetchFn, serverUrl, tokens) {
20
+ this.fetchFn = fetchFn;
21
+ this.serverUrl = serverUrl;
22
+ this.tokens = tokens;
23
+ }
24
+ async call(path, init, timeoutMs = 30_000) {
25
+ for (let attempt = 0;; attempt++) {
26
+ const token = await this.tokens.get();
27
+ const res = await this.fetchFn(`${this.serverUrl}/api/agent/v1${path}`, {
28
+ ...init,
29
+ headers: { ...init.headers, authorization: `Bearer ${token}` },
30
+ ...(timeoutMs !== null && !init.signal ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
31
+ });
32
+ if (res.status === 401 && attempt === 0) {
33
+ this.tokens.invalidate();
34
+ continue;
35
+ }
36
+ if (!res.ok) {
37
+ let code = `http_${res.status}`;
38
+ let message = `The server answered HTTP ${res.status}.`;
39
+ try {
40
+ const parsed = agentApiError.safeParse(await res.json());
41
+ if (parsed.success)
42
+ ({ code, message } = parsed.data.error);
43
+ }
44
+ catch {
45
+ // no JSON body
46
+ }
47
+ throw new ServerError(res.status, code, message);
48
+ }
49
+ return res;
50
+ }
51
+ }
52
+ async post(path, body, parse) {
53
+ const res = await this.call(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
54
+ return parse(await res.json());
55
+ }
56
+ register(name) {
57
+ return this.post("/hosts", { name }, (v) => registerHostResponse.parse(v));
58
+ }
59
+ hello(hostId, body) {
60
+ return this.post(`/hosts/${hostId}/hello`, body, (v) => helloResponse.parse(v));
61
+ }
62
+ heartbeat(hostId, body) {
63
+ return this.post(`/hosts/${hostId}/heartbeat`, body, () => undefined);
64
+ }
65
+ /** Sends a batch of one job's events. Returns true when the server says the job is cancelled. */
66
+ async jobEvents(hostId, jobId, seq, events) {
67
+ return this.post(`/hosts/${hostId}/jobs/${jobId}/events`, { seq, events }, (v) => jobEventsResponse.parse(v).cancelled);
68
+ }
69
+ /** Opens the job stream. Stays open until the server closes it or `signal` aborts. */
70
+ async openStream(hostId, signal) {
71
+ const res = await this.call(`/hosts/${hostId}/stream`, { method: "GET", headers: { accept: "text/event-stream" }, signal }, null);
72
+ if (!res.body)
73
+ throw new ServerError(502, "empty_stream", "The server opened an empty stream.");
74
+ return res.body;
75
+ }
76
+ }