@oalo-ai/cli 0.4.5 → 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.
@@ -0,0 +1,363 @@
1
+ import { MAX_MODELS } from "./config.js";
2
+
3
+ /**
4
+ * The `model` handler: the box's model relay sends an OpenAI chat-completions
5
+ * body and a model id ("model_request"), and this forwards it to the model
6
+ * server in the handler's own config, streaming the reply back as
7
+ * "model_chunk" pushes and a closing "model_end". The box never sends a URL:
8
+ * every call goes to `${base_url}/chat/completions` and nowhere else.
9
+ *
10
+ * The bodies are conversations, so nothing here logs them. The local key
11
+ * (key_env names an env var) only goes to the model server.
12
+ */
13
+
14
+ const DEDUPE_MS = 10 * 60 * 1000;
15
+ // No bytes from the model server for this long ends the request. Long enough
16
+ // for a local model to load before its first token.
17
+ export const IDLE_MS = 5 * 60 * 1000;
18
+
19
+ /** The upstream body for one request: stream and thinking set for its server. */
20
+ export function upstreamBody(handler, payload) {
21
+ const body = JSON.parse(JSON.stringify(payload.body));
22
+ // The model is the one that was checked against the handler's list.
23
+ body.model = payload.model;
24
+ if (payload.stream === true) {
25
+ body.stream = true;
26
+ body.stream_options = { include_usage: true };
27
+ } else {
28
+ body.stream = false;
29
+ delete body.stream_options;
30
+ }
31
+ if (payload.thinking === "off") {
32
+ if (handler.server === "ollama") body.reasoning_effort = "none";
33
+ else if (handler.server === "vllm") {
34
+ const kw = body.chat_template_kwargs && typeof body.chat_template_kwargs === "object" && !Array.isArray(body.chat_template_kwargs) ? body.chat_template_kwargs : {};
35
+ body.chat_template_kwargs = { ...kw, enable_thinking: false };
36
+ }
37
+ }
38
+ return body;
39
+ }
40
+
41
+ /** Headers for the model server. The key comes from the env var key_env names. */
42
+ export function upstreamHeaders(handler, env = process.env, accept = "text/event-stream") {
43
+ const headers = { "content-type": "application/json", accept };
44
+ if (handler.key_env && env[handler.key_env]) headers.authorization = `Bearer ${env[handler.key_env]}`;
45
+ return headers;
46
+ }
47
+
48
+ /** base_url without a trailing slash. */
49
+ export const trimUrl = (u) => String(u || "").replace(/\/+$/, "");
50
+
51
+ /** Why a fetch failed, in a few words, without the address. */
52
+ export function fetchError(e) {
53
+ const code = e?.cause?.code || e?.code;
54
+ if (code === "ECONNREFUSED") return "nothing is listening there (ECONNREFUSED). Is the model server running?";
55
+ if (code) return code;
56
+ return String(e?.cause?.message || e?.message || e).slice(0, 200);
57
+ }
58
+
59
+ // Did this chunk carry the model's first output (text, reasoning or a tool call)?
60
+ function hasOutput(j) {
61
+ const d = j?.choices?.[0]?.delta;
62
+ if (!d) return false;
63
+ return Boolean(d.content || d.reasoning_content || d.reasoning || (Array.isArray(d.tool_calls) && d.tool_calls.length));
64
+ }
65
+
66
+ /**
67
+ * Runs "model_request" pushes. `push(event, payload)` sends to the box;
68
+ * `log(entry)` gets one entry per call (requestLine prints it). Several run at
69
+ * once. A request_id seen in the last 10 minutes runs once: a repeat while it
70
+ * runs is ignored, a repeat after it ended gets a model_end error, and one
71
+ * that was cancelled gets nothing.
72
+ */
73
+ export class ModelRequests {
74
+ constructor({ handlers, push, log = () => {}, env = process.env, fetchImpl = globalThis.fetch, now = () => Date.now(), idleMs = IDLE_MS }) {
75
+ this.byName = new Map((handlers || []).filter((h) => h.kind === "model").map((h) => [h.name, h]));
76
+ this.push = push;
77
+ this.log = log;
78
+ this.env = env;
79
+ this.fetch = fetchImpl;
80
+ this.now = now;
81
+ this.idleMs = idleMs;
82
+ this.seen = new Map();
83
+ this.running = new Map();
84
+ }
85
+
86
+ prune() {
87
+ const t = this.now();
88
+ for (const [k, e] of this.seen) {
89
+ if (t - e.at > DEDUPE_MS) this.seen.delete(k);
90
+ else break; // insertion order is time order
91
+ }
92
+ }
93
+
94
+ /** Stop a running request. Nothing more is sent for it. */
95
+ cancel(payload) {
96
+ const id = payload?.request_id;
97
+ if (typeof id !== "string" || !id) return;
98
+ this.prune();
99
+ const e = this.seen.get(id);
100
+ if (!e) {
101
+ // A cancel that beat its request: the request is then ignored.
102
+ this.seen.set(id, { at: this.now(), state: "cancelled" });
103
+ return;
104
+ }
105
+ if (e.state !== "running") return;
106
+ e.state = "cancelled";
107
+ this.running.get(id)?.abort();
108
+ }
109
+
110
+ /** Stop every running request quietly (the connection to the box dropped). */
111
+ abortAll() {
112
+ for (const [id, c] of this.running) {
113
+ const e = this.seen.get(id);
114
+ if (e) e.state = "cancelled";
115
+ c.abort();
116
+ }
117
+ }
118
+
119
+ end(id, payload) {
120
+ const e = this.seen.get(id);
121
+ if (e?.state === "cancelled") return;
122
+ if (e) e.state = "done";
123
+ this.push("model_end", { request_id: id, ...payload });
124
+ }
125
+
126
+ /** Handle one "model_request". Resolves when it has ended (or was ignored). */
127
+ async handle(payload) {
128
+ const id = payload?.request_id;
129
+ if (typeof id !== "string" || !id) return;
130
+ this.prune();
131
+ const before = this.seen.get(id);
132
+ if (before) {
133
+ if (before.state === "done") this.push("model_end", { request_id: id, error: "repeated request: it already ran" });
134
+ this.log({ model: payload.model ?? "?", handler: payload.handler, duplicate: true, resent: false });
135
+ return;
136
+ }
137
+ this.seen.set(id, { at: this.now(), state: "running" });
138
+
139
+ const started = this.now();
140
+ const entry = { handler: payload.handler, model: payload.model ?? "?", modelCall: true };
141
+ const finish = (r) => {
142
+ entry.ms = this.now() - started;
143
+ Object.assign(entry, r);
144
+ this.log(entry);
145
+ };
146
+ const refuse = (error) => {
147
+ this.end(id, { error });
148
+ finish({ ok: false, error });
149
+ };
150
+
151
+ const h = this.byName.get(payload.handler);
152
+ if (!h) return refuse(`this machine has no model handler called ${payload.handler}`);
153
+ if (typeof payload.model !== "string" || !(h.models || []).some((m) => m.id === payload.model))
154
+ return refuse(`${h.name} doesn't serve the model ${payload.model}`);
155
+ if (!payload.body || typeof payload.body !== "object" || Array.isArray(payload.body)) return refuse("the request has no body");
156
+ if (h.key_env && !this.env[h.key_env]) return refuse(`${h.key_env} isn't set where oalo serve runs, so there's no key for the model server`);
157
+
158
+ const stream = payload.stream === true;
159
+ const body = upstreamBody(h, payload);
160
+ const controller = new AbortController();
161
+ this.running.set(id, controller);
162
+ let idle = null;
163
+ let timedOut = false;
164
+ const touch = () => {
165
+ clearTimeout(idle);
166
+ idle = setTimeout(() => {
167
+ timedOut = true;
168
+ controller.abort();
169
+ }, this.idleMs);
170
+ idle.unref?.();
171
+ };
172
+ const cancelled = () => this.seen.get(id)?.state === "cancelled";
173
+
174
+ let seq = 0;
175
+ let usage = null;
176
+ let firstAt = null;
177
+ const chunk = (data) => {
178
+ if (cancelled()) return;
179
+ this.push("model_chunk", { request_id: id, seq: seq++, data });
180
+ };
181
+
182
+ try {
183
+ touch();
184
+ let res;
185
+ try {
186
+ res = await this.fetch(`${trimUrl(h.base_url)}/chat/completions`, {
187
+ method: "POST",
188
+ headers: upstreamHeaders(h, this.env, stream ? "text/event-stream" : "application/json"),
189
+ body: JSON.stringify(body),
190
+ signal: controller.signal,
191
+ });
192
+ } catch (e) {
193
+ if (cancelled()) return finish({ ok: false, cancelled: true });
194
+ const error = timedOut ? "the model server didn't answer in 5 minutes" : `can't reach the model server: ${fetchError(e)}`;
195
+ this.end(id, { error });
196
+ return finish({ ok: false, error });
197
+ }
198
+ touch();
199
+
200
+ if (!res.ok) {
201
+ let text = "";
202
+ try {
203
+ text = await res.text();
204
+ } catch {
205
+ /* keep it empty */
206
+ }
207
+ const error = `upstream ${res.status}: ${text.slice(0, 300)}`;
208
+ this.end(id, { error, status: res.status });
209
+ return finish({ ok: false, error: `upstream ${res.status}` });
210
+ }
211
+
212
+ if (!stream) {
213
+ const text = await res.text();
214
+ firstAt = this.now();
215
+ try {
216
+ usage = JSON.parse(text)?.usage ?? null;
217
+ } catch {
218
+ /* not JSON: still forwarded as is */
219
+ }
220
+ chunk(text);
221
+ } else {
222
+ const reader = res.body.getReader();
223
+ const dec = new TextDecoder();
224
+ let buf = "";
225
+ const line = (raw) => {
226
+ const l = raw.replace(/\r$/, "");
227
+ if (!l.startsWith("data:")) return;
228
+ const data = l.slice(5).replace(/^ /, "");
229
+ if (data.trim() === "[DONE]" || !data.trim()) return;
230
+ try {
231
+ const j = JSON.parse(data);
232
+ if (j?.usage) usage = j.usage;
233
+ if (firstAt === null && hasOutput(j)) firstAt = this.now();
234
+ } catch {
235
+ /* forwarded as is; the relay decides */
236
+ }
237
+ chunk(data);
238
+ };
239
+ for (;;) {
240
+ const { done, value } = await reader.read();
241
+ if (done) break;
242
+ touch();
243
+ buf += dec.decode(value, { stream: true });
244
+ let i;
245
+ while ((i = buf.indexOf("\n")) >= 0) {
246
+ line(buf.slice(0, i));
247
+ buf = buf.slice(i + 1);
248
+ }
249
+ }
250
+ buf += dec.decode();
251
+ if (buf) line(buf);
252
+ }
253
+ } catch (e) {
254
+ if (cancelled()) return finish({ ok: false, cancelled: true });
255
+ const error = timedOut ? "the model server sent nothing for 5 minutes" : `the model server stopped mid-reply: ${fetchError(e)}`;
256
+ this.end(id, { error });
257
+ return finish({ ok: false, error });
258
+ } finally {
259
+ clearTimeout(idle);
260
+ this.running.delete(id);
261
+ }
262
+
263
+ if (cancelled()) return finish({ ok: false, cancelled: true });
264
+ this.end(id, { usage });
265
+ finish({
266
+ ok: true,
267
+ firstMs: firstAt === null ? null : firstAt - started,
268
+ inTokens: usage?.prompt_tokens ?? null,
269
+ outTokens: usage?.completion_tokens ?? null,
270
+ chunks: seq,
271
+ });
272
+ }
273
+ }
274
+
275
+ /** Ollama's native API root for an OpenAI-style base_url (`.../v1` -> `...`). */
276
+ export const ollamaRoot = (baseUrl) => trimUrl(baseUrl).replace(/\/v1$/, "");
277
+
278
+ /** Is this host on this computer or a private network? */
279
+ export function isLocalHost(hostname) {
280
+ const h = String(hostname || "").toLowerCase().replace(/^\[|\]$/g, "");
281
+ if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".lan") || h.endsWith(".internal")) return true;
282
+ const v4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(h);
283
+ if (v4) {
284
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
285
+ return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
286
+ }
287
+ if (h === "::1") return true;
288
+ if (/^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h)) return true;
289
+ return false;
290
+ }
291
+
292
+ /**
293
+ * Read a model server's models for `oalo serve add model`. Returns
294
+ * {models, server, notes, skipped} or {error}. `only` limits it to those ids.
295
+ */
296
+ export async function discoverModels({ baseUrl, server, only, key, fetchImpl = globalThis.fetch, timeoutMs = 15000 }) {
297
+ const headers = { accept: "application/json" };
298
+ if (key) headers.authorization = `Bearer ${key}`;
299
+ const get = async (url, init = {}) => {
300
+ const r = await fetchImpl(url, { ...init, headers: { ...headers, ...(init.headers || {}) }, signal: AbortSignal.timeout(timeoutMs) });
301
+ const text = await r.text();
302
+ if (!r.ok) throw Object.assign(new Error(`${r.status}: ${text.slice(0, 200)}`), { status: r.status });
303
+ return JSON.parse(text);
304
+ };
305
+
306
+ let list;
307
+ try {
308
+ list = await get(`${trimUrl(baseUrl)}/models`);
309
+ } catch (e) {
310
+ return { error: `couldn't list the models at ${trimUrl(baseUrl)}/models: ${e.status ? e.message : fetchError(e)}`, unreachable: !e.status };
311
+ }
312
+ const data = Array.isArray(list?.data) ? list.data.filter((m) => m && typeof m.id === "string") : [];
313
+ if (!data.length) return { error: `${trimUrl(baseUrl)}/models lists no models. Load or pull one first.` };
314
+
315
+ // vLLM marks its models as its own.
316
+ if (!server) server = data.some((m) => m.owned_by === "vllm") ? "vllm" : "openai";
317
+
318
+ let picked = data;
319
+ if (only) {
320
+ // Ollama answers to "qwen3-8k" for "qwen3-8k:latest", so the short name finds it too.
321
+ const find = (id) => data.find((m) => m.id === id) || (!id.includes(":") && data.find((m) => m.id === `${id}:latest`));
322
+ const missing = only.filter((id) => !find(id));
323
+ if (missing.length) return { error: `the server doesn't list ${missing.join(", ")}. It has: ${data.map((m) => m.id).join(", ")}` };
324
+ picked = only.map(find);
325
+ }
326
+
327
+ const models = [];
328
+ const skipped = [];
329
+ const notes = [];
330
+ for (const m of picked) {
331
+ const out = { id: m.id, context: null, vision: false };
332
+ if (Number.isInteger(m.max_model_len) && m.max_model_len > 0) out.context = m.max_model_len;
333
+ if (server === "ollama") {
334
+ let show = null;
335
+ try {
336
+ show = await get(`${ollamaRoot(baseUrl)}/api/show`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: m.id }) });
337
+ } catch (e) {
338
+ notes.push(`couldn't read ${m.id}'s details from Ollama (${e.status ? e.message : fetchError(e)})`);
339
+ }
340
+ if (show) {
341
+ const caps = Array.isArray(show.capabilities) ? show.capabilities : [];
342
+ // An embedding model can't chat. Skipped unless it was asked for.
343
+ if (!only && caps.length && !caps.includes("completion")) {
344
+ skipped.push(m.id);
345
+ continue;
346
+ }
347
+ out.vision = caps.includes("vision");
348
+ const info = show.model_info && typeof show.model_info === "object" ? show.model_info : {};
349
+ const key = Object.keys(info).find((k) => k.endsWith(".context_length"));
350
+ const max = key && Number.isInteger(info[key]) ? info[key] : null;
351
+ const numCtx = /^num_ctx\s+(\d+)/m.exec(String(show.parameters || ""));
352
+ if (numCtx) out.context = Number(numCtx[1]);
353
+ else if (max) {
354
+ out.context = max;
355
+ out.ollamaMax = true;
356
+ }
357
+ }
358
+ }
359
+ models.push(out);
360
+ }
361
+ if (models.length > MAX_MODELS) return { error: `that's ${models.length} models; a handler declares up to ${MAX_MODELS}. Pick some with --models id1,id2` };
362
+ return { models, server, notes, skipped };
363
+ }
@@ -0,0 +1,292 @@
1
+ import { Socket } from "phoenix";
2
+ import WebSocket from "ws";
3
+ import { existsSync, statSync } from "node:fs";
4
+ import { FolderIndex, runFolder } from "./folder.js";
5
+ import { runCommand } from "./command.js";
6
+ import { ModelRequests } from "./model.js";
7
+ import { declaration, inputError, clampTimeout, MAX_OUTPUT_BYTES, size } from "./config.js";
8
+
9
+ /**
10
+ * `oalo serve`'s side of the node protocol. The machine opens an outbound
11
+ * socket to its box (`<base>/node`, auth by node token), joins
12
+ * `node:<node_id>` declaring its handlers, then answers each "request" push
13
+ * with a "result" push. Nothing listens on the machine.
14
+ *
15
+ * A model handler answers "model_request" pushes instead (model.js), with
16
+ * "model_chunk" pushes and a "model_end".
17
+ *
18
+ * Request content can be customer data, so nothing here prints it: the log
19
+ * line has the handler, the time taken, ok or the error, and sizes.
20
+ */
21
+
22
+ const DEDUPE_MS = 10 * 60 * 1000;
23
+ const bytes = (v) => Buffer.byteLength(JSON.stringify(v ?? null), "utf8");
24
+
25
+ /** Backoff for reconnects and rejoins: 1s, 2s, 4s ... up to 30s. */
26
+ export const backoff = (tries) => Math.min(1000 * 2 ** Math.max(0, tries - 1), 30000);
27
+
28
+ /**
29
+ * Runs a request against the machine's handlers. One per machine; it keeps
30
+ * each folder's index between requests.
31
+ */
32
+ export class Handlers {
33
+ constructor(handlers, { env = process.env } = {}) {
34
+ this.list = handlers;
35
+ this.byName = new Map(handlers.map((h) => [h.name, h]));
36
+ this.indexes = new Map();
37
+ this.env = env;
38
+ }
39
+
40
+ async run(name, input, context = {}, deadlineMs) {
41
+ const h = this.byName.get(name);
42
+ if (!h) return { ok: false, error: `this machine has no handler called ${name}` };
43
+ if (h.kind === "model") return { ok: false, error: `${name} is a model handler: it serves the bot's model, not a tool call` };
44
+ const schema = declaration(h).input_schema;
45
+ const bad = inputError(input, schema);
46
+ if (bad) return { ok: false, error: bad };
47
+ const timeoutMs = Math.min(clampTimeout(h.timeout_ms), Number(deadlineMs) > 0 ? Number(deadlineMs) : Infinity);
48
+
49
+ if (h.kind === "folder") {
50
+ const root = h.folder?.path;
51
+ if (!root || !existsSync(root) || !statSync(root).isDirectory()) return { ok: false, error: "the folder isn't there any more" };
52
+ let index = this.indexes.get(h.name);
53
+ if (!index) this.indexes.set(h.name, (index = new FolderIndex(root)));
54
+ return runFolder(index, input);
55
+ }
56
+ if (h.kind === "command") return runCommand(h, input, context, { timeoutMs, env: this.env });
57
+ return { ok: false, error: `this CLI can't run ${h.kind} handlers yet` };
58
+ }
59
+ }
60
+
61
+ /** The output as a result, or the size error when it's over 64 KB. */
62
+ export function capOutput(r) {
63
+ if (!r.ok) return r;
64
+ const n = bytes(r.output);
65
+ if (n > MAX_OUTPUT_BYTES) return { ok: false, error: `output too large (${Math.ceil(n / 1024)} KB, max 64 KB)` };
66
+ return r;
67
+ }
68
+
69
+ /**
70
+ * Turns "request" pushes into "result" pushes. `push(event, payload)` sends
71
+ * to the box; `log(line)` gets one line per request. A request_id seen in the
72
+ * last 10 minutes runs once: while it runs a repeat is ignored, and after it
73
+ * finished its answer is sent again. The box sends a flow step's request again
74
+ * after a reconnect, and the first answer may have been lost with the old
75
+ * connection.
76
+ */
77
+ export class RequestHandler {
78
+ constructor({ handlers, push, log = () => {}, now = () => Date.now() }) {
79
+ this.handlers = handlers;
80
+ this.push = push;
81
+ this.log = log;
82
+ this.now = now;
83
+ this.seen = new Map();
84
+ }
85
+
86
+ // The entry for a request seen recently ({at, result}), or null after
87
+ // recording this one as new.
88
+ seenBefore(id) {
89
+ const t = this.now();
90
+ for (const [k, e] of this.seen) {
91
+ if (t - e.at > DEDUPE_MS) this.seen.delete(k);
92
+ else break; // insertion order is time order
93
+ }
94
+ const e = this.seen.get(id);
95
+ if (e) return e;
96
+ this.seen.set(id, { at: t, result: null });
97
+ return null;
98
+ }
99
+
100
+ /** Handle one "request" payload. Resolves once the result is pushed (or the request ignored). */
101
+ async handle(payload) {
102
+ const id = payload?.request_id;
103
+ if (typeof id !== "string" || !id) return null;
104
+ const before = this.seenBefore(id);
105
+ if (before) {
106
+ if (before.result) this.push("result", before.result);
107
+ this.log({ handler: payload.handler, duplicate: true, resent: Boolean(before.result) });
108
+ return before.result;
109
+ }
110
+ const started = this.now();
111
+ let r;
112
+ try {
113
+ r = await this.handlers.run(payload.handler, payload.input ?? {}, payload.context ?? {}, payload.deadline_ms);
114
+ } catch (e) {
115
+ r = { ok: false, error: `the handler failed: ${e?.message || e}` };
116
+ }
117
+ r = capOutput(r);
118
+ const result = r.ok ? { request_id: id, ok: true, output: r.output } : { request_id: id, ok: false, error: String(r.error).slice(0, 500) };
119
+ const entry = this.seen.get(id);
120
+ if (entry) entry.result = result;
121
+ this.push("result", result);
122
+ this.log({
123
+ handler: payload.handler,
124
+ ms: this.now() - started,
125
+ ok: r.ok,
126
+ error: r.ok ? null : result.error,
127
+ inBytes: bytes(payload.input),
128
+ outBytes: r.ok ? bytes(r.output) : 0,
129
+ });
130
+ return result;
131
+ }
132
+ }
133
+
134
+ /** One log line for a request. Sizes only: never the input or output itself. */
135
+ export function requestLine(e, at = new Date()) {
136
+ const time = at.toTimeString().slice(0, 8);
137
+ if (e.modelCall) {
138
+ const head = `${time} ${e.handler} ${e.model} ${e.ms} ms`;
139
+ if (e.cancelled) return `${head} cancelled`;
140
+ if (!e.ok) return `${head} error: ${e.error}`;
141
+ const first = e.firstMs === null || e.firstMs === undefined ? "" : `first token ${e.firstMs} ms, `;
142
+ const tokens = e.inTokens === null || e.inTokens === undefined ? "tokens not reported" : `tokens in ${e.inTokens}, out ${e.outTokens ?? "?"}`;
143
+ return `${head} ok ${first}${tokens}`;
144
+ }
145
+ if (e.duplicate) return `${time} ${e.handler ?? "?"} ${e.resent ? "sent its answer again (repeated request)" : "ignored a repeated request (still running)"}`;
146
+ const status = e.ok ? "ok" : `error: ${e.error}`;
147
+ return `${time} ${e.handler} ${e.ms} ms ${status} in ${size(e.inBytes)}, out ${size(e.outBytes)}`;
148
+ }
149
+
150
+ /** What a refused join means, in words, and whether retrying could help. */
151
+ export function joinRefusal(err, machine) {
152
+ const reason = typeof err?.reason === "string" ? err.reason : null;
153
+ if (reason === "revoked")
154
+ return { fatal: true, message: `${machine}'s key was revoked, so the box won't take it. Make a new one with: oalo machines add ${machine}` };
155
+ if (reason === "unknown_node")
156
+ return { fatal: true, message: `the box doesn't know a machine with this key (it may have been removed). Set it up again with: oalo machines add ${machine}` };
157
+ if (reason === "invalid" || reason === "unauthorized")
158
+ return { fatal: true, message: `the box refused ${machine}'s handlers: ${err?.message || reason}. Check them with: oalo serve list` };
159
+ const text = err?.message || (reason ? reason.replace(/_/g, " ") : "no reason given");
160
+ return { fatal: false, message: `the box refused the connection: ${text}. Trying again.` };
161
+ }
162
+
163
+ /**
164
+ * Connect, join and serve until stopped. Events go to `on`:
165
+ * joined({node, tools, skipped}), dropped(), retrying(), fatal(message),
166
+ * request(entry) with what requestLine takes.
167
+ * Returns {stop()}.
168
+ */
169
+ export function serveNode(cfg, opts = {}) {
170
+ const { version, on = {}, SocketImpl = Socket, transport = WebSocket, env = process.env } = opts;
171
+ const emit = (name, ...a) => {
172
+ try {
173
+ on[name]?.(...a);
174
+ } catch {
175
+ /* a printer must not break the connection */
176
+ }
177
+ };
178
+ const wsUrl = String(cfg.url).replace(/^http/, "ws").replace(/\/$/, "") + "/node";
179
+ const socket = new SocketImpl(wsUrl, {
180
+ params: { node_token: cfg.token },
181
+ transport,
182
+ heartbeatIntervalMs: 30000,
183
+ reconnectAfterMs: backoff,
184
+ rejoinAfterMs: backoff,
185
+ // The socket address carries the key; debug output must never show it.
186
+ logger: env.OALO_DEBUG ? (kind, msg) => process.stderr.write(`[phoenix] ${kind}: ${String(msg).replace(/(node_token|cli_token)=[^&\s]+/g, "$1=***")}\n`) : () => {},
187
+ });
188
+
189
+ const handlers = new Handlers(cfg.handlers, { env });
190
+ const channel = socket.channel(`node:${cfg.node_id}`, () => ({ version, handlers: cfg.handlers.map(declaration) }));
191
+ const push = (event, payload) => {
192
+ // The box doesn't need to reply; a push with no timeout handler would
193
+ // just sit there, so it gets one that does nothing.
194
+ try {
195
+ channel.push(event, payload, 30000).receive("timeout", () => {});
196
+ } catch {
197
+ /* not joined right now: the box times the request out */
198
+ }
199
+ };
200
+ const requests = new RequestHandler({ handlers, push, log: (e) => emit("request", e) });
201
+ const models = new ModelRequests({ handlers: cfg.handlers, push, env, log: (e) => emit("request", e), fetchImpl: opts.fetchImpl });
202
+
203
+ let stopped = false;
204
+ let joinedOnce = false;
205
+ let wasUp = false;
206
+
207
+ channel.on("request", (payload) => {
208
+ requests.handle(payload);
209
+ });
210
+ channel.on("model_request", (payload) => {
211
+ models.handle(payload);
212
+ });
213
+ channel.on("model_cancel", (payload) => {
214
+ models.cancel(payload);
215
+ });
216
+
217
+ // The box says why it is closing this connection.
218
+ channel.on("revoked", () => {
219
+ stop();
220
+ emit("fatal", `${cfg.name}'s key was revoked, so the box won't take it. Make a new one with: oalo machines add ${cfg.name}`);
221
+ });
222
+ channel.on("superseded", () => {
223
+ stop();
224
+ emit("fatal", `${cfg.name} connected again from somewhere else (another oalo serve with the same key), so this one stopped.`);
225
+ });
226
+
227
+ // The Phoenix client doesn't reconnect after a clean close from the server
228
+ // (code 1000), and with nothing else scheduled Node would just exit, silently.
229
+ // So after any close we check back, and connect again ourselves if it hasn't.
230
+ let tries = 0;
231
+ let watchdog = null;
232
+ const ensureReconnect = () => {
233
+ if (stopped || watchdog) return;
234
+ const wait = backoff(++tries) + 500;
235
+ watchdog = setTimeout(() => {
236
+ watchdog = null;
237
+ if (stopped) return;
238
+ if (!socket.isConnected()) {
239
+ try { socket.connect(); } catch { /* next close schedules another try */ }
240
+ ensureReconnect();
241
+ }
242
+ }, wait);
243
+ };
244
+
245
+ const stop = () => {
246
+ if (stopped) return;
247
+ stopped = true;
248
+ models.abortAll();
249
+ if (watchdog) clearTimeout(watchdog);
250
+ try { channel.leave(); } catch { /* gone */ }
251
+ try { socket.disconnect(); } catch { /* gone */ }
252
+ };
253
+
254
+ socket.onOpen(() => {
255
+ tries = 0;
256
+ });
257
+
258
+ // A failed connect and a dropped connection both end in close.
259
+ socket.onClose(() => {
260
+ // The box ends a model turn when its machine drops, so stop the model too.
261
+ models.abortAll();
262
+ if (stopped) return;
263
+ ensureReconnect();
264
+ if (wasUp) {
265
+ wasUp = false;
266
+ emit("dropped");
267
+ } else {
268
+ emit("retrying", joinedOnce);
269
+ }
270
+ });
271
+
272
+ channel
273
+ .join()
274
+ .receive("ok", (reply) => {
275
+ joinedOnce = true;
276
+ wasUp = true;
277
+ emit("joined", reply || {});
278
+ })
279
+ .receive("error", (err) => {
280
+ const r = joinRefusal(err, cfg.name);
281
+ if (r.fatal) {
282
+ stop();
283
+ emit("fatal", r.message);
284
+ } else {
285
+ emit("refused", r.message);
286
+ }
287
+ })
288
+ .receive("timeout", () => emit("retrying", joinedOnce));
289
+
290
+ socket.connect();
291
+ return { stop, channel, socket, requests, models };
292
+ }