@oalo-ai/cli 0.4.0 → 0.4.2

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/man/oalo.1 CHANGED
@@ -1,4 +1,4 @@
1
- .TH OALO 1 "" "oalo 0.3.0" "OALO CLI"
1
+ .TH OALO 1 "" "oalo 0.4.2" "OALO CLI"
2
2
  .SH NAME
3
3
  oalo \- wire a local app into your Oalo workspace
4
4
  .SH SYNOPSIS
@@ -368,8 +368,12 @@ Each one says what was seen: which process, how many restarts, a memory kill wit
368
368
  .PP
369
369
  Exit codes: 0 no open incident; 1 an incident is open, or the request failed; 2 bad arguments or no CLI token.
370
370
  .SS db
371
- All of an env's data as plain SQL (every app's own tables and the Oalo models), to keep a copy or take it anywhere. Or load an existing Postgres database into an env.
371
+ Read an env's tables with SQL (your app's own included), dump all of an env's data as plain SQL to keep or take anywhere, or load an existing Postgres database into an env.
372
372
  .PP
373
+ \fBoalo db query "<sql>" [\-\-env dev|prod] [\-\-limit <n>] [\-\-json]\fR
374
+ .br
375
+ \fBoalo db tables [\-\-env dev|prod]\fR
376
+ .br
373
377
  \fBoalo db dump [\-\-env dev|prod] [\-\-out <file.sql>] [\-\-force]\fR
374
378
  .br
375
379
  \fBoalo db restore <file> \-\-env dev|prod [\-\-schema <name>] [\-\-check] [\-\-yes]\fR
@@ -378,7 +382,13 @@ All of an env's data as plain SQL (every app's own tables and the Oalo models),
378
382
  .br
379
383
  .TP
380
384
  \fB\-\-env dev|prod\fR
381
- dump: which env's data. Default prod. restore: which env the data goes into, always on the command line.
385
+ query, tables: which env. Default the project's (dev). dump: which env's data. Default prod. restore: which env the data goes into, always on the command line.
386
+ .TP
387
+ \fB\-\-limit <n>\fR
388
+ query: rows to show. Default 100, at most 1000.
389
+ .TP
390
+ \fB\-\-json\fR
391
+ query: {columns, rows, truncated} as JSON.
382
392
  .TP
383
393
  \fB\-\-out <file.sql>\fR
384
394
  Where to write it. Default <workspace>\-<env>\-<date>.sql here.
@@ -398,6 +408,8 @@ restore: do everything but the write, and report what would happen. Nothing is w
398
408
  \fB\-\-yes\fR
399
409
  restore: go ahead with prod without asking. Needed for prod when there's no terminal to ask at.
400
410
  .IP \(bu 2
411
+ query reads only: one statement (SELECT, WITH, TABLE, VALUES, EXPLAIN or SHOW), run as your app's database login in a read\-only transaction that is rolled back, with a 10 second limit. It sees what your app sees at DATABASE_URL: the env's tables, not the platform's. \fBoalo data\fR is for Oalo models; this is for any table, your app's own included.
412
+ .IP \(bu 2
401
413
  Workspace admins only: it holds every member's data. Restore it into any Postgres with psql \-f.
402
414
  .IP \(bu 2
403
415
  Your code is in git (oalo deploy \-\-pull); this is the data. Together they are everything you need to run your apps elsewhere.
@@ -1150,8 +1162,10 @@ Admins and members with Developer access only: an app can print secrets or custo
1150
1162
  .PP
1151
1163
  Exit codes: 0 done; 1 refused or failed; 2 bad arguments or no CLI token.
1152
1164
  .SS loops
1153
- Test a loop (sends simulated), see its past runs, turn it on or off, or delete it, without pulling and pushing it.
1165
+ List the loops, test one (sends simulated), see its past runs, turn it on or off, or delete it, without pulling and pushing it.
1154
1166
  .PP
1167
+ \fBoalo loops list [\-\-json]\fR
1168
+ .br
1155
1169
  \fBoalo loops test <name> [\-\-sample latest|example] [\-\-input <json|@file.json>] [\-\-json]\fR
1156
1170
  .br
1157
1171
  \fBoalo loops on <name>\fR
@@ -1169,7 +1183,7 @@ Test a loop (sends simulated), see its past runs, turn it on or off, or delete i
1169
1183
  Test with the loop's most recent real event, or one built from its trigger's fields.
1170
1184
  .TP
1171
1185
  \fB\-\-input <json|@file>\fR
1172
- Test with this input instead: an event envelope {type, contact_id, payload}, or what a scheduled loop's first step reads.
1186
+ Test with this input instead: an event envelope {type, contact_id, payload}; for a loop an app calls (an api trigger), {"type": "api", "payload": {<its input fields>}}; or what a scheduled loop's first step reads.
1173
1187
  .TP
1174
1188
  \fB\-\-app <slug>\fR
1175
1189
  Only for a loop pinned to one app: that app's slug (\fBoalo apps\fR) or id. Works with test, runs, on, off and delete.
@@ -1210,7 +1224,7 @@ Exit codes: 0 done; 1 refused or failed; 2 bad arguments or no CLI token.
1210
1224
  .SS pull
1211
1225
  Fetch chat flows, loops and code tools into .oalo/ as files you can edit.
1212
1226
  .PP
1213
- \fBoalo pull [flows|loops|tools] [\-\-bot <id>] [\-\-name <name>] [\-\-force]\fR
1227
+ \fBoalo pull [flows|loops|tools|catalog] [\-\-bot <id>] [\-\-name <name>] [\-\-force]\fR
1214
1228
  .br
1215
1229
  .TP
1216
1230
  \fB\-\-bot <id>\fR
@@ -1232,7 +1246,9 @@ Each file holds the editable object (\fBflow\fR or \fBloop\fR) plus the CLI's bo
1232
1246
  .IP \(bu 2
1233
1247
  A file you have edited is kept, not overwritten, unless you pass \-\-force.
1234
1248
  .IP \(bu 2
1235
- To create a flow or loop, write a file in the same shape without id or version, then push it.
1249
+ With no name, pull copies the whole workspace (every bot's flows, every loop) into .oalo/. In an app's repo, pull what you work on by name, and gitignore the rest. \fBoalo pull catalog\fR writes only the node catalogs.
1250
+ .IP \(bu 2
1251
+ To create a flow or loop, write a file in the same shape without id or version, then push it. A new loop: {"kind": "loop", "name": "<name>", "loop": {"entry", "nodes", "edges", ...}, "triggers": [...]}. A new flow: {"kind": "flow", "bot": "<bot_ id>", "flow": {"name", "graph", ...}}. Run oalo pull once first for the node contracts in .oalo/catalog/.
1236
1252
  .IP \(bu 2
1237
1253
  Needs a CLI token.
1238
1254
  .PP
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oalo-ai/cli",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Wire a local app into your OALO workspace: link a token, generate typed bindings, and serve the build surface over MCP.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,7 +17,8 @@ Don't guess a command, flag or endpoint: `oalo help <command>` has every flag,
17
17
  ## The loop
18
18
 
19
19
  ```sh
20
- oalo pull # flows, loops and code tools into .oalo/, plus the node catalogs
20
+ oalo pull # the whole workspace: flows, loops, code tools, node catalogs
21
+ oalo pull loops --name x # just one (in an app's repo, pull what you work on); `oalo pull catalog`: catalogs only
21
22
  # edit .oalo/flows/<bot>/<flow>.json, .oalo/loops/<loop>.json, .oalo/tools/<tool>.js
22
23
  oalo lint # check every changed file; nothing is saved
23
24
  oalo push # lint, then save with the version you pulled (strict)
@@ -25,6 +26,11 @@ oalo qa <bot> "hola" "..." --channel whatsapp # talk to the bot, read the tran
25
26
  oalo status # what changed locally and on the server
26
27
  ```
27
28
 
29
+ A new loop or flow is a file you write without `id` or `version`, then push.
30
+ A loop: `{"kind": "loop", "name": "<name>", "loop": {"entry", "nodes", "edges", ...}, "triggers": [...]}`.
31
+ A flow: `{"kind": "flow", "bot": "<bot_ id>", "flow": {"name", "graph", ...}}`. Run
32
+ `oalo pull` once first, for the node contracts in `.oalo/catalog/`.
33
+
28
34
  Over MCP the same steps are `oalo_node_catalog`, `oalo_get_flow` / `oalo_get_loop` /
29
35
  `oalo_get_tool_source`, `oalo_lint_flow` / `oalo_lint_loop`, `oalo_save_flow` /
30
36
  `oalo_save_loop` / `oalo_save_tool_source`, `oalo_test_conversation` and
@@ -167,6 +173,8 @@ oalo data push orders_mirror orders.csv --id-field order_no --dry-run # chec
167
173
  oalo data push orders_mirror orders.csv --id-field order_no # upsert into dev
168
174
  oalo data list orders_mirror --limit 5 # look at what landed
169
175
  oalo data promote orders_mirror # copy dev rows to prod, when the person wants it live
176
+ oalo db tables # every table in the env, your app's own included
177
+ oalo db query "select * from quotes order by id desc limit 5" # read any of them (read-only; MCP: oalo_db_query)
170
178
  oalo data routes # the Sync API's endpoints, scopes and limits
171
179
  ```
172
180
 
@@ -108,7 +108,7 @@ function usage(problem) {
108
108
  // A 403 on a read almost always means the token can't see that table.
109
109
  function explain(e) {
110
110
  if (e instanceof ApiError && e.status === 403) return `${e.message}. The saved data token can't do this; check \`oalo whoami\`, or ask an admin for access to this table.`;
111
- if (e instanceof ApiError && e.status === 404) return `${e.message}. Check the table name with \`oalo data models\`.`;
111
+ if (e instanceof ApiError && e.status === 404) return `${e.message}. \`oalo data\` reads Oalo models (\`oalo data models\` lists them). For a table your app made itself, use \`oalo db tables\` and \`oalo db query "select ..."\`.`;
112
112
  return e.message;
113
113
  }
114
114
 
@@ -7,18 +7,79 @@ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../confi
7
7
  import { dim } from "../events.js";
8
8
 
9
9
  const USAGE =
10
- "usage: oalo db dump [--env dev|prod] [--out <file.sql>]\n" +
10
+ "usage: oalo db query \"<sql>\" [--env dev|prod] [--limit <n>] [--json]\n" +
11
+ " oalo db tables [--env dev|prod]\n" +
12
+ " oalo db dump [--env dev|prod] [--out <file.sql>]\n" +
11
13
  " oalo db restore <file> --env dev|prod [--schema <name>] [--check] [--yes]\n" +
12
14
  " oalo db restore --from-env <VAR> --env dev|prod [--schema <name>] [--check] [--yes]";
13
15
 
14
16
  /** `oalo db dump` and `oalo db restore`. */
15
17
  export async function db(flags, rest, opts = {}) {
16
18
  const sub = rest[1];
19
+ if (sub === "query") return query(flags, rest[2], opts);
20
+ if (sub === "tables") return query(flags, TABLES_SQL, opts, { tables: true });
17
21
  if (sub === "dump") return dump(flags, opts);
18
22
  if (sub === "restore") return restore(flags, rest, opts);
19
23
  return fail(USAGE, 2);
20
24
  }
21
25
 
26
+ // The env's tables: an app's own and the Oalo models', with Postgres's row
27
+ // estimate (blank until it has counted; `select count(*)` for the exact number).
28
+ const TABLES_SQL =
29
+ "select c.relname as table, case when c.reltuples > 0 then c.reltuples::bigint end as approx_rows " +
30
+ "from pg_class c join pg_namespace n on n.oid = c.relnamespace " +
31
+ "where n.nspname = current_schema() and c.relkind in ('r', 'p') order by 1";
32
+
33
+ /**
34
+ * `oalo db query "<sql>"`: one read-only statement against an env (default
35
+ * the project's, dev). It runs on the Base as the env's app login, in a
36
+ * read-only transaction that is rolled back, so nothing is ever written.
37
+ * Workspace admins only, as the dump. `oalo db tables` lists the env's tables.
38
+ */
39
+ async function query(flags, sql, opts, { tables = false } = {}) {
40
+ if (typeof sql !== "string" || !sql.trim()) return fail('usage: oalo db query "select ..." [--env dev|prod] [--limit <n>] [--json]', 2);
41
+ const cfg = resolveConfig(flags);
42
+ const env = cfg.env === "prod" ? "prod" : "dev";
43
+ const { url, token } = controlPlane(cfg);
44
+ if (!url || !token) return fail(`oalo db ${tables ? "tables" : "query"} needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
45
+
46
+ const limit = tables ? 1000 : Number.parseInt(flags.limit, 10) || undefined;
47
+ const doFetch = opts.fetch || fetch;
48
+ let res;
49
+ try {
50
+ res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/query`, {
51
+ method: "POST",
52
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
53
+ body: JSON.stringify({ env, sql, ...(limit ? { limit } : {}) }),
54
+ });
55
+ } catch (e) {
56
+ return fail(`could not reach ${url} (${e.message})`, 1);
57
+ }
58
+ const body = await res.json().catch(() => ({}));
59
+ if (res.status === 404) return fail("this Base doesn't have `oalo db query` yet (it comes with a newer Base).", 1);
60
+ if (!res.ok) return fail(body?.error?.message || `the query was refused (HTTP ${res.status})`, 1);
61
+
62
+ if (flags.json) return void console.log(JSON.stringify(body, null, 2));
63
+ printTable(body.columns || [], body.rows || []);
64
+ const n = (body.rows || []).length;
65
+ console.error(dim(`${n} row${n === 1 ? "" : "s"} from ${env}${body.truncated ? `, more not shown (--limit, up to 1000)` : ""}`));
66
+ }
67
+
68
+ function printTable(columns, rows) {
69
+ if (!columns.length) return;
70
+ const text = (v) => {
71
+ const s = v === null || v === undefined ? "" : typeof v === "object" ? JSON.stringify(v) : String(v);
72
+ const one = s.replace(/\s+/g, " ");
73
+ return one.length > 60 ? one.slice(0, 59) + "…" : one;
74
+ };
75
+ const cells = rows.map((r) => r.map(text));
76
+ const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length)));
77
+ const line = (r) => r.map((v, i) => v.padEnd(widths[i])).join(" ").trimEnd();
78
+ console.log(line(columns));
79
+ console.log(widths.map((w) => "-".repeat(w)).join(" "));
80
+ for (const r of cells) console.log(line(r));
81
+ }
82
+
22
83
  /**
23
84
  * `oalo db dump [--env prod] [--out file.sql]`: all of an env's data as plain
24
85
  * SQL (every app's own tables and the Oalo models, with their rows), so it can
@@ -134,7 +134,13 @@ export async function deploy(flags) {
134
134
  console.log(dim("After adding what it needs: commit, then `oalo deploy`. `oalo docs bring-your-repo` has the details."));
135
135
  } else {
136
136
  console.log(`created ${result.app} (${result.app_type}) from ${result.commit.slice(0, 8)}, its history kept: ${result.url}`);
137
- console.log(dim("Its preview is being set up (`oalo logs` shows it). Next deploys: `oalo deploy`; live: `oalo deploy --env prod`."));
137
+ // A server app's preview is checked as a deploy's is (newer Bases); the
138
+ // code is saved either way, but a preview that doesn't run exits 1.
139
+ if (result.preview === "ok") console.log(dim("Its preview answers. Next deploys: `oalo deploy`; live: `oalo deploy --env prod`."));
140
+ else if (result.preview === "failed") {
141
+ console.error(`its preview doesn't run: ${result.preview_error || "see `oalo logs`"}. Fix it, commit, then \`oalo deploy\`.`);
142
+ process.exitCode = 1;
143
+ } else console.log(dim("Its preview is being set up (`oalo logs` shows it). Next deploys: `oalo deploy`; live: `oalo deploy --env prod`."));
138
144
  storeBuildHint(result.app_type, result.app);
139
145
  }
140
146
  }
@@ -16,7 +16,9 @@ import { dim } from "../events.js";
16
16
  * notes.md` saves one; `--json` gives the structured form.
17
17
  */
18
18
  export async function docs(flags, rest) {
19
- const slug = rest[1];
19
+ // `oalo docs list` (and `ls`) is what people and agents type for the list:
20
+ // there is no page by either name.
21
+ const slug = ["list", "ls"].includes(rest[1]) ? undefined : rest[1];
20
22
  const cfg = resolveConfig(flags);
21
23
  const { url, token } = controlPlane(cfg);
22
24
  if (!url || !token) {
@@ -161,8 +161,8 @@ function writeFetched(path, next, force, report) {
161
161
 
162
162
  export async function pull(flags, rest) {
163
163
  const what = rest[1] || "all";
164
- if (!["all", "flows", "loops", "tools"].includes(what)) {
165
- console.error("usage: oalo pull [flows|loops|tools] [--bot <id>] [--name <name>] [--force]");
164
+ if (!["all", "flows", "loops", "tools", "catalog"].includes(what)) {
165
+ console.error("usage: oalo pull [flows|loops|tools|catalog] [--bot <id>] [--name <name>] [--force]");
166
166
  process.exitCode = 2;
167
167
  return;
168
168
  }
@@ -180,6 +180,11 @@ export async function pull(flags, rest) {
180
180
  if (catalog) writeGraphFile(catalogPath(surface), catalog);
181
181
  }
182
182
 
183
+ if (what === "catalog") {
184
+ console.error(dim("node catalogs written to .oalo/catalog/flow.json and loop.json"));
185
+ return;
186
+ }
187
+
183
188
  if (what === "all" || what === "flows") {
184
189
  const bots = await listBots(ch);
185
190
  const chosen = flags.bot
@@ -232,6 +237,17 @@ export async function pull(flags, rest) {
232
237
  for (const p of report.written) console.log(`pulled ${p}`);
233
238
  for (const p of report.kept) console.log(`kept ${p} ${dim("(edited locally; push it, or pull --force to discard)")}`);
234
239
  console.error(dim(`${report.written.length} written, ${report.kept.length} kept. Node catalogs in .oalo/catalog/.`));
240
+ // A bare pull copies the whole workspace (every bot's flows, every loop)
241
+ // into this folder, often an app's repo (found by the CLI trial).
242
+ if (what !== "catalog" && !flags.name && !flags.bot && report.written.length > 5) {
243
+ console.error(
244
+ dim(
245
+ "That's the whole workspace. To work on one, pull it by name (`oalo pull loops --name <loop>`), " +
246
+ "and add .oalo/flows/ and .oalo/loops/ to .gitignore if this repo shouldn't carry the others. " +
247
+ "`oalo pull catalog` gets only the node catalogs.",
248
+ ),
249
+ );
250
+ }
235
251
  } catch (e) {
236
252
  console.error(`pull failed: ${e.message}`);
237
253
  process.exitCode = 1;
@@ -423,7 +439,9 @@ async function pushOne(ch, path, file, flags) {
423
439
  if (triggerNotes.failed.length) {
424
440
  return { ok: false, state: "partly pushed", note: `the loop saved (v${remote?.version ?? "?"}), but ${triggerNotes.failed.join("; ")}` };
425
441
  }
426
- return { ok: true, state: "pushed", note: remote ? `v${remote.version}` : "" };
442
+ // A new loop's first version is 0: say "created" rather than "v0".
443
+ const created = file.version == null;
444
+ 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}`) : "" };
427
445
  } catch (e) {
428
446
  if (e.code === "conflict") {
429
447
  // Save the server's copy beside the file, so the merge is a file diff
@@ -63,7 +63,7 @@ export async function mcp(flags) {
63
63
  if (!args.event) throw new Error("event is required");
64
64
  result = await oalo.call(args.event, args.params || {});
65
65
  } else if (spec.run) {
66
- result = await spec.run(oalo, args, { cfg, url });
66
+ result = await spec.run(oalo, args, { cfg, url, token });
67
67
  } else if (spec.route) {
68
68
  const { event, params } = spec.route(args);
69
69
  // The tool's own wait applies here too: a rollback builds for minutes.
@@ -19,8 +19,9 @@ import { appIdFor } from "../app-ref.js";
19
19
  export async function loops(flags, rest, opts = {}) {
20
20
  const [, sub, name] = rest;
21
21
  if (sub === "runs") return runs(flags, name, opts);
22
+ if (sub === "list") return list(flags, opts);
22
23
  if (!["test", "on", "off", "delete"].includes(sub) || !name) {
23
- return fail("usage: oalo loops test|on|off|delete <name>, or oalo loops runs [<name>] [--id <run>]", 2);
24
+ return fail("usage: oalo loops list, oalo loops test|on|off|delete <name>, or oalo loops runs [<name>] [--id <run>]", 2);
24
25
  }
25
26
 
26
27
  let input;
@@ -71,6 +72,22 @@ export async function flows(flags, rest, opts = {}) {
71
72
  });
72
73
  }
73
74
 
75
+ /** `oalo loops list`: every loop's name, on or off, and description (found missing by the CLI trial). */
76
+ async function list(flags, opts) {
77
+ return withChannel(flags, opts, async (ch) => {
78
+ const entries = (await ch.call("loops:list_for_org", {}))?.entries ?? [];
79
+ if (flags.json) return void console.log(JSON.stringify(entries.map(({ name, enabled, description, app_id }) => ({ name, enabled: enabled !== false, description: description ?? null, app_id: app_id ?? null })), null, 2));
80
+ if (!entries.length) return void console.log("no loops in this workspace");
81
+ const width = Math.min(40, Math.max(...entries.map((e) => String(e.name).length)));
82
+ for (const e of [...entries].sort((a, b) => String(a.name).localeCompare(String(b.name)))) {
83
+ const state = e.enabled === false ? "off" : "on ";
84
+ const desc = String(e.description || "").replace(/\s+/g, " ");
85
+ const pinned = e.app_id ? dim(` [app ${e.app_id}]`) : "";
86
+ console.log(`${String(e.name).padEnd(width)} ${state} ${desc.length > 70 ? desc.slice(0, 69) + "…" : desc}${pinned}`);
87
+ }
88
+ });
89
+ }
90
+
74
91
  /** `oalo loops runs [name]`: recent runs; `--id <run>`: one run, step by step. */
75
92
  async function runs(flags, name, opts) {
76
93
  return withChannel(flags, opts, async (ch) => {
package/src/config.js CHANGED
@@ -119,15 +119,34 @@ export function forgetWorkspace(serverUrl) {
119
119
  * The control-plane URL and CLI token for a command. When this project (or
120
120
  * --server / OALO_URL) names a workspace, only that workspace's token is used;
121
121
  * a token saved for another workspace would just fail to authenticate. With
122
- * no workspace named, the most recently saved one is used.
122
+ * no workspace named, the one saved workspace is used. With several saved, it
123
+ * refuses (WhichWorkspace) rather than pick one: "the latest login" sent an
124
+ * unlinked folder's commands to another customer's live Base.
123
125
  */
124
126
  export function controlPlane(cfg) {
125
127
  if (cfg.cliToken) return { url: cfg.serverUrl, token: cfg.cliToken };
126
128
  const saved = listWorkspaces("cli");
129
+ if (!cfg.serverUrl) {
130
+ const urls = [...new Set(saved.map((w) => w.serverUrl))];
131
+ if (urls.length > 1) throw new WhichWorkspace(urls);
132
+ }
127
133
  const match = cfg.serverUrl ? saved.find((w) => w.serverUrl === cfg.serverUrl) : saved[0];
128
134
  return { url: cfg.serverUrl || match?.serverUrl || null, token: match?.token || null };
129
135
  }
130
136
 
137
+ /** Several workspaces are saved and nothing says which one a command is for. */
138
+ export class WhichWorkspace extends Error {
139
+ constructor(urls) {
140
+ super(
141
+ "This machine has more than one workspace saved, and nothing here says which one to use:\n" +
142
+ urls.map((u) => ` ${u}`).join("\n") +
143
+ "\n\nLink this folder to one with `oalo link --server <url>`, or pass --server <url>, or set OALO_URL."
144
+ );
145
+ this.code = "OALO_WHICH_WORKSPACE";
146
+ this.urls = urls;
147
+ }
148
+ }
149
+
131
150
  /** How to get a CLI token, for "needs a CLI token" messages. */
132
151
  export const HOW_TO_CONNECT =
133
152
  "Connect this machine with:\n oalo login <workspace> (your Base at <workspace>.oalo.ai)\n\n" +
@@ -1,25 +1,25 @@
1
1
  {
2
- "version": "0.4.0",
2
+ "version": "0.4.2",
3
3
  "targets": {
4
4
  "darwin-arm64": {
5
5
  "file": "oalo-coord-darwin-arm64.gz",
6
- "sha256": "da9c1663ffc673924b77fed8ad61b09c16ec61e2f738228e059b5b8fa38cdd29",
7
- "bytes": 24851871
6
+ "sha256": "6bf4ff29d58947190a7e06b9a57ba3b3a86a53f49d6385236d9b12a7dd625a0b",
7
+ "bytes": 24852265
8
8
  },
9
9
  "darwin-x64": {
10
10
  "file": "oalo-coord-darwin-x64.gz",
11
- "sha256": "8e3d36775180843d7e333f54321ed0310f7af126b8a2954b8bbf6afd06a09f32",
12
- "bytes": 26990220
11
+ "sha256": "79c5ef4605c58ef46dfe7322fc3015ba8bc569105fc4567e3d5158faaed3ace9",
12
+ "bytes": 26990581
13
13
  },
14
14
  "linux-x64": {
15
15
  "file": "oalo-coord-linux-x64.gz",
16
- "sha256": "222745d2249b43a0db546bddfcb0118d53cf4040a5e748f76c69834152ac3b05",
17
- "bytes": 36882875
16
+ "sha256": "a0e43de30ea35d270cd6a51fcbd5ef857c128ddc4b80369324d6a7306a2f2068",
17
+ "bytes": 36883315
18
18
  },
19
19
  "linux-arm64": {
20
20
  "file": "oalo-coord-linux-arm64.gz",
21
- "sha256": "43b5c16359d9a864248798162e78f214ccfea0c5639ce479ab83d8be0c3b4803",
22
- "bytes": 37123621
21
+ "sha256": "c9a5a41a7975e256e1d5ec3f0605282549d249ff5c2fc475d52b3eddfc1494df",
22
+ "bytes": 37124009
23
23
  }
24
24
  }
25
25
  }
package/src/graphfiles.js CHANGED
@@ -60,7 +60,7 @@ export const TOOL_FIELDS = ["description", "input_schema", "output_schema"];
60
60
  const ABOUT = {
61
61
  tool: "The code is in the .js file next to this one (`source`); edit it, or `tool`, then `oalo push`. It is compiled when pushed, so code that doesn't build is refused. Leave id, version and base_hash alone.",
62
62
  flow: "Edit `flow`, then `oalo lint` and `oalo push`. Leave id, version and base_hash alone. The node contract is .oalo/catalog/flow.json.",
63
- loop: "Edit `loop`, then `oalo lint` and `oalo push`. The name is the loop's identity. Leave version, base_hash and trigger_base alone. The node contract is .oalo/catalog/loop.json. `triggers` is what starts the loop: add one as {type, event | cron | widget_id, filter?} (types and events: oalo_loop_triggers action=catalog), delete one to remove it, and push. Set a trigger's `enabled` to turn it on or off. `trigger_type`/`trigger_event` in `loop` are the old single trigger; prefer `triggers`.",
63
+ loop: "Edit `loop`, then `oalo lint` and `oalo push`. The name is the loop's identity. Leave version, base_hash and trigger_base alone. The node contract is .oalo/catalog/loop.json. `triggers` is what starts the loop: add one as {type, event | cron | widget_id, filter?} (types and events: oalo_loop_triggers action=catalog), or for an app to call it (POST /api/workflows/v1/<name>/run) as {type: 'api', description, input: {field: 'string'}, output: {field: 'string'}} (oalo docs workflow-calls). Delete one to remove it, and push. Set a trigger's `enabled` to turn it on or off. `trigger_type`/`trigger_event` in `loop` are the old single trigger; prefer `triggers`.",
64
64
  };
65
65
 
66
66
  /** JSON with object keys sorted at every level, so equal content hashes equal. */
@@ -111,7 +111,7 @@ export function flowFile(remote, bot) {
111
111
  * ones a teammate added since.
112
112
  */
113
113
  export function loopFile(remote, triggers) {
114
- const loop = pick(remote, LOOP_FIELDS);
114
+ const loop = withoutInertLegacyTrigger(pick(remote, LOOP_FIELDS));
115
115
  const file = {
116
116
  $about: ABOUT.loop,
117
117
  kind: "loop",
@@ -129,6 +129,20 @@ export function loopFile(remote, triggers) {
129
129
  return file;
130
130
  }
131
131
 
132
+ /**
133
+ * The legacy single trigger (`trigger_type`, `trigger_event`, `trigger_filter`,
134
+ * `cron`) when it starts nothing: the column defaults to "cron" with no
135
+ * schedule, which read as "runs on a schedule" on a loop that an app calls
136
+ * (found by the CLI trial). Left out of the file; a save without any of the
137
+ * three keeps what is stored (Loops), so nothing changes on the server.
138
+ */
139
+ export function withoutInertLegacyTrigger(loop) {
140
+ const blank = (v) => v === null || v === undefined || v === "";
141
+ if (loop.trigger_type !== "cron" || !blank(loop.cron) || !blank(loop.trigger_event) || !blank(loop.trigger_filter)) return loop;
142
+ const { trigger_type, trigger_event, trigger_filter, cron, ...rest } = loop;
143
+ return rest;
144
+ }
145
+
132
146
  /** A trigger as listed, without empty keys. */
133
147
  export function cleanTrigger(t) {
134
148
  return Object.fromEntries(Object.entries(t || {}).filter(([, v]) => v !== null && v !== undefined));
@@ -205,9 +219,19 @@ export function standing(file, remote) {
205
219
  return "clean";
206
220
  }
207
221
 
222
+ /**
223
+ * The smallest new file of each kind, for errors and help: a new loop or flow
224
+ * is often written from scratch, with no pulled file to copy.
225
+ */
226
+ export const NEW_FILE_SHAPE = {
227
+ loop: '{"kind": "loop", "name": "<name>", "loop": {"description": "...", "entry": "<first node id>", "nodes": [...], "edges": [...]}, "triggers": [{"type": "api", "description": "...", "input": {"x": "string"}, "output": {"y": "string"}}]}',
228
+ flow: '{"kind": "flow", "bot": "<bot_ public id>", "flow": {"name": "<name>", "description": "...", "graph": {...}}}',
229
+ };
230
+ const SHAPES = `A new loop file: ${NEW_FILE_SHAPE.loop}\nA new flow file: ${NEW_FILE_SHAPE.flow}\nNode settings: .oalo/catalog/loop.json and flow.json (oalo pull writes them).`;
231
+
208
232
  export function readGraphFile(path) {
209
233
  const file = JSON.parse(readFileSync(path, "utf8"));
210
- if (!["flow", "loop", "tool"].includes(file.kind)) throw new Error(`${path}: not an oalo flow, loop or tool file (kind is ${JSON.stringify(file.kind)})`);
234
+ if (!["flow", "loop", "tool"].includes(file.kind)) throw new Error(`${path}: not an oalo flow, loop or tool file (kind is ${JSON.stringify(file.kind)}).\n${SHAPES}`);
211
235
  if (file.kind === "tool") {
212
236
  if (!file.name || !file.tool) throw new Error(`${path}: a tool file needs \`name\` and \`tool\``);
213
237
  const src = join(dirname(path), file.source || `${slug(file.name)}.js`);
@@ -215,8 +239,8 @@ export function readGraphFile(path) {
215
239
  // Not written back: the .js file is the source of truth for the code.
216
240
  Object.defineProperty(file, "_source", { value: readFileSync(src, "utf8"), enumerable: false });
217
241
  }
218
- if (file.kind === "flow" && (!file.bot || !file.flow)) throw new Error(`${path}: a flow file needs \`bot\` and \`flow\``);
219
- if (file.kind === "loop" && (!file.name || !file.loop)) throw new Error(`${path}: a loop file needs \`name\` and \`loop\``);
242
+ if (file.kind === "flow" && (!file.bot || !file.flow)) throw new Error(`${path}: a flow file needs \`bot\` and \`flow\`.\nA new flow file: ${NEW_FILE_SHAPE.flow}`);
243
+ if (file.kind === "loop" && (!file.name || !file.loop)) throw new Error(`${path}: a loop file needs \`name\` and \`loop\`.\nA new loop file: ${NEW_FILE_SHAPE.loop}`);
220
244
  return file;
221
245
  }
222
246
 
package/src/help.js CHANGED
@@ -245,14 +245,18 @@ export const COMMANDS = [
245
245
  },
246
246
  {
247
247
  name: "db",
248
- summary: "All of an env's data as plain SQL (every app's own tables and the Oalo models), to keep a copy or take it anywhere. Or load an existing Postgres database into an env.",
248
+ summary: "Read an env's tables with SQL (your app's own included), dump all of an env's data as plain SQL to keep or take anywhere, or load an existing Postgres database into an env.",
249
249
  usage: [
250
+ 'oalo db query "<sql>" [--env dev|prod] [--limit <n>] [--json]',
251
+ "oalo db tables [--env dev|prod]",
250
252
  "oalo db dump [--env dev|prod] [--out <file.sql>] [--force]",
251
253
  "oalo db restore <file> --env dev|prod [--schema <name>] [--check] [--yes]",
252
254
  "oalo db restore --from-env <VAR> --env dev|prod [--schema <name>] [--check] [--yes]",
253
255
  ],
254
256
  flags: [
255
- { flag: "--env dev|prod", desc: "dump: which env's data. Default prod. restore: which env the data goes into, always on the command line." },
257
+ { flag: "--env dev|prod", desc: "query, tables: which env. Default the project's (dev). dump: which env's data. Default prod. restore: which env the data goes into, always on the command line." },
258
+ { flag: "--limit <n>", desc: "query: rows to show. Default 100, at most 1000." },
259
+ { flag: "--json", desc: "query: {columns, rows, truncated} as JSON." },
256
260
  { flag: "--out <file.sql>", desc: "Where to write it. Default <workspace>-<env>-<date>.sql here." },
257
261
  { flag: "--force", desc: "Replace the file if it exists." },
258
262
  { flag: "--from-env <VAR>", desc: "restore: copy from a running database instead of a file. VAR is the environment variable that holds its postgres:// or postgresql:// URL. Only its host is ever shown." },
@@ -261,6 +265,7 @@ export const COMMANDS = [
261
265
  { flag: "--yes", desc: "restore: go ahead with prod without asking. Needed for prod when there's no terminal to ask at." },
262
266
  ],
263
267
  notes: [
268
+ "query reads only: one statement (SELECT, WITH, TABLE, VALUES, EXPLAIN or SHOW), run as your app's database login in a read-only transaction that is rolled back, with a 10 second limit. It sees what your app sees at DATABASE_URL: the env's tables, not the platform's. `oalo data` is for Oalo models; this is for any table, your app's own included.",
264
269
  "Workspace admins only: it holds every member's data. Restore it into any Postgres with psql -f.",
265
270
  "Your code is in git (oalo deploy --pull); this is the data. Together they are everything you need to run your apps elsewhere.",
266
271
  "restore loads a dump file made by pg_dump (like Heroku's latest.dump), up to 10 GB, or copies from a database URL. Admins only, and one restore at a time per Base.",
@@ -712,8 +717,9 @@ export const COMMANDS = [
712
717
  },
713
718
  {
714
719
  name: "loops",
715
- summary: "Test a loop (sends simulated), see its past runs, turn it on or off, or delete it, without pulling and pushing it.",
720
+ summary: "List the loops, test one (sends simulated), see its past runs, turn it on or off, or delete it, without pulling and pushing it.",
716
721
  usage: [
722
+ "oalo loops list [--json]",
717
723
  "oalo loops test <name> [--sample latest|example] [--input <json|@file.json>] [--json]",
718
724
  "oalo loops on <name>",
719
725
  "oalo loops off <name>",
@@ -723,7 +729,7 @@ export const COMMANDS = [
723
729
  ],
724
730
  flags: [
725
731
  { flag: "--sample latest|example", desc: "Test with the loop's most recent real event, or one built from its trigger's fields." },
726
- { flag: "--input <json|@file>", desc: "Test with this input instead: an event envelope {type, contact_id, payload}, or what a scheduled loop's first step reads." },
732
+ { flag: "--input <json|@file>", desc: "Test with this input instead: an event envelope {type, contact_id, payload}; for a loop an app calls (an api trigger), {\"type\": \"api\", \"payload\": {<its input fields>}}; or what a scheduled loop's first step reads." },
727
733
  { flag: "--app <slug>", desc: "Only for a loop pinned to one app: that app's slug (`oalo apps`) or id. Works with test, runs, on, off and delete." },
728
734
  { flag: "--id <run>", desc: "runs: one run step by step, with each step's output." },
729
735
  { flag: "--limit N", desc: "runs: at most this many (default 20)." },
@@ -751,7 +757,7 @@ export const COMMANDS = [
751
757
  {
752
758
  name: "pull",
753
759
  summary: "Fetch chat flows, loops and code tools into .oalo/ as files you can edit.",
754
- usage: ["oalo pull [flows|loops|tools] [--bot <id>] [--name <name>] [--force]"],
760
+ usage: ["oalo pull [flows|loops|tools|catalog] [--bot <id>] [--name <name>] [--force]"],
755
761
  flags: [
756
762
  { flag: "--bot <id>", desc: "Only this bot's flows (numeric or public bot_ id)." },
757
763
  { flag: "--name <name>", desc: "Only the flow or loop with this name." },
@@ -763,7 +769,8 @@ export const COMMANDS = [
763
769
  "A loop file also lists the loop's `triggers` (what starts it). Add or delete entries and push: push adds the new ones and removes the ones you deleted, and keeps any a teammate added since your pull. Set a trigger's `enabled` to turn it on or off.",
764
770
  "Each file holds the editable object (`flow` or `loop`) plus the CLI's bookkeeping: id, version (sent back as base_version on push) and base_hash (how the CLI knows you edited it). Edit the object; leave the bookkeeping alone.",
765
771
  "A file you have edited is kept, not overwritten, unless you pass --force.",
766
- "To create a flow or loop, write a file in the same shape without id or version, then push it.",
772
+ "With no name, pull copies the whole workspace (every bot's flows, every loop) into .oalo/. In an app's repo, pull what you work on by name, and gitignore the rest. `oalo pull catalog` writes only the node catalogs.",
773
+ "To create a flow or loop, write a file in the same shape without id or version, then push it. A new loop: {\"kind\": \"loop\", \"name\": \"<name>\", \"loop\": {\"entry\", \"nodes\", \"edges\", ...}, \"triggers\": [...]}. A new flow: {\"kind\": \"flow\", \"bot\": \"<bot_ id>\", \"flow\": {\"name\", \"graph\", ...}}. Run oalo pull once first for the node contracts in .oalo/catalog/.",
767
774
  "Needs a CLI token.",
768
775
  ],
769
776
  exits: { 0: "pulled", 1: "pull failed", 2: "bad arguments or no token" },
package/src/index.js CHANGED
@@ -90,7 +90,13 @@ if ((flags.version || cmd === "version") && !flags.help) {
90
90
  }
91
91
  }
92
92
 
93
- await dispatch(cmd);
93
+ try {
94
+ await dispatch(cmd);
95
+ } catch (e) {
96
+ // controlPlane() refusing to guess between saved workspaces: a usage error.
97
+ if (e?.code === "OALO_WHICH_WORKSPACE") finish(e.message, 2, process.stderr);
98
+ else throw e;
99
+ }
94
100
  }
95
101
 
96
102
  async function dispatch(cmd) {
package/src/mcp/tools.js CHANGED
@@ -634,7 +634,7 @@ export const TOOLS = [
634
634
  {
635
635
  name: "oalo_read_rows",
636
636
  description:
637
- "Read rows from a model. With id: one row. Otherwise a page in write order: pass since=<next_since> from the previous page to continue while has_more is true. Each row is {id, document, owner_id, availability, product_id, seqnum, ...}; the fields are in document. Read-only.",
637
+ "Read rows from an Oalo model (a table an app made itself isn't one: use oalo_db_query). With id: one row. Otherwise a page in write order: pass since=<next_since> from the previous page to continue while has_more is true. Each row is {id, document, owner_id, availability, product_id, seqnum, ...}; the fields are in document. Read-only.",
638
638
  inputSchema: S(
639
639
  {
640
640
  table: { type: "string" },
@@ -650,6 +650,30 @@ export const TOOLS = [
650
650
  return id ? getRow(c, table, id) : listRows(c, table, { since, limit });
651
651
  },
652
652
  },
653
+ {
654
+ name: "oalo_db_query",
655
+ description:
656
+ "One read-only SQL statement against an env's tables, as the app's own database login sees them (the server apps' own tables and the Oalo models; not the platform's). Use it to check rows an app wrote to its own table, which oalo_read_rows can't see (it reads Oalo models only). SELECT, WITH, TABLE, VALUES, EXPLAIN or SHOW; run in a read-only transaction that is rolled back, 10 second limit. List the tables with: select relname from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = current_schema() and relkind = 'r'. Workspace admins only. Rows can hold customers' details: never repeat those. Read-only.",
657
+ inputSchema: S(
658
+ {
659
+ sql: { type: "string", description: "One statement" },
660
+ env: { type: "string", enum: ["dev", "prod"], description: "Default dev" },
661
+ limit: { type: "integer", description: "Rows, default 100, at most 1000" },
662
+ },
663
+ ["sql"],
664
+ ),
665
+ run: async (_oalo, { sql, env, limit }, ctx) => {
666
+ const res = await fetch(`${String(ctx.url).replace(/\/$/, "")}/api/cli/v1/db/query`, {
667
+ method: "POST",
668
+ headers: { authorization: `Bearer ${ctx.token}`, "content-type": "application/json" },
669
+ body: JSON.stringify({ sql, env: env === "prod" ? "prod" : "dev", ...(limit ? { limit } : {}) }),
670
+ });
671
+ const body = await res.json().catch(() => ({}));
672
+ if (res.status === 404) throw new Error("this workspace doesn't have db queries yet (it comes with a newer Base)");
673
+ if (!res.ok) throw new Error(body?.error?.message || `the query was refused (HTTP ${res.status})`);
674
+ return body;
675
+ },
676
+ },
653
677
  {
654
678
  name: "oalo_query_metrics",
655
679
  description:
@@ -763,8 +787,9 @@ export const BY_NAME = Object.fromEntries(TOOLS.map((t) => [t.name, t]));
763
787
 
764
788
  /** The read side for data tools: the saved data token, on one schema. */
765
789
  function readSide(ctx, env = "dev") {
766
- // The project may name no workspace; then the channel connected to the most
767
- // recently saved one, and its data token is the one to use.
790
+ // The project may name no workspace; then the channel connected to the one
791
+ // saved workspace (several saved and none named is refused), and its data
792
+ // token is the one to use.
768
793
  const token = ctx?.cfg?.token || (ctx?.url && readToken({ serverUrl: ctx.url, appId: null }, "sync"));
769
794
  if (!token) {
770
795
  throw new Error("no data token saved for this workspace. Ask the person to run `oalo login --server <workspace url>`.");