@oalo-ai/cli 0.4.5 → 0.5.1

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,215 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, chmodSync, existsSync, renameSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * The machine configs `oalo serve` runs from: ~/.oalo/serve/<machine>.json,
7
+ * one per machine, written by `oalo machines add` and edited by
8
+ * `oalo serve add|remove`.
9
+ *
10
+ * { name, node_id, url, token, handlers: [{ name, kind, description,
11
+ * timeout_ms, input_schema, folder?: { path }, command?: { argv, cwd? } }] }
12
+ *
13
+ * A model handler has no input_schema or timeout. It holds base_url, server
14
+ * (ollama, vllm or openai), key_env (the NAME of an env var holding the model
15
+ * server's key, never the key) and models: [{ id, label?, context, output, vision }].
16
+ *
17
+ * The token is a node token: it can only answer the box's requests for this
18
+ * machine. It is still a credential, so the folder is 0700 and each file 0600,
19
+ * and nothing in the CLI prints it.
20
+ *
21
+ * OALO_HOME moves the `~` part, as for the credential store, so tests never
22
+ * touch a real home. Read on each call, not at import, for the same reason.
23
+ */
24
+
25
+ export const MACHINE_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
26
+ export const HANDLER_NAME = /^[a-z][a-z0-9_]{0,47}$/;
27
+ export const KINDS = ["folder", "command", "model"];
28
+ export const MODEL_SERVERS = ["ollama", "vllm", "openai"];
29
+ export const MAX_MODELS = 32;
30
+ export const DEFAULT_TIMEOUT_MS = 30000;
31
+ export const MAX_TIMEOUT_MS = 3_600_000;
32
+ export const MAX_OUTPUT_BYTES = 1024 * 1024;
33
+
34
+ /** The input every folder handler takes. Fixed: the bot only ever sends a query. */
35
+ export const FOLDER_SCHEMA = Object.freeze({
36
+ type: "object",
37
+ properties: {
38
+ query: { type: "string", description: "What to look for" },
39
+ limit: { type: "integer", description: "How many snippets, 1-10" },
40
+ },
41
+ required: ["query"],
42
+ });
43
+
44
+ export function serveDir() {
45
+ return join(process.env.OALO_HOME || homedir(), ".oalo", "serve");
46
+ }
47
+
48
+ export function machinePath(name) {
49
+ return join(serveDir(), `${name}.json`);
50
+ }
51
+
52
+ export function machineNameError(name) {
53
+ if (typeof name !== "string" || !name) return "a machine needs a name, like shop-pc";
54
+ if (!MACHINE_NAME.test(name)) return `"${name}" can't be a machine name. Use lowercase letters, digits and hyphens, up to 40, starting with a letter or digit (shop-pc).`;
55
+ return null;
56
+ }
57
+
58
+ export function handlerNameError(name) {
59
+ if (typeof name !== "string" || !name) return "a handler needs a name, like handbook";
60
+ if (!HANDLER_NAME.test(name)) return `"${name}" can't be a handler name. It becomes the bot's tool name: lowercase letters, digits and underscores, up to 48, starting with a letter (stock, return_policy).`;
61
+ return null;
62
+ }
63
+
64
+ /** The machine names with a config on this computer, sorted. */
65
+ export function localMachines() {
66
+ let names;
67
+ try {
68
+ names = readdirSync(serveDir());
69
+ } catch {
70
+ return [];
71
+ }
72
+ return names
73
+ .filter((f) => f.endsWith(".json"))
74
+ .map((f) => f.slice(0, -5))
75
+ .filter((n) => MACHINE_NAME.test(n))
76
+ .sort();
77
+ }
78
+
79
+ /** The machine's config, or null when this computer has none for it. Throws on a broken file. */
80
+ export function readMachine(name) {
81
+ const path = machinePath(name);
82
+ let text;
83
+ try {
84
+ text = readFileSync(path, "utf8");
85
+ } catch {
86
+ return null;
87
+ }
88
+ let cfg;
89
+ try {
90
+ cfg = JSON.parse(text);
91
+ } catch {
92
+ throw new Error(`${path} isn't valid JSON. Fix it, or remove it and run \`oalo machines add ${name}\` again.`);
93
+ }
94
+ if (!Array.isArray(cfg.handlers)) cfg.handlers = [];
95
+ return cfg;
96
+ }
97
+
98
+ /** Write a machine's config: folder 0700, file 0600, replaced in one step. */
99
+ export function writeMachine(cfg) {
100
+ const dir = serveDir();
101
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
102
+ chmodSync(dir, 0o700);
103
+ const path = machinePath(cfg.name);
104
+ const tmp = `${path}.${process.pid}.tmp`;
105
+ writeFileSync(tmp, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
106
+ chmodSync(tmp, 0o600);
107
+ renameSync(tmp, path);
108
+ return path;
109
+ }
110
+
111
+ /**
112
+ * Which machine a command means: --machine, else the only one on this
113
+ * computer. Returns {name} or {error, code}.
114
+ */
115
+ export function pickMachine(flag) {
116
+ if (flag === true) return { error: "--machine needs a name", code: 2 };
117
+ if (typeof flag === "string") {
118
+ const bad = machineNameError(flag);
119
+ if (bad) return { error: bad, code: 2 };
120
+ if (!existsSync(machinePath(flag))) return { error: `this computer has no machine called ${flag}. Set it up with: oalo machines add ${flag}`, code: 2 };
121
+ return { name: flag };
122
+ }
123
+ const all = localMachines();
124
+ if (!all.length) return { error: "this computer isn't set up as a machine yet. Run: oalo machines add <name> (like: oalo machines add shop-pc)", code: 2 };
125
+ if (all.length > 1) return { error: `this computer has more than one machine (${all.join(", ")}). Say which with --machine <name>.`, code: 2 };
126
+ return { name: all[0] };
127
+ }
128
+
129
+ /**
130
+ * `sku:string,qty:integer?` as a JSON Schema. A `?` makes a field optional.
131
+ * Types: string, integer, number, boolean. Returns {schema} or {error}.
132
+ */
133
+ export function parseInputSpec(spec) {
134
+ const schema = { type: "object", properties: {}, required: [] };
135
+ if (spec === undefined || spec === null || spec === "") return { schema: { type: "object", properties: {} } };
136
+ if (typeof spec !== "string") return { error: "--input needs fields, like --input 'sku:string,qty:integer?'" };
137
+ for (const raw of spec.split(",").map((s) => s.trim()).filter(Boolean)) {
138
+ const m = /^([a-z_][a-z0-9_]{0,63}):(string|integer|number|boolean)(\?)?$/i.exec(raw);
139
+ if (!m) return { error: `--input: "${raw}" isn't name:type. Types are string, integer, number and boolean; add ? for an optional field, in quotes: --input 'sku:string,qty:integer?'.` };
140
+ const [, name, type, optional] = m;
141
+ if (schema.properties[name]) return { error: `--input: ${name} is listed twice` };
142
+ schema.properties[name] = { type };
143
+ if (!optional) schema.required.push(name);
144
+ }
145
+ if (!schema.required.length) delete schema.required;
146
+ return { schema };
147
+ }
148
+
149
+ /**
150
+ * Check an input against a handler's schema: an object, its required fields
151
+ * there, and each declared field of the declared type. Returns an error string
152
+ * or null. The box checks too; this keeps a handler from running on an input
153
+ * it never declared.
154
+ */
155
+ export function inputError(input, schema) {
156
+ if (!input || typeof input !== "object" || Array.isArray(input)) return "the input must be a JSON object";
157
+ for (const k of schema?.required || []) {
158
+ if (input[k] === undefined || input[k] === null) return `the input needs ${k}`;
159
+ }
160
+ for (const [k, p] of Object.entries(schema?.properties || {})) {
161
+ const v = input[k];
162
+ if (v === undefined || v === null || !p?.type) continue;
163
+ const ok =
164
+ p.type === "string" ? typeof v === "string"
165
+ : p.type === "integer" ? Number.isInteger(v)
166
+ : p.type === "number" ? typeof v === "number" && Number.isFinite(v)
167
+ : p.type === "boolean" ? typeof v === "boolean"
168
+ : p.type === "array" ? Array.isArray(v)
169
+ : p.type === "object" ? typeof v === "object" && !Array.isArray(v)
170
+ : true;
171
+ if (!ok) return `${k} should be ${p.type === "integer" ? "an" : "a"} ${p.type}`;
172
+ }
173
+ return null;
174
+ }
175
+
176
+ /** What the box is told about a handler at join: no paths, no argv, no URL or key. */
177
+ export function declaration(h) {
178
+ if (h.kind === "model") {
179
+ return {
180
+ name: h.name,
181
+ kind: "model",
182
+ description: h.description || "",
183
+ server: MODEL_SERVERS.includes(h.server) ? h.server : "openai",
184
+ models: (h.models || []).slice(0, MAX_MODELS).map(modelDeclaration),
185
+ };
186
+ }
187
+ return {
188
+ name: h.name,
189
+ kind: h.kind,
190
+ description: h.description || "",
191
+ input_schema: h.kind === "folder" ? FOLDER_SCHEMA : h.input_schema || { type: "object", properties: {} },
192
+ timeout_ms: clampTimeout(h.timeout_ms),
193
+ };
194
+ }
195
+
196
+ function modelDeclaration(m) {
197
+ const d = { id: String(m.id) };
198
+ if (m.label) d.label = String(m.label);
199
+ d.context = Math.max(0, Math.floor(Number(m.context) || 0));
200
+ d.output = Math.max(0, Math.floor(Number(m.output) || 0));
201
+ d.vision = m.vision === true;
202
+ return d;
203
+ }
204
+
205
+ export function clampTimeout(ms) {
206
+ const n = Number(ms);
207
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_TIMEOUT_MS;
208
+ return Math.min(Math.round(n), MAX_TIMEOUT_MS);
209
+ }
210
+
211
+ /** Bytes, the way the request log shows them. */
212
+ export function size(bytes) {
213
+ if (bytes < 1024) return `${bytes} B`;
214
+ return `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} KB`;
215
+ }
@@ -0,0 +1,372 @@
1
+ import { readdirSync, lstatSync, statSync, realpathSync, readFileSync } from "node:fs";
2
+ import { join, extname, sep } from "node:path";
3
+
4
+ /**
5
+ * The `folder` handler: keyword search over a local folder, so a bot can
6
+ * answer from documents that never leave the machine. Only the best snippets
7
+ * go back.
8
+ *
9
+ * Plain BM25 over lowercased, accent-folded words: customers write Spanish,
10
+ * and "devolución" has to find "devolucion". The index is kept in memory and
11
+ * checked on every search: a walk with one stat per file, and only files whose
12
+ * size or mtime changed are read again.
13
+ *
14
+ * It never reads outside the folder. Dot files and folders, node_modules and
15
+ * files over 2 MB are skipped, and a symlink counts only when it resolves
16
+ * inside the folder.
17
+ */
18
+
19
+ export const EXTENSIONS = new Set([
20
+ ".md", ".markdown", ".txt", ".csv", ".tsv", ".json", ".jsonl", ".html", ".htm",
21
+ ".xml", ".yaml", ".yml", ".toml", ".ini", ".sql",
22
+ ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py", ".ex", ".exs", ".rb", ".go", ".rs", ".sh", ".css",
23
+ ]);
24
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
25
+ const MAX_FILES = 20000;
26
+ const CHUNK = 800;
27
+ const SNIPPET = 1500;
28
+ const K1 = 1.2;
29
+ const B = 0.75;
30
+
31
+ /** Lowercase, accents off, split on anything that isn't a letter or digit. */
32
+ export function tokenize(text) {
33
+ return String(text)
34
+ .normalize("NFD")
35
+ .replace(/\p{M}+/gu, "")
36
+ .toLowerCase()
37
+ .split(/[^\p{L}\p{N}]+/u)
38
+ .filter((t) => t.length > 1 || /\d/.test(t));
39
+ }
40
+
41
+ /**
42
+ * A light ending trim for English and Spanish, so a search for "return policy"
43
+ * finds "Returns", "returned" finds "return", and "devolucion" finds
44
+ * "Devoluciones". Deliberately small: it only has to make the same word meet
45
+ * itself, not be a real stemmer. Runs on tokenize() output (lowercase, no accents).
46
+ */
47
+ export function stem(t) {
48
+ if (t.length <= 3 || /\d/.test(t)) return t;
49
+ if (t.endsWith("ciones")) return t.slice(0, -6) + "cion";
50
+ if (t.endsWith("ies") && t.length > 4) return t.slice(0, -3) + "y";
51
+ if (t.endsWith("ing") && t.length > 5) return undouble(t.slice(0, -3));
52
+ if (t.endsWith("ed") && t.length > 4) return undouble(t.slice(0, -2));
53
+ if (t.endsWith("es") && t.length > 4 && /[nrldzj]/.test(t[t.length - 3])) return t.slice(0, -2);
54
+ if (t.endsWith("s") && !t.endsWith("ss") && !t.endsWith("us") && !t.endsWith("is")) return t.slice(0, -1);
55
+ return t;
56
+ }
57
+
58
+ // "shipp" (from "shipping") -> "ship", but "fall", "press" stay.
59
+ function undouble(t) {
60
+ return /([^aeiouls])\1$/.test(t) ? t.slice(0, -1) : t;
61
+ }
62
+
63
+ /** The search terms of a text: tokens with their endings trimmed. */
64
+ export function terms(text) {
65
+ return tokenize(text).map(stem);
66
+ }
67
+
68
+ /** Text out of HTML: scripts, styles and tags dropped, common entities decoded. */
69
+ export function htmlText(html) {
70
+ return String(html)
71
+ .replace(/<!--[\s\S]*?-->/g, " ")
72
+ .replace(/<(script|style|noscript|template)\b[\s\S]*?<\/\1\s*>/gi, " ")
73
+ .replace(/<\/?(p|div|br|li|tr|h[1-6]|section|article|header|footer|table|ul|ol|blockquote|pre)\b[^>]*>/gi, "\n\n")
74
+ .replace(/<[^>]+>/g, " ")
75
+ .replace(/&nbsp;/g, " ")
76
+ .replace(/&amp;/g, "&")
77
+ .replace(/&lt;/g, "<")
78
+ .replace(/&gt;/g, ">")
79
+ .replace(/&quot;/g, '"')
80
+ .replace(/&#39;|&apos;/g, "'")
81
+ .replace(/&#(\d+);/g, (_, n) => safeChar(Number(n)))
82
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => safeChar(parseInt(n, 16)))
83
+ .replace(/[ \t]+/g, " ")
84
+ .replace(/\n[ \t]+/g, "\n")
85
+ .replace(/\n{3,}/g, "\n\n");
86
+ }
87
+
88
+ function safeChar(n) {
89
+ try {
90
+ return String.fromCodePoint(n);
91
+ } catch {
92
+ return " ";
93
+ }
94
+ }
95
+
96
+ // Pack paragraphs into chunks of up to CHUNK characters; a longer paragraph
97
+ // is cut at sentence ends, then hard.
98
+ function pack(paragraphs, prefix = "") {
99
+ const out = [];
100
+ let cur = "";
101
+ const room = CHUNK - (prefix ? prefix.length + 1 : 0);
102
+ const flush = () => {
103
+ if (cur.trim()) out.push(prefix && !cur.startsWith(prefix) ? `${prefix}\n${cur.trim()}` : cur.trim());
104
+ cur = "";
105
+ };
106
+ for (const p of paragraphs) {
107
+ for (const piece of split(p, room)) {
108
+ if (cur && cur.length + piece.length + 2 > room) flush();
109
+ cur = cur ? `${cur}\n\n${piece}` : piece;
110
+ }
111
+ }
112
+ flush();
113
+ return out;
114
+ }
115
+
116
+ function split(text, max) {
117
+ const t = text.trim();
118
+ if (!t) return [];
119
+ if (t.length <= max) return [t];
120
+ const out = [];
121
+ let cur = "";
122
+ for (const s of t.split(/(?<=[.!?])\s+/)) {
123
+ if (s.length > max) {
124
+ if (cur) out.push(cur), (cur = "");
125
+ for (let i = 0; i < s.length; i += max) out.push(s.slice(i, i + max));
126
+ continue;
127
+ }
128
+ if (cur && cur.length + s.length + 1 > max) out.push(cur), (cur = "");
129
+ cur = cur ? `${cur} ${s}` : s;
130
+ }
131
+ if (cur) out.push(cur);
132
+ return out;
133
+ }
134
+
135
+ /** Markdown or plain text: split at headings, then paragraphs, each chunk led by its heading. */
136
+ export function chunkText(text) {
137
+ const sections = [];
138
+ let heading = "";
139
+ let body = [];
140
+ const close = () => {
141
+ if (heading || body.some((l) => l.trim())) sections.push({ heading, body: body.join("\n") });
142
+ body = [];
143
+ };
144
+ for (const line of String(text).replace(/\r\n?/g, "\n").split("\n")) {
145
+ if (/^#{1,6}\s+\S/.test(line)) {
146
+ close();
147
+ heading = line.trim();
148
+ } else {
149
+ body.push(line);
150
+ }
151
+ }
152
+ close();
153
+ const chunks = [];
154
+ for (const s of sections) {
155
+ const paras = s.body.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
156
+ if (!paras.length) {
157
+ if (s.heading) chunks.push(s.heading);
158
+ continue;
159
+ }
160
+ chunks.push(...pack(paras, s.heading));
161
+ }
162
+ return chunks;
163
+ }
164
+
165
+ /** CSV or TSV rows, quoted fields (with commas, tabs or newlines inside) kept whole. */
166
+ export function rows(text) {
167
+ const out = [];
168
+ let cur = "";
169
+ let quoted = false;
170
+ const t = String(text).replace(/^/, "").replace(/\r\n?/g, "\n");
171
+ for (let i = 0; i < t.length; i++) {
172
+ const c = t[i];
173
+ if (c === '"') {
174
+ if (quoted && t[i + 1] === '"') {
175
+ cur += '""';
176
+ i++;
177
+ continue;
178
+ }
179
+ quoted = !quoted;
180
+ cur += c;
181
+ } else if (c === "\n" && !quoted) {
182
+ if (cur.trim()) out.push(cur);
183
+ cur = "";
184
+ } else {
185
+ cur += c;
186
+ }
187
+ }
188
+ if (cur.trim()) out.push(cur);
189
+ return out;
190
+ }
191
+
192
+ /** One chunk per row, each led by the header line, so a row stands alone. */
193
+ export function chunkTable(text) {
194
+ const [header, ...body] = rows(text);
195
+ if (!header) return [];
196
+ if (!body.length) return [header];
197
+ return body.map((r) => `${header}\n${r}`);
198
+ }
199
+
200
+ /** A JSON file: a list gives one chunk per item; anything else is read as text. */
201
+ export function chunkJson(text) {
202
+ let data;
203
+ try {
204
+ data = JSON.parse(text);
205
+ } catch {
206
+ return chunkText(text);
207
+ }
208
+ if (Array.isArray(data)) return data.flatMap((item) => split(typeof item === "string" ? item : JSON.stringify(item), CHUNK * 2));
209
+ return chunkText(JSON.stringify(data, null, 1));
210
+ }
211
+
212
+ export function chunkFile(path, text) {
213
+ const ext = extname(path).toLowerCase();
214
+ if (ext === ".csv" || ext === ".tsv") return chunkTable(text);
215
+ if (ext === ".json") return chunkJson(text);
216
+ if (ext === ".html" || ext === ".htm") return chunkText(htmlText(text));
217
+ return chunkText(text);
218
+ }
219
+
220
+ function inside(root, real) {
221
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
222
+ }
223
+
224
+ /**
225
+ * Every readable file under `root` (its real path), as {abs, rel, size, mtime}.
226
+ * Symlinks count only when they resolve inside the folder; a folder reached
227
+ * twice (a link loop) is read once.
228
+ */
229
+ export function walk(root) {
230
+ const realRoot = realpathSync(root);
231
+ const files = [];
232
+ const seen = new Set([realRoot]);
233
+ const visit = (dir, relDir) => {
234
+ let entries;
235
+ try {
236
+ entries = readdirSync(dir, { withFileTypes: true });
237
+ } catch {
238
+ return;
239
+ }
240
+ entries.sort((a, b) => a.name.localeCompare(b.name));
241
+ for (const e of entries) {
242
+ if (files.length >= MAX_FILES) return;
243
+ if (e.name.startsWith(".") || e.name === "node_modules") continue;
244
+ const abs = join(dir, e.name);
245
+ const rel = relDir ? `${relDir}/${e.name}` : e.name;
246
+ let st;
247
+ let real = abs;
248
+ try {
249
+ if (e.isSymbolicLink() || lstatSync(abs).isSymbolicLink()) {
250
+ real = realpathSync(abs);
251
+ if (!inside(realRoot, real)) continue;
252
+ }
253
+ st = statSync(real);
254
+ } catch {
255
+ continue;
256
+ }
257
+ if (st.isDirectory()) {
258
+ if (seen.has(real)) continue;
259
+ seen.add(real);
260
+ visit(real, rel);
261
+ } else if (st.isFile()) {
262
+ if (!EXTENSIONS.has(extname(e.name).toLowerCase())) continue;
263
+ if (st.size > MAX_FILE_BYTES) continue;
264
+ files.push({ abs: real, rel, size: st.size, mtime: st.mtimeMs });
265
+ }
266
+ }
267
+ };
268
+ visit(realRoot, "");
269
+ return { realRoot, files };
270
+ }
271
+
272
+ /**
273
+ * A searchable folder. `search()` refreshes from disk first, so edits show up
274
+ * on the next request.
275
+ */
276
+ export class FolderIndex {
277
+ constructor(root) {
278
+ this.root = root;
279
+ this.files = new Map(); // rel -> {size, mtime, chunks: [{text, tf, len}]}
280
+ this.stats = null;
281
+ }
282
+
283
+ refresh() {
284
+ const { realRoot, files } = walk(this.root);
285
+ let changed = false;
286
+ const keep = new Set();
287
+ for (const f of files) {
288
+ keep.add(f.rel);
289
+ const old = this.files.get(f.rel);
290
+ if (old && old.size === f.size && old.mtime === f.mtime) continue;
291
+ // Checked again right before reading: the file must still resolve inside.
292
+ let text;
293
+ try {
294
+ if (!inside(realRoot, realpathSync(f.abs))) continue;
295
+ text = readFileSync(f.abs, "utf8");
296
+ } catch {
297
+ continue;
298
+ }
299
+ const chunks = chunkFile(f.rel, text).map((t) => {
300
+ const toks = terms(t);
301
+ const tf = new Map();
302
+ for (const w of toks) tf.set(w, (tf.get(w) || 0) + 1);
303
+ return { text: t, tf, len: toks.length };
304
+ });
305
+ this.files.set(f.rel, { size: f.size, mtime: f.mtime, chunks });
306
+ changed = true;
307
+ }
308
+ for (const rel of [...this.files.keys()]) {
309
+ if (!keep.has(rel)) {
310
+ this.files.delete(rel);
311
+ changed = true;
312
+ }
313
+ }
314
+ if (changed || !this.stats) this.stats = this.computeStats();
315
+ }
316
+
317
+ computeStats() {
318
+ const df = new Map();
319
+ let n = 0;
320
+ let total = 0;
321
+ for (const f of this.files.values()) {
322
+ for (const c of f.chunks) {
323
+ n++;
324
+ total += c.len;
325
+ for (const w of c.tf.keys()) df.set(w, (df.get(w) || 0) + 1);
326
+ }
327
+ }
328
+ return { df, n, avg: n ? total / n : 0 };
329
+ }
330
+
331
+ /** The top `limit` chunks for `query`: [{file, snippet, score}]. */
332
+ search(query, limit = 5) {
333
+ this.refresh();
334
+ const wanted = [...new Set(terms(query))];
335
+ const { df, n, avg } = this.stats;
336
+ if (!wanted.length || !n) return [];
337
+ const scored = [];
338
+ for (const [rel, f] of this.files) {
339
+ for (const c of f.chunks) {
340
+ let score = 0;
341
+ for (const t of wanted) {
342
+ const tf = c.tf.get(t);
343
+ if (!tf) continue;
344
+ const d = df.get(t) || 0;
345
+ const idf = Math.log(1 + (n - d + 0.5) / (d + 0.5));
346
+ score += idf * ((tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * c.len) / (avg || 1))));
347
+ }
348
+ if (score > 0) scored.push({ file: rel, snippet: c.text, score });
349
+ }
350
+ }
351
+ scored.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));
352
+ return scored.slice(0, limit).map((r) => ({
353
+ file: r.file,
354
+ snippet: r.snippet.length > SNIPPET ? r.snippet.slice(0, SNIPPET - 3) + "..." : r.snippet,
355
+ score: Math.round(r.score * 1000) / 1000,
356
+ }));
357
+ }
358
+ }
359
+
360
+ /** Run a folder handler on one input. Returns {ok, output} or {ok: false, error}. */
361
+ export function runFolder(index, input) {
362
+ const query = typeof input?.query === "string" ? input.query.trim() : "";
363
+ if (!query) return { ok: false, error: "the input needs a query" };
364
+ const n = Number.isInteger(input.limit) ? input.limit : 5;
365
+ const limit = Math.min(10, Math.max(1, n));
366
+ try {
367
+ return { ok: true, output: { results: index.search(query, limit) } };
368
+ } catch (e) {
369
+ if (e?.code === "ENOENT") return { ok: false, error: "the folder isn't there any more" };
370
+ return { ok: false, error: `couldn't search the folder: ${e?.code || e?.message || "unknown error"}` };
371
+ }
372
+ }
@@ -0,0 +1,107 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { serveDir } from "./config.js";
4
+
5
+ /**
6
+ * `oalo serve install`: a launchd LaunchAgent (macOS) or a systemd user unit
7
+ * (Linux) that runs `oalo serve --machine <name>` at login and restarts it if
8
+ * it stops. It only writes the file and prints the command that loads it; it
9
+ * never runs launchctl or systemctl itself.
10
+ *
11
+ * The unit runs node and this CLI's own entry file by absolute path, because a
12
+ * service starts with a bare PATH where `oalo` and `node` may not be found.
13
+ * PATH is copied in, so a command handler finds python3 and friends as it
14
+ * does in a terminal.
15
+ */
16
+
17
+ const xml = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
18
+
19
+ /** One systemd ExecStart word: quoted when it needs it, % doubled. */
20
+ export function systemdWord(s) {
21
+ const t = String(s).replace(/%/g, "%%");
22
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(t) ? t : `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
23
+ }
24
+
25
+ /**
26
+ * The unit for this platform: {path, content, load, reload, log?, logs?, note?}
27
+ * or {error}. `load` starts a new one; `reload` replaces one already loaded.
28
+ * `program` is [node, entry file]; `env` is copied for PATH and OALO_HOME.
29
+ */
30
+ export function unitFor(machine, { platform = process.platform, home = homedir(), program, env = process.env } = {}) {
31
+ const args = [...program, "serve", "--machine", machine];
32
+ const log = join(serveDir(), `${machine}.log`);
33
+ const vars = { PATH: env.PATH || "/usr/bin:/bin:/usr/sbin:/sbin" };
34
+ if (env.OALO_HOME) vars.OALO_HOME = env.OALO_HOME;
35
+
36
+ if (platform === "darwin") {
37
+ const label = `ai.oalo.serve.${machine}`;
38
+ const path = join(home, "Library", "LaunchAgents", `${label}.plist`);
39
+ const content = [
40
+ `<?xml version="1.0" encoding="UTF-8"?>`,
41
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
42
+ `<plist version="1.0">`,
43
+ `<dict>`,
44
+ ` <key>Label</key>`,
45
+ ` <string>${xml(label)}</string>`,
46
+ ` <key>ProgramArguments</key>`,
47
+ ` <array>`,
48
+ ...args.map((a) => ` <string>${xml(a)}</string>`),
49
+ ` </array>`,
50
+ ` <key>EnvironmentVariables</key>`,
51
+ ` <dict>`,
52
+ ...Object.entries(vars).flatMap(([k, v]) => [` <key>${xml(k)}</key>`, ` <string>${xml(v)}</string>`]),
53
+ ` </dict>`,
54
+ ` <key>RunAtLoad</key>`,
55
+ ` <true/>`,
56
+ ` <key>KeepAlive</key>`,
57
+ ` <true/>`,
58
+ ` <key>ThrottleInterval</key>`,
59
+ ` <integer>10</integer>`,
60
+ ` <key>StandardOutPath</key>`,
61
+ ` <string>${xml(log)}</string>`,
62
+ ` <key>StandardErrorPath</key>`,
63
+ ` <string>${xml(log)}</string>`,
64
+ `</dict>`,
65
+ `</plist>`,
66
+ ``,
67
+ ].join("\n");
68
+ return { path, content, log, load: `launchctl load -w ${shellWord(path)}`, reload: `launchctl unload ${shellWord(path)} && launchctl load -w ${shellWord(path)}` };
69
+ }
70
+
71
+ if (platform === "linux") {
72
+ const unit = `oalo-serve-${machine}.service`;
73
+ const base = env.XDG_CONFIG_HOME || join(home, ".config");
74
+ const path = join(base, "systemd", "user", unit);
75
+ const content = [
76
+ `[Unit]`,
77
+ `Description=Oalo machine ${machine} (oalo serve)`,
78
+ `After=network-online.target`,
79
+ `Wants=network-online.target`,
80
+ ``,
81
+ `[Service]`,
82
+ `ExecStart=${args.map(systemdWord).join(" ")}`,
83
+ ...Object.entries(vars).map(([k, v]) => `Environment=${systemdWord(`${k}=${v}`)}`),
84
+ `Restart=always`,
85
+ `RestartSec=5`,
86
+ ``,
87
+ `[Install]`,
88
+ `WantedBy=default.target`,
89
+ ``,
90
+ ].join("\n");
91
+ return {
92
+ path,
93
+ content,
94
+ load: `systemctl --user enable --now ${unit}`,
95
+ reload: `systemctl --user daemon-reload && systemctl --user restart ${unit}`,
96
+ note: "To keep it running when you're logged out, run once: loginctl enable-linger $USER",
97
+ logs: `journalctl --user -u ${unit} -f`,
98
+ };
99
+ }
100
+
101
+ return { error: "oalo serve install works on macOS and Linux. On this computer, keep `oalo serve` running in a terminal, or start it with your own service manager." };
102
+ }
103
+
104
+ /** A path as one shell word, quoted only when it needs it. */
105
+ export function shellWord(s) {
106
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${String(s).replace(/'/g, `'\\''`)}'`;
107
+ }