@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.
@@ -359,7 +359,7 @@ async function watch(flags, rest, cfg) {
359
359
  signal: ac.signal,
360
360
  onEvent: (event, d) => {
361
361
  if (event === "heartbeat") return;
362
- console.log(flags.json ? JSON.stringify({ event, data: d }) : `${event} ${JSON.stringify(d?.id ? { id: d.id, ...d.document } : d)}`);
362
+ console.log(flags.json ? JSON.stringify({ event, data: d }) : `${event} ${watchLine(d)}`);
363
363
  },
364
364
  });
365
365
  } catch (e) {
@@ -452,3 +452,11 @@ async function showRoutes(flags, cfg) {
452
452
  if (r.rate_limits_per_minute) console.log(dim(`\nlimits per minute: ${Object.entries(r.rate_limits_per_minute).map(([k, v]) => `${k} ${v}`).join(", ")}`));
453
453
  });
454
454
  }
455
+
456
+ /** One row of `oalo data watch`: the row's id and fields. Stream events from
457
+ * sources and bulk writes wrap the row as `{table, operation, row_id, data:
458
+ * row, ...}`, which printed as one long raw line (2026-11-18). */
459
+ export function watchLine(d) {
460
+ const row = d?.data && (d.data.document || d.data.id) ? d.data : d;
461
+ return JSON.stringify(row?.id ? { id: row.id, ...row.document } : row);
462
+ }
@@ -129,8 +129,12 @@ export async function deploy(flags) {
129
129
  // A new app: this project now deploys to it (as `oalo link --app` saves).
130
130
  if (result.created) {
131
131
  writeConfig({ ...(readConfig(root) || {}), serverUrl: url, appId: result.app, env: "dev" }, root);
132
- // As `oalo link` does: the link file stays out of the repo's commits.
133
- ensureGitignored(root);
132
+ // As `oalo link` does: the link file stays out of the repo's commits. Say
133
+ // so: the next `oalo deploy` refuses uncommitted changes, and this edit
134
+ // was one nobody saw (2026-11-18).
135
+ if (ensureGitignored(root)) {
136
+ console.log(dim("added .oalo/credentials* to .gitignore: commit it before your next `oalo deploy`."));
137
+ }
134
138
  if (result.app_type === "code_only") {
135
139
  // The server's progress line already said what to add.
136
140
  console.log(`created ${result.app} from ${result.commit.slice(0, 8)}, its history kept. Nothing runs yet (see above).`);
@@ -13,10 +13,12 @@ import {
13
13
  readGraphFile,
14
14
  writeGraphFile,
15
15
  removeFile,
16
+ pushWriteBack,
16
17
  listGraphFiles,
17
18
  expandTargets,
18
19
  locallyModified,
19
20
  standing,
21
+ rollbackHint,
20
22
  rel,
21
23
  cleanTrigger,
22
24
  triggerKey,
@@ -388,7 +390,21 @@ function saveParams(file, { force, strict }) {
388
390
  return { event: file.version == null ? "loops:create" : "loops:update", params };
389
391
  }
390
392
 
391
- async function pushOne(ch, path, file, flags) {
393
+ /**
394
+ * Write the server's copy after a save (see pushWriteBack): the pushed file,
395
+ * and the pulled copy under .oalo unless it has edits of its own. Returns the
396
+ * note to add to the push line.
397
+ */
398
+ function writeBack(path, savedPath, next) {
399
+ const { file: saved } = existsSync(savedPath) ? load(savedPath) : {};
400
+ const plan = pushWriteBack(path, savedPath, !!saved && locallyModified(saved));
401
+ for (const p of plan.write) writeGraphFile(p, next);
402
+ if (plan.remove) removeFile(plan.remove);
403
+ if (plan.kept) return `. ${rel(plan.kept)} has edits of its own, so it was left as it is (now behind v${next.version})`;
404
+ return plan.write.length > 1 ? `, ${rel(plan.write[1])} updated too` : "";
405
+ }
406
+
407
+ export async function pushOne(ch, path, file, flags) {
392
408
  const strict = flags["no-strict"] !== true;
393
409
 
394
410
  // Lint first, so the author sees every finding even when the save would
@@ -431,10 +447,7 @@ async function pushOne(ch, path, file, flags) {
431
447
 
432
448
  if (file.kind === "flow") {
433
449
  const next = flowFile(reply.flow, file.bot);
434
- const newPath = flowPath(file.bot, next.flow.name);
435
- writeGraphFile(newPath, next);
436
- if (resolvePath(newPath) !== resolvePath(path)) removeFile(path);
437
- return { ok: true, state: "pushed", note: `v${next.version}` };
450
+ return { ok: true, state: "pushed", note: `v${next.version}${writeBack(path, flowPath(file.bot, next.flow.name), next)}` };
438
451
  }
439
452
 
440
453
  const triggerNotes = Array.isArray(file.triggers) && !file.app_id ? await syncTriggers(ch, file) : { notes: [], failed: [] };
@@ -442,7 +455,7 @@ async function pushOne(ch, path, file, flags) {
442
455
  // Loop saves reply with a version only; read the stored copy back so the
443
456
  // file matches what the server normalised (legacy edge keys, stale entry).
444
457
  const remote = await getLoop(ch, file.name, file.app_id);
445
- if (remote) writeGraphFile(loopPath(file.name, file.app_id), loopFile(remote, await listTriggers(ch, file.name, file.app_id)));
458
+ const written = remote ? writeBack(path, loopPath(file.name, file.app_id), loopFile(remote, await listTriggers(ch, file.name, file.app_id))) : "";
446
459
  if (file.app_id) console.log(dim(" app-pinned loop: saved without the version guard or strict check"));
447
460
  for (const n of triggerNotes.notes) console.log(dim(` ${n}`));
448
461
  if (triggerNotes.failed.length) {
@@ -450,12 +463,16 @@ async function pushOne(ch, path, file, flags) {
450
463
  }
451
464
  // A new loop's first version is 0: say "created" rather than "v0".
452
465
  const created = file.version == null;
453
- return { ok: true, state: created ? "created" : "pushed", note: remote ? (created ? `v${remote.version}${remote.enabled === false ? `, off until \`oalo loops on ${file.name}\`` : ""}` : `v${remote.version}`) : "" };
466
+ return { ok: true, state: created ? "created" : "pushed", note: remote ? (created ? `v${remote.version}${remote.enabled === false ? `, off until \`oalo loops on ${file.name}\`` : ""}` : `v${remote.version}`) + written : "" };
454
467
  } catch (e) {
455
468
  if (e.code === "conflict") {
456
469
  // Save the server's copy beside the file, so the merge is a file diff
457
470
  // rather than a lost edit. It becomes the base for the next push.
458
471
  const current = await remoteOf(ch, file).catch(() => null);
472
+ // A rollback (an unchanged earlier pull) has nothing to merge: say so
473
+ // before writing a server copy beside it.
474
+ const rollback = rollbackHint(file, current?.version ?? e.reply?.current?.version, rel(path));
475
+ if (rollback) return { ok: false, state: "behind", note: rollback };
459
476
  const theirsPath = path.replace(/\.json$/, ".server.json");
460
477
  let theirs = null;
461
478
  if (current && file.kind === "tool") {
@@ -588,7 +605,10 @@ export async function push(flags, rest) {
588
605
  else failed++;
589
606
  }
590
607
 
591
- if (pushed + failed === 0) console.log("nothing to push: no file differs from what was pulled");
608
+ if (pushed + failed === 0) {
609
+ console.log("nothing to push: no file differs from what was pulled");
610
+ console.log(dim(" A file restored from git (an earlier version) counts as unchanged. To make it live again: oalo push <file> --force. `oalo status` shows files behind the server."));
611
+ }
592
612
  if (failed > 0) process.exitCode = 1;
593
613
  } catch (e) {
594
614
  console.error(`push failed: ${e.message}`);
@@ -4,19 +4,20 @@ import { fetchManifest, ApiError } from "../api.js";
4
4
  import { OaloChannel } from "../channel.js";
5
5
  import { installSkill, installedSkillVersion } from "./skill.js";
6
6
 
7
- export async function link(flags) {
8
- if (flags.status) return status(flags);
7
+ export async function link(flags, opts = {}) {
8
+ if (flags.status) return status(flags, opts);
9
9
 
10
10
  const serverUrl = (flags.server || process.env.OALO_URL || "").replace(/\/$/, "");
11
- // After `oalo login`, the workspace's saved data token is used, so linking a
12
- // project needs only --server.
13
- const token = flags.token || process.env.OALO_SYNC_TOKEN || (serverUrl && readToken({ serverUrl, appId: null }, "sync"));
11
+ // After `oalo login`, the workspace's saved data or CLI token is used, so
12
+ // linking a project needs only --server.
13
+ const token = flags.token || process.env.OALO_SYNC_TOKEN || (serverUrl && readToken({ serverUrl, appId: null }, "sync")) || null;
14
+ const cliToken = flags["cli-token"] || process.env.OALO_CLI_TOKEN || (serverUrl && readToken({ serverUrl, appId: null }, "cli")) || null;
14
15
 
15
- if (!serverUrl || !token) {
16
+ if (!serverUrl || (!token && !cliToken)) {
16
17
  console.error(
17
- "usage: oalo link --server https://<workspace>.oalo.ai [--token <sync token>] [--app <id>] [--env dev|prod]\n\n" +
18
+ "usage: oalo link --server https://<workspace>.oalo.ai [--token <sync token>] [--cli-token <cli token>] [--app <id>] [--env dev|prod]\n\n" +
18
19
  (serverUrl
19
- ? `No saved token for ${serverUrl}. Run \`oalo login --server ${serverUrl}\` first, or pass --token.`
20
+ ? `No saved token for ${serverUrl}. Run \`oalo login --server ${serverUrl}\` first, or pass --token / --cli-token.`
20
21
  : "Run `oalo login --server <url>` first, or create a connection in the dashboard under\nAccount -> CLI & agents and run the oalo link command it shows."),
21
22
  );
22
23
  process.exitCode = 2;
@@ -31,38 +32,38 @@ export async function link(flags) {
31
32
  }
32
33
 
33
34
  const config = { serverUrl: serverUrl.replace(/\/$/, ""), appId: flags.app || null, env };
35
+ const doManifest = opts.fetchManifest || fetchManifest;
36
+ const makeChannel = opts.channel || ((o) => new OaloChannel(o));
34
37
 
35
38
  // Verify BEFORE saving anything. A link that reports success and then 403s on
36
39
  // first real use is the worst outcome: the developer has no reason to suspect
37
40
  // the credential and goes looking for the bug in their own code.
38
- let manifest;
39
- try {
40
- manifest = await fetchManifest({ ...config, token });
41
- } catch (e) {
42
- console.error(`link failed: ${e.message}`);
43
- if (e instanceof ApiError && e.status === 403) {
44
- console.error("\nThe token was accepted but lacks read scope. Mint one with read access.");
45
- }
46
- if (e instanceof ApiError && e.status === 401) {
47
- console.error("\nThe token was rejected. It may be revoked, expired, or for another workspace.");
41
+ let manifest = null;
42
+ if (token) {
43
+ try {
44
+ manifest = await doManifest({ ...config, token });
45
+ } catch (e) {
46
+ console.error(`link failed: ${e.message}`);
47
+ if (e instanceof ApiError && e.status === 403) {
48
+ console.error("\nThe token was accepted but lacks read scope. Mint one with read access.");
49
+ }
50
+ if (e instanceof ApiError && e.status === 401) {
51
+ console.error("\nThe token was rejected. It may be revoked, expired, or for another workspace.");
52
+ }
53
+ process.exitCode = 1;
54
+ return;
48
55
  }
49
- process.exitCode = 1;
50
- return;
51
56
  }
52
57
 
53
- const models = Object.keys(manifest?.models || {});
58
+ const models = manifest ? Object.keys(manifest?.models || {}) : null;
54
59
  config.schemaVersion = manifest?.schema_version ?? null;
55
60
 
56
- // A CLI token is optional and a DIFFERENT kind (control plane, for `oalo
57
- // mcp`). Verify it the same way rather than storing it hopefully: with two
58
- // token kinds in play, pasting one where the other belongs is now the most
59
- // likely mistake, and it should be caught here rather than surfacing later as
60
- // a confusing channel auth failure.
61
- const cliToken = flags["cli-token"] || null;
61
+ // Verify CLI token when explicitly passed, or when linking without a sync token.
62
+ const verifyCli = Boolean(cliToken && (flags["cli-token"] || !token));
62
63
  let cliOk = null;
63
64
 
64
- if (cliToken) {
65
- const ch = new OaloChannel({ url: config.serverUrl, token: cliToken, timeoutMs: 15000 });
65
+ if (verifyCli) {
66
+ const ch = makeChannel({ url: config.serverUrl, token: cliToken, timeoutMs: 15000 });
66
67
  try {
67
68
  await ch.connect();
68
69
  cliOk = true;
@@ -84,16 +85,21 @@ export async function link(flags) {
84
85
  }
85
86
 
86
87
  writeConfig(config);
87
- const credPath = writeToken(config, token, "sync");
88
- if (cliToken) writeToken(config, cliToken, "cli");
88
+ let credPath = credentialsPath();
89
+ if (token) credPath = writeToken(config, token, "sync");
90
+ if (cliToken) credPath = writeToken(config, cliToken, "cli");
89
91
  const addedRule = ensureGitignored();
90
92
 
91
93
  console.log(`linked to ${config.serverUrl}`);
92
94
  console.log(` env ${config.env}`);
93
95
  if (config.appId) console.log(` app ${config.appId}`);
94
- console.log(` schema version ${config.schemaVersion}`);
95
- console.log(` models visible ${models.length}`);
96
- if (cliToken) console.log(` cli token verified (oalo mcp is ready)`);
96
+ if (manifest) {
97
+ console.log(` schema version ${config.schemaVersion}`);
98
+ console.log(` models visible ${models.length}`);
99
+ } else {
100
+ console.log(` sync token none (control-plane only; oalo pull, bots, deploy, and mcp are ready)`);
101
+ }
102
+ if (cliOk) console.log(` cli token verified (oalo mcp is ready)`);
97
103
  console.log(`\n config .oalo/config.json (safe to commit)`);
98
104
  console.log(` token ${credPath} (never committed)`);
99
105
  if (addedRule) console.log(`\n added .oalo/credentials* to .gitignore`);
@@ -111,11 +117,13 @@ export async function link(flags) {
111
117
  }
112
118
  // A Flutter app from Oalo's template takes Dart, not TypeScript.
113
119
  const flutter = existsSync("pubspec.yaml") && /^\s*flutter:/m.test(readFileSync("pubspec.yaml", "utf8"));
114
- console.log(flutter ? `\nNext: oalo typegen --dart` : `\nNext: oalo typegen`);
120
+ console.log(!token ? `\nNext: oalo pull` : flutter ? `\nNext: oalo typegen --dart` : `\nNext: oalo typegen`);
115
121
  }
116
122
 
117
- async function status(flags) {
123
+ async function status(flags, opts = {}) {
118
124
  const cfg = resolve(flags);
125
+ const doManifest = opts.fetchManifest || fetchManifest;
126
+ const makeChannel = opts.channel || ((o) => new OaloChannel(o));
119
127
 
120
128
  if (!cfg.serverUrl) {
121
129
  console.log("not linked. run: oalo link --server <url> --token <token>");
@@ -128,25 +136,39 @@ async function status(flags) {
128
136
  if (cfg.configDir && cfg.configDir !== process.cwd()) console.log(`linked by ${cfg.configDir}/.oalo/config.json`);
129
137
  console.log(`env ${cfg.env}`);
130
138
  console.log(`app ${cfg.appId || "(none)"}`);
131
- console.log(`sync token ${cfg.token ? "present" : "MISSING"} (${credentialsPath()})`);
139
+ console.log(`sync token ${cfg.token ? "present" : "absent"} (${credentialsPath()})`);
132
140
  console.log(`cli token ${cfg.cliToken ? "present" : "absent (oalo mcp needs one)"}`);
133
141
 
134
- if (!cfg.token) {
142
+ if (!cfg.token && !cfg.cliToken) {
135
143
  process.exitCode = 1;
136
144
  return;
137
145
  }
138
146
 
139
- try {
140
- const m = await fetchManifest(cfg);
141
- const models = Object.keys(m?.models || {}).length;
142
- console.log(`reachable yes, schema version ${m?.schema_version}, ${models} models`);
143
- if (cfg.schemaVersion != null && m?.schema_version !== cfg.schemaVersion) {
144
- console.log(
145
- `\nschema moved since link (${cfg.schemaVersion} -> ${m.schema_version}). re-run oalo typegen.`,
146
- );
147
+ if (cfg.token) {
148
+ try {
149
+ const m = await doManifest(cfg);
150
+ const models = Object.keys(m?.models || {}).length;
151
+ console.log(`reachable yes, schema version ${m?.schema_version}, ${models} models`);
152
+ if (cfg.schemaVersion != null && m?.schema_version !== cfg.schemaVersion) {
153
+ console.log(
154
+ `\nschema moved since link (${cfg.schemaVersion} -> ${m.schema_version}). re-run oalo typegen.`,
155
+ );
156
+ }
157
+ } catch (e) {
158
+ console.log(`reachable NO: ${e.message}`);
159
+ process.exitCode = 1;
147
160
  }
161
+ return;
162
+ }
163
+
164
+ const ch = makeChannel({ url: cfg.serverUrl, token: cfg.cliToken, timeoutMs: 15000 });
165
+ try {
166
+ await ch.connect();
167
+ console.log("reachable yes (control plane via CLI token)");
148
168
  } catch (e) {
149
169
  console.log(`reachable NO: ${e.message}`);
150
170
  process.exitCode = 1;
171
+ } finally {
172
+ ch.close();
151
173
  }
152
174
  }
@@ -121,7 +121,7 @@ export async function login(flags, rest = []) {
121
121
 
122
122
  console.log(`\nConnected "${poll.json.name}" to ${serverUrl}.`);
123
123
  console.log(` credentials ${path} (not in any project)`);
124
- if (!poll.json.sync_token) console.log(" data token none: your access doesn't include the Sync API, so typegen and tail won't work");
124
+ if (!poll.json.sync_token) console.log(" data token none: your access doesn't include the Sync API, so typegen and data reads won't work");
125
125
  console.log("\nNext: oalo pull (or oalo link --server ... in a project, then oalo typegen)");
126
126
  return;
127
127
  }
@@ -0,0 +1,182 @@
1
+ import { OaloChannel } from "../channel.js";
2
+ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
3
+ import { requireFeature } from "../server.js";
4
+ import { dim } from "../events.js";
5
+ import { machineNameError, readMachine, writeMachine, localMachines } from "../serve/config.js";
6
+
7
+ /**
8
+ * `oalo machines`: the computers that answer this workspace's bots from their
9
+ * own data, through `oalo serve`.
10
+ *
11
+ * oalo machines list them, online or not
12
+ * oalo machines add <name> make this computer one; saves its key
13
+ * oalo machines revoke <name> --yes its key stops working
14
+ *
15
+ * `add` mints a node token and writes it straight into
16
+ * ~/.oalo/serve/<name>.json (mode 0600). It is never printed. A node token can
17
+ * only answer the box's requests for that machine; it can't read or change
18
+ * anything in the workspace.
19
+ */
20
+ export async function machines(flags, rest, opts = {}) {
21
+ const sub = rest[1] || "list";
22
+ const name = rest[2];
23
+ if (!["list", "add", "revoke", "allow"].includes(sub)) return fail(`unknown machines command: ${sub}\n\n${USAGE}`, 2);
24
+ if (sub === "add" || sub === "revoke") {
25
+ const bad = machineNameError(name);
26
+ if (bad) return fail(`${bad}\n\n${USAGE}`, 2);
27
+ }
28
+ if (sub === "allow" && (!name || !name.startsWith("byo-"))) {
29
+ return fail(`expected a model id like byo-<endpoint>/<model> (from \`oalo machines\`)\n\n${USAGE}`, 2);
30
+ }
31
+
32
+ if (sub === "add") {
33
+ let local;
34
+ try {
35
+ local = readMachine(name);
36
+ } catch (e) {
37
+ return fail(e.message, 1);
38
+ }
39
+ if (local?.token) return fail(`${name} is already set up on this computer (${pathOf(name)}). To start over, revoke it first: oalo machines revoke ${name} --yes`, 1);
40
+ }
41
+
42
+ if (sub === "revoke" && !flags.yes) {
43
+ return fail(
44
+ `This revokes ${name}'s key for good: oalo serve on it stops connecting, and the bot tools it serves stop answering. Run it again with --yes to go ahead.`,
45
+ 2,
46
+ );
47
+ }
48
+
49
+ const cfg = resolveConfig(flags);
50
+ const { url, token } = controlPlane(cfg);
51
+ if (!url || !token) return fail(`oalo machines needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
52
+
53
+ if (!opts.channel) {
54
+ try {
55
+ await requireFeature(url, "machines", "oalo machines");
56
+ } catch (e) {
57
+ return fail(e.message, 1);
58
+ }
59
+ }
60
+
61
+ const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
62
+ try {
63
+ await ch.connect();
64
+ if (sub === "list") return await list(ch, url, flags);
65
+ if (sub === "add") return await add(ch, url, name, flags);
66
+ if (sub === "allow") return await allowModel(ch, name, flags);
67
+ return await revoke(ch, url, name, flags);
68
+ } catch (e) {
69
+ if (e.code === "admin_only") return fail(`only a workspace admin can ${sub === "add" ? "add a machine" : sub === "allow" ? "override a model check" : "revoke a machine"}. Ask an admin to run it.`, 1);
70
+ return fail(e.message, 1);
71
+ } finally {
72
+ ch.close();
73
+ }
74
+ }
75
+
76
+ export const USAGE = [
77
+ "usage: oalo machines [--json]",
78
+ " oalo machines add <name>",
79
+ " oalo machines revoke <name> --yes",
80
+ " oalo machines allow <byo-endpoint/model> [--off]",
81
+ ].join("\n");
82
+
83
+ const pathOf = (name) => `~/.oalo/serve/${name}.json`;
84
+
85
+ // Machines whose config on this computer points at this workspace.
86
+ function hereFor(url) {
87
+ const out = new Set();
88
+ for (const n of localMachines()) {
89
+ try {
90
+ const m = readMachine(n);
91
+ if (m?.url === url) out.add(n);
92
+ } catch {
93
+ /* a broken file isn't this command's problem */
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+
99
+ async function list(ch, url, flags) {
100
+ const { machines: all = [] } = await ch.call("machines:list", {});
101
+ if (flags.json) return void console.log(JSON.stringify(all, null, 2));
102
+ if (!all.length) return void console.log(`no machines in ${url} yet. Make this computer one: oalo machines add <name>`);
103
+ const here = hereFor(url);
104
+ const w = Math.max(...all.map((m) => m.name.length));
105
+ for (const m of all) {
106
+ const status = m.online ? "online " : "offline";
107
+ const seen = !m.online && m.last_seen_at ? `last seen ${String(m.last_seen_at).slice(0, 16).replace("T", " ")}` : m.online ? "" : "never connected";
108
+ const handlers = (m.handlers || []).map((h) => h.name);
109
+ const tail = [seen, handlers.length ? `handlers: ${handlers.join(", ")}` : "no handlers yet", here.has(m.name) ? "this computer" : ""].filter(Boolean).join(", ");
110
+ console.log(`${m.name.padEnd(w)} ${status} ${dim(tail)}`);
111
+ printModels(m.models || []);
112
+ }
113
+ }
114
+
115
+ // A machine's own models: the check's result, the real window, and the id a
116
+ // bot is set to (or why it can't be used yet).
117
+ function printModels(models) {
118
+ if (!models.length) return;
119
+ const w = Math.max(...models.map((x) => x.model.length));
120
+ for (const x of models) {
121
+ const win = x.window ? `window ${Number(x.window).toLocaleString("en-US")}` : "";
122
+ const tag = x.allow_unverified && x.check !== "passed" ? " (override)" : "";
123
+ const tail = x.serving ? `bots can use: ${x.model_id}${tag}` : x.check === "running" ? "check running" : x.why || "";
124
+ console.log(` ${x.handler} ${x.model.padEnd(w)} ${String(x.check).padEnd(11)} ${dim([win, tail].filter(Boolean).join(", "))}`);
125
+ }
126
+ }
127
+
128
+ async function allowModel(ch, modelId, flags) {
129
+ const allow = !flags.off;
130
+ const r = await ch.call("machines:model_override", { model_id: modelId, allow });
131
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
132
+ console.log(
133
+ allow
134
+ ? `${modelId}: allowed for bots and workflows (ModelCheck override on).`
135
+ : `${modelId}: ModelCheck override turned off (requires passing ModelCheck to serve).`,
136
+ );
137
+ }
138
+
139
+ async function add(ch, url, name, flags) {
140
+ const r = await ch.call("machines:add", { name });
141
+ const id = r?.machine?.id;
142
+ if (typeof r?.token !== "string" || !r.token || !id) return fail("the box didn't send back a machine key. Nothing was saved.", 1);
143
+ // A config left by a revoked key keeps its handlers.
144
+ let handlers = [];
145
+ try {
146
+ handlers = readMachine(name)?.handlers || [];
147
+ } catch {
148
+ handlers = [];
149
+ }
150
+ const path = writeMachine({ name, node_id: id, url, token: r.token, handlers });
151
+ if (flags.json) return void console.log(JSON.stringify({ machine: { id, name: r.machine.name || name }, config: path }, null, 2));
152
+ console.log(`added ${name}. Its key is saved in ${path} (only you can read it).`);
153
+ console.log(dim("The key can only answer your bots' questions. It can't read or change anything in your workspace."));
154
+ console.log("");
155
+ console.log("Next, share a folder or a script, then start serving:");
156
+ console.log(` oalo serve add folder handbook ~/Documents/Handbook --describe "Store policies, shipping and returns"`);
157
+ console.log(` oalo serve add command stock --input sku:string --describe "Stock and price for one product code" -- python3 ~/oalo/stock.py`);
158
+ console.log(` oalo serve`);
159
+ if (handlers.length) console.log(dim(`(kept the ${handlers.length} handler${handlers.length === 1 ? "" : "s"} already set up for ${name}: oalo serve list)`));
160
+ }
161
+
162
+ async function revoke(ch, url, name, flags) {
163
+ await ch.call("machines:revoke", { name });
164
+ // Drop the dead key from this computer's config; the handlers stay, so
165
+ // `oalo machines add <name>` sets it up again.
166
+ let local = null;
167
+ try {
168
+ local = readMachine(name);
169
+ } catch {
170
+ local = null;
171
+ }
172
+ const cleared = local?.token && local.url === url;
173
+ if (cleared) writeMachine({ ...local, token: null });
174
+ if (flags.json) return void console.log(JSON.stringify({ revoked: true, name, local_key_removed: !!cleared }, null, 2));
175
+ console.log(`revoked ${name}. Its key stops working now, and the bot tools it served stop answering.`);
176
+ if (cleared) console.log(dim(`Removed the key from ${pathOf(name)}. Its handlers are kept: oalo machines add ${name} sets it up again.`));
177
+ }
178
+
179
+ function fail(message, code) {
180
+ console.error(message);
181
+ process.exitCode = code;
182
+ }
@@ -40,8 +40,7 @@ export async function mcp(flags) {
40
40
 
41
41
  // Connect lazily: a client may list tools without calling one, and a
42
42
  // temporarily unreachable workspace should not stop the server from starting.
43
- let connected = null;
44
- const ensureConnected = () => (connected ||= oalo.connect());
43
+ const ensureConnected = createLazyConnector(oalo);
45
44
 
46
45
  const server = new Server({ name: "oalo", version: CLI_VERSION }, { capabilities: { tools: {} } });
47
46
 
@@ -106,3 +105,28 @@ export async function mcp(flags) {
106
105
  await server.connect(new StdioServerTransport());
107
106
  process.stderr.write(`oalo mcp: ready (${url})\n`);
108
107
  }
108
+
109
+ /**
110
+ * Lazy-connect helper for `oalo mcp`: caches the in-flight/resolved connect
111
+ * promise, and clears it + closes the failed socket on rejection so a transient
112
+ * outage never permanently wedges the MCP server.
113
+ */
114
+ export function createLazyConnector(channel) {
115
+ let connected = null;
116
+ return () => {
117
+ if (!connected) {
118
+ connected = Promise.resolve()
119
+ .then(() => channel.connect())
120
+ .catch((err) => {
121
+ connected = null;
122
+ try {
123
+ channel.close?.();
124
+ } catch {
125
+ /* already closed */
126
+ }
127
+ throw err;
128
+ });
129
+ }
130
+ return connected;
131
+ };
132
+ }
@@ -13,11 +13,10 @@ import { isInternal, NOISY, format, clock, dim } from "../events.js";
13
13
  * chat:bots:test_message {"bot_id", "text"} -> replies stream back
14
14
  *
15
15
  * NOTE `run loop` fires the loop DIRECTLY. It does not exercise the loop's
16
- * trigger binding, because triggers come from the event bus (a real form
17
- * submission, a real inbound message) which nothing exposes for simulation yet.
16
+ * trigger binding (use `oalo emit <event> --dry-run` to test trigger matching).
18
17
  * So this proves the loop's BODY works, not that its trigger is wired.
19
18
  */
20
- async function connect(flags) {
19
+ async function connect(flags, opts = {}) {
21
20
  const cfg = resolveConfig(flags);
22
21
  const { url, token } = controlPlane(cfg);
23
22
 
@@ -28,7 +27,8 @@ async function connect(flags) {
28
27
  return null;
29
28
  }
30
29
 
31
- return { ch: new OaloChannel({ url, token }), url, env: cfg.env };
30
+ const make = opts.channel || ((o) => new OaloChannel(o));
31
+ return { ch: make({ url, token }), url, env: cfg.env };
32
32
  }
33
33
 
34
34
  /** Stream events for `seconds`, or until `done` says we have seen enough. */
@@ -48,7 +48,7 @@ function watch(ch, { seconds, done }) {
48
48
  });
49
49
  }
50
50
 
51
- export async function run(flags, rest) {
51
+ export async function run(flags, rest, opts = {}) {
52
52
  const what = rest[1];
53
53
 
54
54
  if (!what || !["loop", "bot"].includes(what)) {
@@ -57,7 +57,7 @@ export async function run(flags, rest) {
57
57
  return;
58
58
  }
59
59
 
60
- const conn = await connect(flags);
60
+ const conn = await connect(flags, opts);
61
61
  if (!conn) {
62
62
  process.exitCode = 2;
63
63
  return;
@@ -156,11 +156,15 @@ export async function run(flags, rest) {
156
156
 
157
157
  // bot_id accepts an integer, a numeric string, or a public bot_ id — the
158
158
  // server normalises all three at the channel boundary.
159
- await ch.call("chat:bots:test_message", { bot_id: botId, text });
159
+ const reply = await ch.call("chat:bots:test_message", { bot_id: botId, text });
160
+ const convId = reply?.conversation_id ?? null;
160
161
  console.error(dim(`sent to ${botId}; watching for ${seconds}s; ctrl-c stops`));
161
162
  await watch(ch, {
162
163
  seconds,
163
- done: (event) => event === "response:done",
164
+ done: (event, p) => {
165
+ if (event !== "chat:msg:done") return false;
166
+ return convId == null || p?.conversation_id == null || p.conversation_id === convId;
167
+ },
164
168
  });
165
169
  } catch (e) {
166
170
  console.error(`run failed: ${e.message}`);