@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.
- package/README.md +20 -0
- package/man/oalo.1 +125 -5
- package/package.json +1 -1
- package/src/args.js +9 -1
- package/src/bot-settings.json +13 -0
- package/src/channel.js +1 -1
- package/src/commands/data.js +9 -1
- package/src/commands/deploy.js +6 -2
- package/src/commands/graphs.js +28 -8
- package/src/commands/machines.js +165 -0
- package/src/commands/serve.js +562 -0
- package/src/commands/switches.js +10 -0
- package/src/commands/tokens.js +14 -6
- package/src/commands/typegen.js +2 -1
- package/src/coord-release.json +9 -9
- package/src/events.js +9 -4
- package/src/graphfiles.js +44 -1
- package/src/help.js +66 -4
- package/src/index.js +8 -0
- package/src/serve/command.js +142 -0
- package/src/serve/config.js +215 -0
- package/src/serve/folder.js +368 -0
- package/src/serve/install.js +107 -0
- package/src/serve/model.js +363 -0
- package/src/serve/node.js +292 -0
package/src/events.js
CHANGED
|
@@ -27,10 +27,15 @@ function format(event, payload) {
|
|
|
27
27
|
const p = payload && typeof payload === "object" ? payload : {};
|
|
28
28
|
|
|
29
29
|
if (event === "activity:event") {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
30
|
+
// A workflow run has no person behind it and its event carries only the
|
|
31
|
+
// run id: it printed "someone started" (2026-11-18).
|
|
32
|
+
const run = p.surface === "runs";
|
|
33
|
+
const who = p.actor?.username || p.actor?.user_id || (run ? "workflow" : "someone");
|
|
34
|
+
const object =
|
|
35
|
+
p.object_type || p.object_name
|
|
36
|
+
? [p.object_type, p.object_name && `"${p.object_name}"`]
|
|
37
|
+
: [run && p.object_id != null && `run #${p.object_id}`];
|
|
38
|
+
const what = [p.verb, ...object].filter(Boolean).join(" ");
|
|
34
39
|
return `${bold(who)} ${what || p.surface}${p.link ? dim(` ${p.link}`) : ""}`;
|
|
35
40
|
}
|
|
36
41
|
|
package/src/graphfiles.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, unlinkSync, statSync } from "node:fs";
|
|
3
|
-
import { join, dirname, relative } from "node:path";
|
|
3
|
+
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Flows and loops as files in the project, for `oalo pull` / `push` / `status`.
|
|
@@ -224,6 +224,16 @@ export function standing(file, remote) {
|
|
|
224
224
|
return "clean";
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
+
/**
|
|
228
|
+
* A file that is exactly an older pulled version (restored from git, say) is
|
|
229
|
+
* a rollback, not someone else's edit: say how to make it live. Null when the
|
|
230
|
+
* file was edited, is new, or is not behind the server.
|
|
231
|
+
*/
|
|
232
|
+
export function rollbackHint(file, remoteVersion, relPath) {
|
|
233
|
+
if (file.version == null || locallyModified(file) || remoteVersion == null || remoteVersion === file.version) return null;
|
|
234
|
+
return `this file is v${file.version} as it was pulled, unchanged, and the server is at v${remoteVersion}. To make this earlier version live again (a rollback), run \`oalo push ${relPath} --force\`.`;
|
|
235
|
+
}
|
|
236
|
+
|
|
227
237
|
/**
|
|
228
238
|
* The smallest new file of each kind, for errors and help: a new loop or flow
|
|
229
239
|
* is often written from scratch, with no pulled file to copy.
|
|
@@ -265,6 +275,39 @@ export function removeFile(path) {
|
|
|
265
275
|
if (existsSync(path)) unlinkSync(path);
|
|
266
276
|
}
|
|
267
277
|
|
|
278
|
+
/**
|
|
279
|
+
* The file a flow push leaves stale, to remove: a pulled file under
|
|
280
|
+
* .oalo/flows whose flow is now saved at another path (it was renamed). A file
|
|
281
|
+
* pushed from anywhere else is the user's own copy and stays (demo sweep
|
|
282
|
+
* 2026-11-18: pushing a kept copy of a flow from a demos folder deleted it).
|
|
283
|
+
* Null when nothing is stale.
|
|
284
|
+
*/
|
|
285
|
+
export function staleAfterFlowPush(path, newPath, cwd = process.cwd()) {
|
|
286
|
+
const old = resolve(cwd, path);
|
|
287
|
+
if (old === resolve(cwd, newPath)) return null;
|
|
288
|
+
return old.startsWith(resolve(cwd, ROOT, "flows") + sep) ? old : null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Where a successful push writes the server's copy back. `path` is the file
|
|
293
|
+
* pushed, `savedPath` where pull keeps that flow or loop. The pushed file is
|
|
294
|
+
* always rewritten with the new version, so it is clean, not "behind its own
|
|
295
|
+
* push". When it lives elsewhere (a copy in a demos folder), the pulled copy at
|
|
296
|
+
* `savedPath` is refreshed too, unless it holds edits of its own
|
|
297
|
+
* (`savedEdited`): then it is kept, not overwritten (demo sweep 2026-11-18:
|
|
298
|
+
* pushing a kept copy of a loop wiped an unsaved edit in .oalo/loops).
|
|
299
|
+
* Returns {write: [paths], remove: path | null, kept: path | null}.
|
|
300
|
+
*/
|
|
301
|
+
export function pushWriteBack(path, savedPath, savedEdited, cwd = process.cwd()) {
|
|
302
|
+
const pushed = resolve(cwd, path);
|
|
303
|
+
const saved = resolve(cwd, savedPath);
|
|
304
|
+
if (pushed === saved) return { write: [saved], remove: null, kept: null };
|
|
305
|
+
if (savedEdited) return { write: [pushed], remove: null, kept: saved };
|
|
306
|
+
const stale = staleAfterFlowPush(pushed, saved, cwd);
|
|
307
|
+
if (stale) return { write: [saved], remove: stale, kept: null };
|
|
308
|
+
return { write: [pushed, saved], remove: null, kept: null };
|
|
309
|
+
}
|
|
310
|
+
|
|
268
311
|
// `<name>.server.json` is the server's copy saved by a conflicted push: a merge
|
|
269
312
|
// aid, not a file to push.
|
|
270
313
|
const isGraphFile = (f) => f.endsWith(".json") && !f.endsWith(".server.json");
|
package/src/help.js
CHANGED
|
@@ -19,7 +19,7 @@ export const TOKENS = [
|
|
|
19
19
|
kind: "cli",
|
|
20
20
|
where: "`oalo login`, or dashboard -> Account -> CLI & agents",
|
|
21
21
|
plane: "control (the build surface)",
|
|
22
|
-
usedBy: ["whoami", "tail", "call", "run", "emit", "data", "tokens", "docs", "apps", "deploy", "env", "logs", "secrets", "loops", "flows", "pull", "status", "lint", "push", "qa", "rehearse", "bots", "sources", "mcp"],
|
|
22
|
+
usedBy: ["whoami", "tail", "call", "run", "emit", "data", "tokens", "docs", "apps", "deploy", "env", "logs", "secrets", "loops", "flows", "pull", "status", "lint", "push", "qa", "rehearse", "bots", "sources", "machines", "mcp"],
|
|
23
23
|
warning: "Acts as you, with exactly your permissions. No read-only mode. Treat it like a password.",
|
|
24
24
|
},
|
|
25
25
|
];
|
|
@@ -561,6 +561,66 @@ export const COMMANDS = [
|
|
|
561
561
|
],
|
|
562
562
|
exits: { 0: "done", 1: "refused or failed", 2: "bad arguments or no CLI token" },
|
|
563
563
|
},
|
|
564
|
+
{
|
|
565
|
+
name: "machines",
|
|
566
|
+
summary: "The computers that answer your bots from their own data, through oalo serve: list, add, revoke.",
|
|
567
|
+
usage: ["oalo machines [--json]", "oalo machines add <name> [--json]", "oalo machines revoke <name> --yes [--json]"],
|
|
568
|
+
flags: [
|
|
569
|
+
{ flag: "add <name>", desc: "Make this computer a machine: lowercase letters, digits and hyphens, up to 40 (shop-pc). Saves its key to ~/.oalo/serve/<name>.json, mode 0600. The key is never printed. Admins only." },
|
|
570
|
+
{ flag: "revoke <name>", desc: "Its key stops working at once: oalo serve on it can't connect, and the bot tools it serves stop answering. Removes the key from this computer's config too, keeping its handlers." },
|
|
571
|
+
{ flag: "--yes", desc: "revoke: go ahead. Without it, revoke only says what it would do." },
|
|
572
|
+
{ flag: "--json", desc: "The machines, or what add and revoke did, as JSON." },
|
|
573
|
+
],
|
|
574
|
+
notes: [
|
|
575
|
+
"The list shows each machine online or offline, when it was last seen, the handlers it declared and which one is this computer. Under it, each model a model handler declared: its model check result (passed, failed, running or not checked), the window it really has, and the id a bot is set to (byo-mep_.../qwen3:14b) once it passes, or why it can't be used yet.",
|
|
576
|
+
"A machine's key (a node token, oalo_node_...) can only answer the box's requests for that machine. It can't read data or change anything in the workspace, so it is safe to leave on a shop computer. It is still a credential: the file is readable only by you.",
|
|
577
|
+
"Then add handlers and start serving: see `oalo help serve`. In the dashboard, a flow or loop's \"On your machine\" step lists each machine's handlers and whether it's online.",
|
|
578
|
+
],
|
|
579
|
+
exits: { 0: "done", 1: "refused or failed (only an admin can add or revoke)", 2: "bad arguments, revoke without --yes, or no CLI token" },
|
|
580
|
+
},
|
|
581
|
+
{
|
|
582
|
+
name: "serve",
|
|
583
|
+
summary: "Answer your bots from this computer: a folder or a script here answers the bot's tool calls, and the data never leaves it. A model server here (Ollama, vLLM) can run the bots too.",
|
|
584
|
+
usage: [
|
|
585
|
+
"oalo serve [--machine <name>]",
|
|
586
|
+
"oalo serve add folder <name> <path> --describe \"<what's in it>\"",
|
|
587
|
+
"oalo serve add command <name> --describe \"<what it answers>\" [--input 'sku:string,qty:integer?'] [--timeout <seconds>] -- <program> [args...]",
|
|
588
|
+
"oalo serve add model <name> [--base-url <url>] [--server ollama|vllm|openai] [--models <id1,id2>] [--key-env <VAR>] [--context <tokens>] [--output <tokens>] [--describe \"...\"]",
|
|
589
|
+
"oalo serve remove <name>",
|
|
590
|
+
"oalo serve list [--json]",
|
|
591
|
+
"oalo serve test <name> '<json input>'",
|
|
592
|
+
"oalo serve install [--dry-run]",
|
|
593
|
+
],
|
|
594
|
+
flags: [
|
|
595
|
+
{ flag: "--machine <name>", desc: "Which machine, when this computer has more than one (`oalo machines add` made them). Every subcommand takes it." },
|
|
596
|
+
{ flag: "--describe <text>", desc: "add: what the handler holds or answers. The bot reads it when deciding to call the tool, so be specific: \"Store policies, shipping and returns\"." },
|
|
597
|
+
{ flag: "--input <fields>", desc: "add command: the fields the bot sends, name:type, comma-separated: --input 'sku:string,qty:integer?'. Types string, integer, number, boolean; a ? makes a field optional (keep the quotes, or zsh reads the ? as a file pattern). Left out, the tool takes no input." },
|
|
598
|
+
{ flag: "--timeout <seconds>", desc: "add command: how long the program may run, 1 to 120. Default 30. Then it's stopped (SIGTERM, then SIGKILL 2 s later) and the bot sees a timeout." },
|
|
599
|
+
{ flag: "-- <program> [args...]", desc: "add command: the program to run and its arguments, after a bare --. Run directly, never through a shell, from the folder you ran add in." },
|
|
600
|
+
{ flag: "--base-url <url>", desc: "add model: the model server's OpenAI-style API root, http or https. Default Ollama's http://127.0.0.1:11434/v1. Every model call goes to <url>/chat/completions and nowhere else. A warning if it isn't this computer or a private network address." },
|
|
601
|
+
{ flag: "--server <kind>", desc: "add model: ollama, vllm or openai (any other OpenAI-compatible server, like LM Studio). Left out: ollama on port 11434, vllm when its model list says so, else openai. It decides how thinking is turned off." },
|
|
602
|
+
{ flag: "--models <ids>", desc: "add model: which of the server's models to declare, comma-separated, up to 32 (qwen3:14b,llama3.2:3b). Left out: all its chat models." },
|
|
603
|
+
{ flag: "--key-env <name>", desc: "add model: the NAME of an environment variable holding the model server's key, sent as Authorization: Bearer. The key isn't saved, printed or sent to the workspace; set the variable where oalo serve runs." },
|
|
604
|
+
{ flag: "--context <tokens>", desc: "add model: the context window to declare for every model. Left out: Ollama's num_ctx if the model sets one, else the model's maximum; vLLM's max_model_len." },
|
|
605
|
+
{ flag: "--output <tokens>", desc: "add model: the most tokens a reply may take, for every model. Default the smaller of 8192 and a quarter of the context." },
|
|
606
|
+
{ flag: "--dry-run", desc: "install: print the service file and the command to load it; write nothing." },
|
|
607
|
+
{ flag: "--json", desc: "list: the machine's handlers as JSON." },
|
|
608
|
+
],
|
|
609
|
+
notes: [
|
|
610
|
+
"Start with `oalo machines add <name>`, which saves this computer's key (step by step: `oalo docs answer-from-your-own-data`). Handlers live in that machine's config, ~/.oalo/serve/<name>.json, never in a project. OALO_HOME moves it.",
|
|
611
|
+
"oalo serve connects out to your workspace and declares the handlers; nothing listens on this computer and no port is opened. Each handler becomes a workspace tool with the handler's name: give it to a bot with `oalo bots tools <bot> --add <handler>`. A name another tool already has is skipped, and oalo serve says so. A handler name is lowercase letters, digits and underscores, up to 48, starting with a letter.",
|
|
612
|
+
"It prints one line per request: the time, the handler, how long it took, ok or the error, and the sizes in and out. Never what was asked or answered, which can be customer data. If the connection drops it reconnects, waiting 1 s, then 2, 4, up to 30.",
|
|
613
|
+
"folder: keyword search over the folder's .md, .markdown, .txt, .csv, .tsv, .json, .html and .htm files. Hidden files and folders, node_modules, files over 2 MB and links that lead outside the folder are skipped; nothing outside it is read. Markdown is split by heading and paragraph, a CSV or TSV one row at a time with its header line. Accents don't matter: devolucion finds devolución. The bot sends {\"query\", \"limit\"} (limit 1 to 10, default 5) and gets back {\"results\": [{\"file\", \"snippet\", \"score\"}]}. Edits are picked up on the next request.",
|
|
614
|
+
"command: the program gets {\"input\": {...}, \"context\": {...}} on stdin and prints one JSON object on stdout, which is the answer. context has surface (chat, flow or loop), bot, conversation and member: the verified id of the person chatting, so a script can return only their own orders. A flow step adds the flow's name, a loop step the loop's name and the run's contact. Use it, never a name or id the person typed. A non-zero exit or output that isn't a JSON object is an error the bot sees, with the last line the program wrote to stderr. Its environment is yours minus every OALO_ variable.",
|
|
615
|
+
"An answer is at most 64 KB; a bigger one is refused as \"output too large\". The answer goes into the bot's reply, so it passes through Oalo and the bot's model for that message. The folder or the program's data stays here.",
|
|
616
|
+
"test runs a handler here, with no connection, and prints exactly what the bot would get. Try every handler with it before a bot uses it.",
|
|
617
|
+
"install writes a launchd agent (macOS, ~/Library/LaunchAgents/ai.oalo.serve.<name>.plist) or a systemd user unit (Linux, ~/.config/systemd/user/oalo-serve-<name>.service) that runs oalo serve --machine <name> at login and restarts it if it stops, then prints the one command that starts it. It never runs launchctl or systemctl itself.",
|
|
618
|
+
"model: runs your bots on a model server on this computer or your network (Ollama, vLLM, LM Studio, anything OpenAI-compatible). It isn't a tool: the workspace sends a model id and a chat request, never an address, and this computer forwards it to the --base-url in its own config and streams the reply back. add reads the server's models (and, for Ollama, each model's window and whether it sees images); run it again with the same name to update them. Ollama serves a smaller window than a model's maximum unless OLLAMA_CONTEXT_LENGTH or num_ctx is raised, so add says so, and the workspace's model check finds the real one. test sends one message the way the workspace would, thinking off, and prints the reply, the time to the first token and tokens per second: oalo serve test <name> '{\"model\": \"qwen3:14b\", \"message\": \"Say hi in five words\"}'. Each model call is one line: the time, the handler, the model, how long, the first token, tokens in and out. Never the conversation. Before a bot can use a model, the workspace checks it through the same path a member's message takes: it must call a made-up lookup tool and answer from it (6 of 6), pick the right one of three tools, refuse to run commands or read files, never reply with nothing, find facts far back in a long conversation, and return a form's fields as JSON. A model that can't call tools fails, and so does one whose server really reads fewer than 8,192 tokens (raise OLLAMA_CONTEXT_LENGTH or num_ctx, then add the model again with --context so it's checked again). The check starts by itself when oalo serve first declares a model and takes a few minutes per model; `oalo machines` shows the result. Then set the bot to the model: oalo bots settings <bot> set provider=opencode model=<the id oalo machines shows>. If this computer is off when a bot needs the model, the member gets a short apology and the workspace an incident. The whole walkthrough: `oalo docs run-your-bot-on-your-own-model`.",
|
|
619
|
+
"After add or remove, restart oalo serve so the workspace sees the change.",
|
|
620
|
+
"Flows and loops can call a handler too, with a remote_step (\"On your machine\" in the editor). The step waits for the answer without holding anything open, and a step that started while this computer was off is sent when oalo serve connects. The handler's own --timeout still limits each run.",
|
|
621
|
+
],
|
|
622
|
+
exits: { 0: "done, or stopped with Ctrl-C", 1: "a handler failed its test, the key was revoked, or a write failed", 2: "bad arguments, no machine on this computer, or no handlers" },
|
|
623
|
+
},
|
|
564
624
|
{
|
|
565
625
|
name: "tokens",
|
|
566
626
|
summary: "List, create and revoke the workspace's sync tokens, for an app's own server.",
|
|
@@ -858,7 +918,8 @@ export const COMMANDS = [
|
|
|
858
918
|
"Without files, pushes every file edited since its pull (and new ones).",
|
|
859
919
|
"Each save sends the pulled version: if someone saved in between, the push is refused as a conflict and nothing is overwritten. Pull, merge, push again.",
|
|
860
920
|
"Saves are strict: error-level lint findings block them. Fix the findings (each says how) or pass --no-strict.",
|
|
861
|
-
"After a save the file is rewritten from the server's copy with the new version.",
|
|
921
|
+
"After a save the file is rewritten from the server's copy with the new version. A flow file pushed from outside .oalo/flows is kept as it is, and the saved copy goes to .oalo/flows/<bot>/<flow>.json.",
|
|
922
|
+
"Oalo keeps no older versions of a flow or loop. Keep the .oalo/ files in git to have them: to go back, restore the earlier file and run `oalo push <file> --force` (it still carries the version it was pulled at, so without --force it counts as unchanged).",
|
|
862
923
|
"Needs a CLI token.",
|
|
863
924
|
],
|
|
864
925
|
exits: { 0: "every file saved", 1: "a file was refused, in conflict, or failed", 2: "bad arguments or no token" },
|
|
@@ -897,8 +958,8 @@ export const COMMANDS = [
|
|
|
897
958
|
usage: ["oalo rehearse [--number <phone_number_id>] [--responder <bot_...>] [--timeout <s>] [--json]", "oalo rehearse --script <file.json>"],
|
|
898
959
|
flags: [
|
|
899
960
|
{ flag: "--number <id>", desc: "The WhatsApp number (phone_number_id) the customer writes to. Default: the workspace's default number." },
|
|
900
|
-
{ flag: "--responder <bot_...>", desc: "The bot the checks expect to end up answering, by its public id (`oalo bots` lists them). It's a check, not routing: messages still go where the number and its triage send them. To rehearse a bot that isn't on the number, give a --script scenario with an open_thread on that bot. Default: the bot an enabled triage loop hands threads to, else the number's bot." },
|
|
901
|
-
{ flag: "--script <file>", desc: 'A JSON file: {"scenarios": [{"name", "messages", "known_contact", "opted_out", "open_thread": {"bot_id", "number", "hours_ago", "tags", "assigned", "deal", "messages"}, "expect": {"reply", "bot_id", "assigned"}}]}. open_thread.bot_id is a public id (bot_...) or number. An open thread starts with one earlier exchange: open_thread.messages [customer, reply] when given, else a Spanish greeting ("Hola" / "¡Hola! ¿En qué te puedo ayudar?"), which can set the language the bot answers in.' },
|
|
961
|
+
{ flag: "--responder <bot_...>", desc: "The bot the checks expect to end up answering, by its public id (`oalo bots` lists them). It's a check, not routing: messages still go where the number and its triage send them. To rehearse a bot that isn't on the number, give a --script scenario with an open_thread on that bot. Default: the bot an enabled triage loop hands threads to, counting only loops that fire for a WhatsApp message on that number (their channel and bot filters allow it), else the number's bot." },
|
|
962
|
+
{ flag: "--script <file>", desc: 'A JSON file: {"scenarios": [{"name", "messages", "known_contact", "opted_out", "open_thread": {"bot_id", "number", "hours_ago", "tags", "assigned", "deal", "messages"}, "expect": {"reply", "bot_id", "assigned"}}]}. open_thread.bot_id is a public id (bot_...) or number. open_thread.number defaults to the number the scenario writes to. An open thread starts with one earlier exchange: open_thread.messages [customer, reply] when given, else a Spanish greeting ("Hola" / "¡Hola! ¿En qué te puedo ayudar?"), which can set the language the bot answers in.' },
|
|
902
963
|
{ flag: "--timeout <s>", desc: "How long one message may take to settle. Default 120, at most 300." },
|
|
903
964
|
{ flag: "--json", desc: "Print every scenario as JSON: turns (what was sent), threads, loop runs and their steps, checks, why_silent, cost_usd." },
|
|
904
965
|
],
|
|
@@ -933,6 +994,7 @@ export const COMMANDS = [
|
|
|
933
994
|
usage: ["oalo mcp"],
|
|
934
995
|
flags: [],
|
|
935
996
|
notes: [
|
|
997
|
+
"Add it to Claude Code from the linked project folder: `claude mcp add oalo -- oalo mcp` (or put {\"mcpServers\": {\"oalo\": {\"command\": \"oalo\", \"args\": [\"mcp\"]}}} in .mcp.json). Cursor: the same command and args in its MCP settings.",
|
|
936
998
|
"stdout is the MCP protocol stream. Diagnostics go to stderr.",
|
|
937
999
|
"Exposes a curated tool set plus an oalo_call passthrough; the build surface has ~442 events and mapping them all would wreck tool selection.",
|
|
938
1000
|
"oalo_describe is a short summary (apps, bots and loops by name, the tool groups, how dev and prod work, the docs index); its section argument pages through the full records. A reply longer than about 60,000 characters has its longest list cut, with a `_cut` note saying how to get the rest (oalo_call takes match and offset; oalo_node_catalog takes node_type).",
|
package/src/index.js
CHANGED
|
@@ -35,6 +35,8 @@ import { metrics, dashboards } from "./commands/metrics.js";
|
|
|
35
35
|
import { db } from "./commands/db.js";
|
|
36
36
|
import { migrate } from "./commands/migrate.js";
|
|
37
37
|
import { coordInstall, coordRun } from "./commands/coord-bin.js";
|
|
38
|
+
import { machines } from "./commands/machines.js";
|
|
39
|
+
import { serve } from "./commands/serve.js";
|
|
38
40
|
import { existsSync } from "node:fs";
|
|
39
41
|
import { overview, commandHelp, helpJson, COMMANDS } from "./help.js";
|
|
40
42
|
import { parse } from "./args.js";
|
|
@@ -158,6 +160,12 @@ async function dispatch(cmd) {
|
|
|
158
160
|
case "sources":
|
|
159
161
|
await sources(flags, rest);
|
|
160
162
|
break;
|
|
163
|
+
case "machines":
|
|
164
|
+
await machines(flags, rest);
|
|
165
|
+
break;
|
|
166
|
+
case "serve":
|
|
167
|
+
await serve(flags, rest);
|
|
168
|
+
break;
|
|
161
169
|
case "setup":
|
|
162
170
|
await setup(flags, rest);
|
|
163
171
|
break;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { MAX_OUTPUT_BYTES, clampTimeout } from "./config.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The `command` handler: run a local program, never through a shell. It gets
|
|
6
|
+
* {"input": ..., "context": ...} on stdin and prints one JSON object on
|
|
7
|
+
* stdout, which is the handler's output.
|
|
8
|
+
*
|
|
9
|
+
* The child's environment is this process's minus every OALO_ variable, so a
|
|
10
|
+
* script never sees the CLI's own settings. The node token isn't in the
|
|
11
|
+
* environment at all (it lives in the machine's config file), and it is never
|
|
12
|
+
* on a child's command line.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const KILL_AFTER_MS = 2000;
|
|
16
|
+
const STDERR_KEEP = 8192;
|
|
17
|
+
|
|
18
|
+
/** process.env without OALO_* (and with nothing else changed). */
|
|
19
|
+
export function childEnv(env = process.env) {
|
|
20
|
+
const out = {};
|
|
21
|
+
for (const [k, v] of Object.entries(env)) if (!k.startsWith("OALO_")) out[k] = v;
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The last non-empty stderr line, at most 300 characters. */
|
|
26
|
+
export function lastLine(text) {
|
|
27
|
+
const lines = String(text || "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
28
|
+
const l = lines[lines.length - 1] || "";
|
|
29
|
+
return l.length > 300 ? l.slice(0, 297) + "..." : l;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Run one request. `timeoutMs` is the handler's timeout, already cut to the
|
|
34
|
+
* request's deadline. Resolves {ok, output} or {ok: false, error}; never
|
|
35
|
+
* rejects.
|
|
36
|
+
*/
|
|
37
|
+
export function runCommand(handler, input, context, { timeoutMs, env = process.env } = {}) {
|
|
38
|
+
const argv = handler.command?.argv;
|
|
39
|
+
if (!Array.isArray(argv) || !argv.length || !argv.every((a) => typeof a === "string")) {
|
|
40
|
+
return Promise.resolve({ ok: false, error: "this handler has no command to run" });
|
|
41
|
+
}
|
|
42
|
+
const limit = clampTimeout(timeoutMs ?? handler.timeout_ms);
|
|
43
|
+
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
let done = false;
|
|
46
|
+
let timer = null;
|
|
47
|
+
let killer = null;
|
|
48
|
+
const finish = (r) => {
|
|
49
|
+
if (done) return;
|
|
50
|
+
done = true;
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
clearTimeout(killer);
|
|
53
|
+
resolve(r);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
let child;
|
|
57
|
+
const group = process.platform !== "win32";
|
|
58
|
+
try {
|
|
59
|
+
child = spawn(argv[0], argv.slice(1), {
|
|
60
|
+
cwd: handler.command.cwd || undefined,
|
|
61
|
+
env: childEnv(env),
|
|
62
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
63
|
+
shell: false,
|
|
64
|
+
detached: group,
|
|
65
|
+
windowsHide: true,
|
|
66
|
+
});
|
|
67
|
+
} catch (e) {
|
|
68
|
+
return finish({ ok: false, error: `couldn't start ${argv[0]}: ${e.code || e.message}` });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const out = [];
|
|
72
|
+
let outBytes = 0;
|
|
73
|
+
let tooBig = false;
|
|
74
|
+
let err = "";
|
|
75
|
+
let timedOut = false;
|
|
76
|
+
|
|
77
|
+
// The child leads its own process group, so a script's own children
|
|
78
|
+
// (a shell's sleep, say) stop with it.
|
|
79
|
+
const sendSignal = (sig) => {
|
|
80
|
+
try {
|
|
81
|
+
if (group) process.kill(-child.pid, sig);
|
|
82
|
+
else child.kill(sig);
|
|
83
|
+
} catch {
|
|
84
|
+
try { child.kill(sig); } catch { /* gone */ }
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const stop = () => {
|
|
88
|
+
if (killer) return;
|
|
89
|
+
sendSignal("SIGTERM");
|
|
90
|
+
killer = setTimeout(() => sendSignal("SIGKILL"), KILL_AFTER_MS);
|
|
91
|
+
killer.unref?.();
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
timer = setTimeout(() => {
|
|
95
|
+
timedOut = true;
|
|
96
|
+
stop();
|
|
97
|
+
}, limit);
|
|
98
|
+
|
|
99
|
+
child.stdout.on("data", (b) => {
|
|
100
|
+
if (tooBig) return;
|
|
101
|
+
outBytes += b.length;
|
|
102
|
+
if (outBytes > MAX_OUTPUT_BYTES) {
|
|
103
|
+
tooBig = true;
|
|
104
|
+
stop();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
out.push(b);
|
|
108
|
+
});
|
|
109
|
+
child.stderr.on("data", (b) => {
|
|
110
|
+
err = (err + b.toString("utf8")).slice(-STDERR_KEEP);
|
|
111
|
+
});
|
|
112
|
+
// A program that exits without reading stdin closes the pipe: not an error.
|
|
113
|
+
child.stdin.on("error", () => {});
|
|
114
|
+
|
|
115
|
+
child.on("error", (e) => {
|
|
116
|
+
const why = e.code === "ENOENT" ? "not found" : e.code === "EACCES" ? "not allowed to run it" : e.code || e.message;
|
|
117
|
+
finish({ ok: false, error: `couldn't start ${argv[0]}: ${why}` });
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
child.on("close", (code, signal) => {
|
|
121
|
+
const tail = lastLine(err);
|
|
122
|
+
const withTail = (msg) => (tail ? `${msg}: ${tail}` : msg);
|
|
123
|
+
if (timedOut) return finish({ ok: false, error: `timed out after ${limit >= 1000 ? `${Math.round(limit / 1000)}s` : `${limit} ms`}` });
|
|
124
|
+
if (tooBig) return finish({ ok: false, error: `output too large (over 64 KB, max 64 KB)` });
|
|
125
|
+
if (signal) return finish({ ok: false, error: withTail(`stopped by ${signal}`) });
|
|
126
|
+
if (code !== 0) return finish({ ok: false, error: withTail(`exited with code ${code}`) });
|
|
127
|
+
const text = Buffer.concat(out).toString("utf8").trim();
|
|
128
|
+
let output;
|
|
129
|
+
try {
|
|
130
|
+
output = JSON.parse(text);
|
|
131
|
+
} catch {
|
|
132
|
+
return finish({ ok: false, error: withTail(text ? "printed something that isn't JSON" : "printed nothing (it should print one JSON object)") });
|
|
133
|
+
}
|
|
134
|
+
if (!output || typeof output !== "object" || Array.isArray(output)) {
|
|
135
|
+
return finish({ ok: false, error: "printed JSON that isn't an object (wrap it: {\"results\": [...]})" });
|
|
136
|
+
}
|
|
137
|
+
finish({ ok: true, output });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
child.stdin.end(JSON.stringify({ input, context }) + "\n");
|
|
141
|
+
});
|
|
142
|
+
}
|
|
@@ -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 = 120000;
|
|
32
|
+
export const MAX_OUTPUT_BYTES = 64 * 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
|
+
}
|