@oalo-ai/cli 0.4.4 → 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,368 @@
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([".md", ".markdown", ".txt", ".csv", ".tsv", ".json", ".html", ".htm"]);
20
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
21
+ const MAX_FILES = 20000;
22
+ const CHUNK = 800;
23
+ const SNIPPET = 1500;
24
+ const K1 = 1.2;
25
+ const B = 0.75;
26
+
27
+ /** Lowercase, accents off, split on anything that isn't a letter or digit. */
28
+ export function tokenize(text) {
29
+ return String(text)
30
+ .normalize("NFD")
31
+ .replace(/\p{M}+/gu, "")
32
+ .toLowerCase()
33
+ .split(/[^\p{L}\p{N}]+/u)
34
+ .filter((t) => t.length > 1 || /\d/.test(t));
35
+ }
36
+
37
+ /**
38
+ * A light ending trim for English and Spanish, so a search for "return policy"
39
+ * finds "Returns", "returned" finds "return", and "devolucion" finds
40
+ * "Devoluciones". Deliberately small: it only has to make the same word meet
41
+ * itself, not be a real stemmer. Runs on tokenize() output (lowercase, no accents).
42
+ */
43
+ export function stem(t) {
44
+ if (t.length <= 3 || /\d/.test(t)) return t;
45
+ if (t.endsWith("ciones")) return t.slice(0, -6) + "cion";
46
+ if (t.endsWith("ies") && t.length > 4) return t.slice(0, -3) + "y";
47
+ if (t.endsWith("ing") && t.length > 5) return undouble(t.slice(0, -3));
48
+ if (t.endsWith("ed") && t.length > 4) return undouble(t.slice(0, -2));
49
+ if (t.endsWith("es") && t.length > 4 && /[nrldzj]/.test(t[t.length - 3])) return t.slice(0, -2);
50
+ if (t.endsWith("s") && !t.endsWith("ss") && !t.endsWith("us") && !t.endsWith("is")) return t.slice(0, -1);
51
+ return t;
52
+ }
53
+
54
+ // "shipp" (from "shipping") -> "ship", but "fall", "press" stay.
55
+ function undouble(t) {
56
+ return /([^aeiouls])\1$/.test(t) ? t.slice(0, -1) : t;
57
+ }
58
+
59
+ /** The search terms of a text: tokens with their endings trimmed. */
60
+ export function terms(text) {
61
+ return tokenize(text).map(stem);
62
+ }
63
+
64
+ /** Text out of HTML: scripts, styles and tags dropped, common entities decoded. */
65
+ export function htmlText(html) {
66
+ return String(html)
67
+ .replace(/<!--[\s\S]*?-->/g, " ")
68
+ .replace(/<(script|style|noscript|template)\b[\s\S]*?<\/\1\s*>/gi, " ")
69
+ .replace(/<\/?(p|div|br|li|tr|h[1-6]|section|article|header|footer|table|ul|ol|blockquote|pre)\b[^>]*>/gi, "\n\n")
70
+ .replace(/<[^>]+>/g, " ")
71
+ .replace(/&nbsp;/g, " ")
72
+ .replace(/&amp;/g, "&")
73
+ .replace(/&lt;/g, "<")
74
+ .replace(/&gt;/g, ">")
75
+ .replace(/&quot;/g, '"')
76
+ .replace(/&#39;|&apos;/g, "'")
77
+ .replace(/&#(\d+);/g, (_, n) => safeChar(Number(n)))
78
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => safeChar(parseInt(n, 16)))
79
+ .replace(/[ \t]+/g, " ")
80
+ .replace(/\n[ \t]+/g, "\n")
81
+ .replace(/\n{3,}/g, "\n\n");
82
+ }
83
+
84
+ function safeChar(n) {
85
+ try {
86
+ return String.fromCodePoint(n);
87
+ } catch {
88
+ return " ";
89
+ }
90
+ }
91
+
92
+ // Pack paragraphs into chunks of up to CHUNK characters; a longer paragraph
93
+ // is cut at sentence ends, then hard.
94
+ function pack(paragraphs, prefix = "") {
95
+ const out = [];
96
+ let cur = "";
97
+ const room = CHUNK - (prefix ? prefix.length + 1 : 0);
98
+ const flush = () => {
99
+ if (cur.trim()) out.push(prefix && !cur.startsWith(prefix) ? `${prefix}\n${cur.trim()}` : cur.trim());
100
+ cur = "";
101
+ };
102
+ for (const p of paragraphs) {
103
+ for (const piece of split(p, room)) {
104
+ if (cur && cur.length + piece.length + 2 > room) flush();
105
+ cur = cur ? `${cur}\n\n${piece}` : piece;
106
+ }
107
+ }
108
+ flush();
109
+ return out;
110
+ }
111
+
112
+ function split(text, max) {
113
+ const t = text.trim();
114
+ if (!t) return [];
115
+ if (t.length <= max) return [t];
116
+ const out = [];
117
+ let cur = "";
118
+ for (const s of t.split(/(?<=[.!?])\s+/)) {
119
+ if (s.length > max) {
120
+ if (cur) out.push(cur), (cur = "");
121
+ for (let i = 0; i < s.length; i += max) out.push(s.slice(i, i + max));
122
+ continue;
123
+ }
124
+ if (cur && cur.length + s.length + 1 > max) out.push(cur), (cur = "");
125
+ cur = cur ? `${cur} ${s}` : s;
126
+ }
127
+ if (cur) out.push(cur);
128
+ return out;
129
+ }
130
+
131
+ /** Markdown or plain text: split at headings, then paragraphs, each chunk led by its heading. */
132
+ export function chunkText(text) {
133
+ const sections = [];
134
+ let heading = "";
135
+ let body = [];
136
+ const close = () => {
137
+ if (heading || body.some((l) => l.trim())) sections.push({ heading, body: body.join("\n") });
138
+ body = [];
139
+ };
140
+ for (const line of String(text).replace(/\r\n?/g, "\n").split("\n")) {
141
+ if (/^#{1,6}\s+\S/.test(line)) {
142
+ close();
143
+ heading = line.trim();
144
+ } else {
145
+ body.push(line);
146
+ }
147
+ }
148
+ close();
149
+ const chunks = [];
150
+ for (const s of sections) {
151
+ const paras = s.body.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
152
+ if (!paras.length) {
153
+ if (s.heading) chunks.push(s.heading);
154
+ continue;
155
+ }
156
+ chunks.push(...pack(paras, s.heading));
157
+ }
158
+ return chunks;
159
+ }
160
+
161
+ /** CSV or TSV rows, quoted fields (with commas, tabs or newlines inside) kept whole. */
162
+ export function rows(text) {
163
+ const out = [];
164
+ let cur = "";
165
+ let quoted = false;
166
+ const t = String(text).replace(/^/, "").replace(/\r\n?/g, "\n");
167
+ for (let i = 0; i < t.length; i++) {
168
+ const c = t[i];
169
+ if (c === '"') {
170
+ if (quoted && t[i + 1] === '"') {
171
+ cur += '""';
172
+ i++;
173
+ continue;
174
+ }
175
+ quoted = !quoted;
176
+ cur += c;
177
+ } else if (c === "\n" && !quoted) {
178
+ if (cur.trim()) out.push(cur);
179
+ cur = "";
180
+ } else {
181
+ cur += c;
182
+ }
183
+ }
184
+ if (cur.trim()) out.push(cur);
185
+ return out;
186
+ }
187
+
188
+ /** One chunk per row, each led by the header line, so a row stands alone. */
189
+ export function chunkTable(text) {
190
+ const [header, ...body] = rows(text);
191
+ if (!header) return [];
192
+ if (!body.length) return [header];
193
+ return body.map((r) => `${header}\n${r}`);
194
+ }
195
+
196
+ /** A JSON file: a list gives one chunk per item; anything else is read as text. */
197
+ export function chunkJson(text) {
198
+ let data;
199
+ try {
200
+ data = JSON.parse(text);
201
+ } catch {
202
+ return chunkText(text);
203
+ }
204
+ if (Array.isArray(data)) return data.flatMap((item) => split(typeof item === "string" ? item : JSON.stringify(item), CHUNK * 2));
205
+ return chunkText(JSON.stringify(data, null, 1));
206
+ }
207
+
208
+ export function chunkFile(path, text) {
209
+ const ext = extname(path).toLowerCase();
210
+ if (ext === ".csv" || ext === ".tsv") return chunkTable(text);
211
+ if (ext === ".json") return chunkJson(text);
212
+ if (ext === ".html" || ext === ".htm") return chunkText(htmlText(text));
213
+ return chunkText(text);
214
+ }
215
+
216
+ function inside(root, real) {
217
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
218
+ }
219
+
220
+ /**
221
+ * Every readable file under `root` (its real path), as {abs, rel, size, mtime}.
222
+ * Symlinks count only when they resolve inside the folder; a folder reached
223
+ * twice (a link loop) is read once.
224
+ */
225
+ export function walk(root) {
226
+ const realRoot = realpathSync(root);
227
+ const files = [];
228
+ const seen = new Set([realRoot]);
229
+ const visit = (dir, relDir) => {
230
+ let entries;
231
+ try {
232
+ entries = readdirSync(dir, { withFileTypes: true });
233
+ } catch {
234
+ return;
235
+ }
236
+ entries.sort((a, b) => a.name.localeCompare(b.name));
237
+ for (const e of entries) {
238
+ if (files.length >= MAX_FILES) return;
239
+ if (e.name.startsWith(".") || e.name === "node_modules") continue;
240
+ const abs = join(dir, e.name);
241
+ const rel = relDir ? `${relDir}/${e.name}` : e.name;
242
+ let st;
243
+ let real = abs;
244
+ try {
245
+ if (e.isSymbolicLink() || lstatSync(abs).isSymbolicLink()) {
246
+ real = realpathSync(abs);
247
+ if (!inside(realRoot, real)) continue;
248
+ }
249
+ st = statSync(real);
250
+ } catch {
251
+ continue;
252
+ }
253
+ if (st.isDirectory()) {
254
+ if (seen.has(real)) continue;
255
+ seen.add(real);
256
+ visit(real, rel);
257
+ } else if (st.isFile()) {
258
+ if (!EXTENSIONS.has(extname(e.name).toLowerCase())) continue;
259
+ if (st.size > MAX_FILE_BYTES) continue;
260
+ files.push({ abs: real, rel, size: st.size, mtime: st.mtimeMs });
261
+ }
262
+ }
263
+ };
264
+ visit(realRoot, "");
265
+ return { realRoot, files };
266
+ }
267
+
268
+ /**
269
+ * A searchable folder. `search()` refreshes from disk first, so edits show up
270
+ * on the next request.
271
+ */
272
+ export class FolderIndex {
273
+ constructor(root) {
274
+ this.root = root;
275
+ this.files = new Map(); // rel -> {size, mtime, chunks: [{text, tf, len}]}
276
+ this.stats = null;
277
+ }
278
+
279
+ refresh() {
280
+ const { realRoot, files } = walk(this.root);
281
+ let changed = false;
282
+ const keep = new Set();
283
+ for (const f of files) {
284
+ keep.add(f.rel);
285
+ const old = this.files.get(f.rel);
286
+ if (old && old.size === f.size && old.mtime === f.mtime) continue;
287
+ // Checked again right before reading: the file must still resolve inside.
288
+ let text;
289
+ try {
290
+ if (!inside(realRoot, realpathSync(f.abs))) continue;
291
+ text = readFileSync(f.abs, "utf8");
292
+ } catch {
293
+ continue;
294
+ }
295
+ const chunks = chunkFile(f.rel, text).map((t) => {
296
+ const toks = terms(t);
297
+ const tf = new Map();
298
+ for (const w of toks) tf.set(w, (tf.get(w) || 0) + 1);
299
+ return { text: t, tf, len: toks.length };
300
+ });
301
+ this.files.set(f.rel, { size: f.size, mtime: f.mtime, chunks });
302
+ changed = true;
303
+ }
304
+ for (const rel of [...this.files.keys()]) {
305
+ if (!keep.has(rel)) {
306
+ this.files.delete(rel);
307
+ changed = true;
308
+ }
309
+ }
310
+ if (changed || !this.stats) this.stats = this.computeStats();
311
+ }
312
+
313
+ computeStats() {
314
+ const df = new Map();
315
+ let n = 0;
316
+ let total = 0;
317
+ for (const f of this.files.values()) {
318
+ for (const c of f.chunks) {
319
+ n++;
320
+ total += c.len;
321
+ for (const w of c.tf.keys()) df.set(w, (df.get(w) || 0) + 1);
322
+ }
323
+ }
324
+ return { df, n, avg: n ? total / n : 0 };
325
+ }
326
+
327
+ /** The top `limit` chunks for `query`: [{file, snippet, score}]. */
328
+ search(query, limit = 5) {
329
+ this.refresh();
330
+ const wanted = [...new Set(terms(query))];
331
+ const { df, n, avg } = this.stats;
332
+ if (!wanted.length || !n) return [];
333
+ const scored = [];
334
+ for (const [rel, f] of this.files) {
335
+ for (const c of f.chunks) {
336
+ let score = 0;
337
+ for (const t of wanted) {
338
+ const tf = c.tf.get(t);
339
+ if (!tf) continue;
340
+ const d = df.get(t) || 0;
341
+ const idf = Math.log(1 + (n - d + 0.5) / (d + 0.5));
342
+ score += idf * ((tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * c.len) / (avg || 1))));
343
+ }
344
+ if (score > 0) scored.push({ file: rel, snippet: c.text, score });
345
+ }
346
+ }
347
+ scored.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));
348
+ return scored.slice(0, limit).map((r) => ({
349
+ file: r.file,
350
+ snippet: r.snippet.length > SNIPPET ? r.snippet.slice(0, SNIPPET - 3) + "..." : r.snippet,
351
+ score: Math.round(r.score * 1000) / 1000,
352
+ }));
353
+ }
354
+ }
355
+
356
+ /** Run a folder handler on one input. Returns {ok, output} or {ok: false, error}. */
357
+ export function runFolder(index, input) {
358
+ const query = typeof input?.query === "string" ? input.query.trim() : "";
359
+ if (!query) return { ok: false, error: "the input needs a query" };
360
+ const n = Number.isInteger(input.limit) ? input.limit : 5;
361
+ const limit = Math.min(10, Math.max(1, n));
362
+ try {
363
+ return { ok: true, output: { results: index.search(query, limit) } };
364
+ } catch (e) {
365
+ if (e?.code === "ENOENT") return { ok: false, error: "the folder isn't there any more" };
366
+ return { ok: false, error: `couldn't search the folder: ${e?.code || e?.message || "unknown error"}` };
367
+ }
368
+ }
@@ -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
+ }