@oalo-ai/cli 0.4.1 → 0.4.3

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.
@@ -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
@@ -14,6 +14,7 @@ import {
14
14
  writeGraphFile,
15
15
  removeFile,
16
16
  listGraphFiles,
17
+ expandTargets,
17
18
  locallyModified,
18
19
  standing,
19
20
  rel,
@@ -129,11 +130,11 @@ function botKey(bots, flow) {
129
130
  return bot?.public_bot_id || String(flow.bot_id);
130
131
  }
131
132
 
132
- /** Resolve the files a command acts on: the ones named, or every file. */
133
+ /** Resolve the files a command acts on: the ones named (a folder means the files in it), or every file. */
133
134
  function targetFiles(rest) {
134
135
  const named = rest.slice(1);
135
136
  if (named.length === 0) return listGraphFiles();
136
- return named.map((p) => resolvePath(p));
137
+ return expandTargets(named.map((p) => resolvePath(p)));
137
138
  }
138
139
 
139
140
  function load(path) {
@@ -161,8 +162,8 @@ function writeFetched(path, next, force, report) {
161
162
 
162
163
  export async function pull(flags, rest) {
163
164
  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]");
165
+ if (!["all", "flows", "loops", "tools", "catalog"].includes(what)) {
166
+ console.error("usage: oalo pull [flows|loops|tools|catalog] [--bot <id>] [--name <name>] [--force]");
166
167
  process.exitCode = 2;
167
168
  return;
168
169
  }
@@ -180,6 +181,11 @@ export async function pull(flags, rest) {
180
181
  if (catalog) writeGraphFile(catalogPath(surface), catalog);
181
182
  }
182
183
 
184
+ if (what === "catalog") {
185
+ console.error(dim("node catalogs written to .oalo/catalog/flow.json and loop.json"));
186
+ return;
187
+ }
188
+
183
189
  if (what === "all" || what === "flows") {
184
190
  const bots = await listBots(ch);
185
191
  const chosen = flags.bot
@@ -232,6 +238,17 @@ export async function pull(flags, rest) {
232
238
  for (const p of report.written) console.log(`pulled ${p}`);
233
239
  for (const p of report.kept) console.log(`kept ${p} ${dim("(edited locally; push it, or pull --force to discard)")}`);
234
240
  console.error(dim(`${report.written.length} written, ${report.kept.length} kept. Node catalogs in .oalo/catalog/.`));
241
+ // A bare pull copies the whole workspace (every bot's flows, every loop)
242
+ // into this folder, often an app's repo (found by the CLI trial).
243
+ if (what !== "catalog" && !flags.name && !flags.bot && report.written.length > 5) {
244
+ console.error(
245
+ dim(
246
+ "That's the whole workspace. To work on one, pull it by name (`oalo pull loops --name <loop>`), " +
247
+ "and add .oalo/flows/ and .oalo/loops/ to .gitignore if this repo shouldn't carry the others. " +
248
+ "`oalo pull catalog` gets only the node catalogs.",
249
+ ),
250
+ );
251
+ }
235
252
  } catch (e) {
236
253
  console.error(`pull failed: ${e.message}`);
237
254
  process.exitCode = 1;
@@ -295,15 +312,18 @@ export async function status(flags, rest) {
295
312
 
296
313
  // ---- lint ------------------------------------------------------------------
297
314
 
298
- export async function lint(flags, rest) {
315
+ // Lint has no check for a tool's code: it is compiled when pushed.
316
+ export const TOOL_NOT_LINTED = "not checked by lint: a tool's code is compiled and checked when you push it";
317
+
318
+ export async function lint(flags, rest, opts = {}) {
299
319
  const paths = targetFiles(rest);
300
320
  if (paths.length === 0) {
301
- console.error("no flow or loop files under .oalo/. Run `oalo pull` first, or name a file.");
321
+ console.error(rest.length > 1 ? `no flow, loop or tool files in ${rest.slice(1).join(", ")}` : "no flow or loop files under .oalo/. Run `oalo pull` first, or name a file.");
302
322
  process.exitCode = 1;
303
323
  return;
304
324
  }
305
325
 
306
- const ws = await openWorkspace(flags, "lint").catch((e) => (console.error(`lint failed: ${e.message}`), null));
326
+ const ws = await openWorkspace(flags, "lint", opts).catch((e) => (console.error(`lint failed: ${e.message}`), null));
307
327
  if (!ws) return void (process.exitCode = process.exitCode || 2);
308
328
  const { ch } = ws;
309
329
  let errors = 0;
@@ -316,6 +336,11 @@ export async function lint(flags, rest) {
316
336
  errors++;
317
337
  continue;
318
338
  }
339
+ if (file.kind === "tool") {
340
+ if (flags.json) console.log(JSON.stringify({ path: rel(path), findings: [], note: TOOL_NOT_LINTED }));
341
+ else console.log(`${rel(path)}\n ${TOOL_NOT_LINTED}`);
342
+ continue;
343
+ }
319
344
  const findings = await lintFile(ch, file);
320
345
  if (flags.json) {
321
346
  console.log(JSON.stringify({ path: rel(path), findings }));
@@ -423,7 +448,9 @@ async function pushOne(ch, path, file, flags) {
423
448
  if (triggerNotes.failed.length) {
424
449
  return { ok: false, state: "partly pushed", note: `the loop saved (v${remote?.version ?? "?"}), but ${triggerNotes.failed.join("; ")}` };
425
450
  }
426
- return { ok: true, state: "pushed", note: remote ? `v${remote.version}` : "" };
451
+ // A new loop's first version is 0: say "created" rather than "v0".
452
+ 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}`) : "" };
427
454
  } catch (e) {
428
455
  if (e.code === "conflict") {
429
456
  // Save the server's copy beside the file, so the merge is a file diff
@@ -527,7 +554,9 @@ const describeTrigger = (t) =>
527
554
  .join(" ");
528
555
 
529
556
  export async function push(flags, rest) {
530
- const explicit = rest.length > 1;
557
+ // A file named directly is pushed even when unchanged; the files in a named
558
+ // folder are pushed only when changed, like a bare push.
559
+ const named = new Set(rest.slice(1).map((p) => resolvePath(p)));
531
560
  const paths = targetFiles(rest);
532
561
  if (paths.length === 0) {
533
562
  console.error("no flow or loop files under .oalo/. Run `oalo pull` first, or name a file.");
@@ -550,7 +579,7 @@ export async function push(flags, rest) {
550
579
  continue;
551
580
  }
552
581
  // Without named files, push only what changed (or is new).
553
- if (!explicit && !locallyModified(file) && !flags.all) continue;
582
+ if (!named.has(path) && !locallyModified(file) && !flags.all) continue;
554
583
 
555
584
  console.log(`${rel(path)}`);
556
585
  const r = await pushOne(ch, path, file, flags);
@@ -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, flags);
24
25
  }
25
26
 
26
27
  let input;
@@ -28,11 +29,11 @@ export async function loops(flags, rest, opts = {}) {
28
29
  try {
29
30
  input = readInput(flags.input);
30
31
  } catch (e) {
31
- return fail(e.message, 2);
32
+ return fail(e.message, 2, flags);
32
33
  }
33
34
  }
34
35
  if (flags.sample !== undefined && !["latest", "example"].includes(flags.sample)) {
35
- return fail("--sample is latest or example", 2);
36
+ return fail("--sample is latest or example", 2, flags);
36
37
  }
37
38
 
38
39
  return withChannel(flags, opts, async (ch) => {
@@ -59,7 +60,7 @@ export async function loops(flags, rest, opts = {}) {
59
60
  export async function flows(flags, rest, opts = {}) {
60
61
  const [, sub, bot, flow] = rest;
61
62
  if (!["on", "off", "delete"].includes(sub) || !bot || !flow) {
62
- return fail("usage: oalo flows on|off|delete <bot> <flow> (bot: its public id; flow: its name or id)", 2);
63
+ return fail("usage: oalo flows on|off|delete <bot> <flow> (bot: its public id; flow: its name or id)", 2, flags);
63
64
  }
64
65
 
65
66
  return withChannel(flags, opts, async (ch) => {
@@ -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) => {
@@ -79,7 +96,7 @@ async function runs(flags, name, opts) {
79
96
  const r = await ch.call("loops:get_run", { run_id: Number(flags.id) });
80
97
  if (flags.json) return void console.log(JSON.stringify(r, null, 2));
81
98
  const run = r.run || {};
82
- console.log(`${run.name} run ${run.id}: ${run.status}${run.error ? `: ${oneLine(run.error)}` : ""} ${dim(`(${run.trigger || "?"}, ${String(run.started_at || "").slice(0, 19).replace("T", " ")})`)}`);
99
+ console.log(`${run.name} run ${run.id}: ${run.status}${run.error ? `: ${oneLine(run.error)}` : ""} ${dim(`(${run.trigger || "?"}, ${utc(run.started_at, true)})`)}`);
83
100
  for (const n of r.nodes || []) {
84
101
  console.log(` ${n.node_id} ${dim(`(${n.node_type}${n.status ? `, ${n.status}` : ""})`)}`);
85
102
  const out = n.error || n.output;
@@ -92,7 +109,7 @@ async function runs(flags, name, opts) {
92
109
  if (flags.json) return void console.log(JSON.stringify(r.runs, null, 2));
93
110
  if (!r.runs?.length) return void console.log(name ? `no runs of ${name} yet` : "no loop runs yet");
94
111
  for (const x of r.runs) {
95
- const when = String(x.started_at || "").slice(0, 16).replace("T", " ");
112
+ const when = utc(x.started_at);
96
113
  const test = x.rehearsal ? ", test" : "";
97
114
  console.log(`${String(x.id).padEnd(7)} ${x.name} ${x.status}${x.error ? dim(`: ${oneLine(x.error).slice(0, 120)}`) : ""} ${dim(`${when}, ${x.trigger}${test}`)}`);
98
115
  }
@@ -112,6 +129,19 @@ function printTest(r) {
112
129
  if (r.final_output !== undefined && r.final_output !== null) console.log(`output: ${oneLine(r.final_output)}`);
113
130
  }
114
131
 
132
+ /**
133
+ * A run's start time as "2026-11-07 08:00 UTC" (with seconds when asked). The
134
+ * server's times are UTC; one without a zone is read as UTC too.
135
+ */
136
+ export function utc(ts, seconds = false) {
137
+ if (!ts) return "?";
138
+ const s = String(ts);
139
+ const zoned = /(Z|[+-]\d\d:?\d\d)$/i.test(s);
140
+ const d = new Date(zoned ? s : `${s}Z`);
141
+ if (Number.isNaN(d.getTime())) return s;
142
+ return `${d.toISOString().slice(0, seconds ? 19 : 16).replace("T", " ")} UTC`;
143
+ }
144
+
115
145
  function oneLine(v) {
116
146
  const text = typeof v === "string" ? v : JSON.stringify(v);
117
147
  return text.length > 300 ? text.slice(0, 300) + "..." : text;
@@ -137,20 +167,25 @@ async function pinnedApp(ch, flags) {
137
167
  async function withChannel(flags, opts, fn) {
138
168
  const cfg = resolveConfig(flags);
139
169
  const { url, token } = controlPlane(cfg);
140
- if (!url || !token) return fail(`this needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
170
+ if (!url || !token) return fail(`this needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2, flags);
141
171
 
142
172
  const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
143
173
  try {
144
174
  await ch.connect();
145
175
  await fn(ch);
146
176
  } catch (e) {
147
- fail(e.message, 1);
177
+ fail(e.message, 1, flags, e.code);
148
178
  } finally {
149
179
  ch.close();
150
180
  }
151
181
  }
152
182
 
153
- function fail(message, code) {
183
+ /**
184
+ * Print an error and set the exit code. Under --json it is also printed to
185
+ * stdout as {"error", "code"?}, so a program reading stdout sees why it failed.
186
+ */
187
+ function fail(message, exitCode, flags = {}, code = undefined) {
154
188
  console.error(message);
155
- process.exitCode = code;
189
+ if (flags.json) console.log(JSON.stringify({ error: message, ...(code ? { code } : {}) }));
190
+ process.exitCode = exitCode;
156
191
  }
@@ -1,25 +1,25 @@
1
1
  {
2
- "version": "0.4.1",
2
+ "version": "0.4.3",
3
3
  "targets": {
4
4
  "darwin-arm64": {
5
5
  "file": "oalo-coord-darwin-arm64.gz",
6
- "sha256": "83bca933ccbc22511fa1bf506dc7fe39731a46da59efb354f4a2e45bc80d6b3c",
7
- "bytes": 24851980
6
+ "sha256": "cc0685ae983b04ca73fe8451c64ced465a894e15385ec10a9dc3be2ecf4d356c",
7
+ "bytes": 24853827
8
8
  },
9
9
  "darwin-x64": {
10
10
  "file": "oalo-coord-darwin-x64.gz",
11
- "sha256": "6ba7d6b98f0ac541e6eca0f649c7c4110cbbf2bcc7fb0bcfa8fc9d708629c9d0",
12
- "bytes": 26990319
11
+ "sha256": "565c6ca3d5c783625ce4e45ce3369e1c04d09c539225b291ff5c18abd4e891eb",
12
+ "bytes": 26992076
13
13
  },
14
14
  "linux-x64": {
15
15
  "file": "oalo-coord-linux-x64.gz",
16
- "sha256": "43312caa34706ca12b502678936c12940c3d7495960841546e2935ec543b6117",
17
- "bytes": 36882974
16
+ "sha256": "a7fdc3119120ea386f1e748d31cf29530e7f7edb4d65f0c32f7dcd19e8552e8f",
17
+ "bytes": 36884995
18
18
  },
19
19
  "linux-arm64": {
20
20
  "file": "oalo-coord-linux-arm64.gz",
21
- "sha256": "64a426d6bfc9e646f12b9d6c1edd0b62f3830f33718b55e6232e92379255c9f8",
22
- "bytes": 37123721
21
+ "sha256": "6e088ca338ccef4bff2f01fb5ceb2de3e127946c9d4c17685771922074968daa",
22
+ "bytes": 37125644
23
23
  }
24
24
  }
25
25
  }
package/src/data.js CHANGED
@@ -330,7 +330,9 @@ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
330
330
  * Saved per workspace with the tables it covers. When a write needs a table it
331
331
  * doesn't cover, a new token is made for the old tables plus the new one and
332
332
  * the old token is revoked, so there is one write token per workspace, limited
333
- * to the tables this machine has written. It expires after 30 days.
333
+ * to the tables this machine has written. It expires after 30 days. Every use
334
+ * logs the tables it covers, since any project on this machine may have
335
+ * widened it.
334
336
  *
335
337
  * `channel` is a connected OaloChannel on the CLI token. `log` reports what was
336
338
  * created, since making a credential should never be silent.
@@ -339,7 +341,12 @@ export async function writeTokenFor(serverUrl, tables, channel, { log = () => {}
339
341
  const saved = readEntry(serverUrl)?.sync_write;
340
342
  const covered = new Set(saved?.tables || []);
341
343
  const live = saved?.token && (!saved.expires_at || Date.parse(saved.expires_at) > now + 60_000);
342
- if (live && tables.every((t) => covered.has(t))) return saved.token;
344
+ // The token is shared by every project on this machine for this workspace,
345
+ // so say what it can write each time it is used.
346
+ if (live && tables.every((t) => covered.has(t))) {
347
+ log(`write token covers: ${[...covered].sort().join(", ")}`);
348
+ return saved.token;
349
+ }
343
350
 
344
351
  const all = [...new Set([...(live ? covered : []), ...tables])].sort();
345
352
  const expires_at = new Date(now + WRITE_TOKEN_DAYS * 86_400_000).toISOString();
@@ -351,7 +358,8 @@ export async function writeTokenFor(serverUrl, tables, channel, { log = () => {}
351
358
  if (!minted?.token) throw new Error("the workspace did not return a token");
352
359
 
353
360
  writeToken({ serverUrl, appId: null }, minted.token, "sync_write", { id: minted.id, tables: all, expires_at });
354
- log(`made a write token for ${all.join(", ")} (expires ${expires_at.slice(0, 10)}). See it with \`oalo tokens list\`.`);
361
+ const until = `(expires ${expires_at.slice(0, 10)}). See it with \`oalo tokens list\`.`;
362
+ log(live ? `widened the write token. It covers: ${all.join(", ")} ${until}` : `made a write token for ${all.join(", ")} ${until}`);
355
363
 
356
364
  if (saved?.id && saved.id !== minted.id) {
357
365
  try {
package/src/graphfiles.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, unlinkSync } from "node:fs";
2
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, unlinkSync, statSync } from "node:fs";
3
3
  import { join, dirname, relative } from "node:path";
4
4
 
5
5
  /**
@@ -30,6 +30,7 @@ export const ROOT = ".oalo";
30
30
  export const FLOW_FIELDS = [
31
31
  "name",
32
32
  "description",
33
+ "goal",
33
34
  "enabled",
34
35
  "trigger",
35
36
  "trigger_instructions",
@@ -60,7 +61,7 @@ export const TOOL_FIELDS = ["description", "input_schema", "output_schema"];
60
61
  const ABOUT = {
61
62
  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
63
  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`.",
64
+ 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
65
  };
65
66
 
66
67
  /** JSON with object keys sorted at every level, so equal content hashes equal. */
@@ -101,6 +102,10 @@ export const catalogPath = (surface, cwd = process.cwd()) => join(cwd, ROOT, "ca
101
102
  /** A flow as the server returned it -> the file we keep. */
102
103
  export function flowFile(remote, bot) {
103
104
  const flow = pick(remote, FLOW_FIELDS);
105
+ // The server sends a Decimal as a string ("0.50"); keep the file a number.
106
+ if (typeof flow.max_cost_usd === "string" && flow.max_cost_usd.trim() !== "" && Number.isFinite(Number(flow.max_cost_usd))) {
107
+ flow.max_cost_usd = Number(flow.max_cost_usd);
108
+ }
104
109
  return { $about: ABOUT.flow, kind: "flow", bot, id: remote.id, version: remote.version ?? null, base_hash: hashOf(flow), flow };
105
110
  }
106
111
 
@@ -111,7 +116,7 @@ export function flowFile(remote, bot) {
111
116
  * ones a teammate added since.
112
117
  */
113
118
  export function loopFile(remote, triggers) {
114
- const loop = pick(remote, LOOP_FIELDS);
119
+ const loop = withoutInertLegacyTrigger(pick(remote, LOOP_FIELDS));
115
120
  const file = {
116
121
  $about: ABOUT.loop,
117
122
  kind: "loop",
@@ -129,6 +134,20 @@ export function loopFile(remote, triggers) {
129
134
  return file;
130
135
  }
131
136
 
137
+ /**
138
+ * The legacy single trigger (`trigger_type`, `trigger_event`, `trigger_filter`,
139
+ * `cron`) when it starts nothing: the column defaults to "cron" with no
140
+ * schedule, which read as "runs on a schedule" on a loop that an app calls
141
+ * (found by the CLI trial). Left out of the file; a save without any of the
142
+ * three keeps what is stored (Loops), so nothing changes on the server.
143
+ */
144
+ export function withoutInertLegacyTrigger(loop) {
145
+ const blank = (v) => v === null || v === undefined || v === "";
146
+ if (loop.trigger_type !== "cron" || !blank(loop.cron) || !blank(loop.trigger_event) || !blank(loop.trigger_filter)) return loop;
147
+ const { trigger_type, trigger_event, trigger_filter, cron, ...rest } = loop;
148
+ return rest;
149
+ }
150
+
132
151
  /** A trigger as listed, without empty keys. */
133
152
  export function cleanTrigger(t) {
134
153
  return Object.fromEntries(Object.entries(t || {}).filter(([, v]) => v !== null && v !== undefined));
@@ -250,6 +269,44 @@ export function removeFile(path) {
250
269
  // aid, not a file to push.
251
270
  const isGraphFile = (f) => f.endsWith(".json") && !f.endsWith(".server.json");
252
271
 
272
+ /**
273
+ * The files a command was given, with each directory expanded to the flow,
274
+ * loop and tool files anywhere inside it (`oalo lint .oalo/loops`). A JSON
275
+ * file in a directory that isn't one (a node catalog) is skipped; one that
276
+ * doesn't parse is kept, so the command reports it. Files named directly are
277
+ * kept as they are.
278
+ */
279
+ export function expandTargets(paths) {
280
+ const out = [];
281
+ for (const p of paths) {
282
+ if (existsSync(p) && statSync(p).isDirectory()) out.push(...graphFilesIn(p));
283
+ else out.push(p);
284
+ }
285
+ return [...new Set(out)];
286
+ }
287
+
288
+ const SKIP_DIRS = new Set(["node_modules", ".git"]);
289
+
290
+ function graphFilesIn(dir) {
291
+ const out = [];
292
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
293
+ const p = join(dir, e.name);
294
+ if (e.isDirectory()) {
295
+ if (!SKIP_DIRS.has(e.name)) out.push(...graphFilesIn(p));
296
+ } else if (e.isFile() && isGraphFile(e.name)) {
297
+ let kind;
298
+ try {
299
+ kind = JSON.parse(readFileSync(p, "utf8"))?.kind;
300
+ } catch {
301
+ out.push(p);
302
+ continue;
303
+ }
304
+ if (["flow", "loop", "tool"].includes(kind)) out.push(p);
305
+ }
306
+ }
307
+ return out.sort();
308
+ }
309
+
253
310
  /** Every flow and loop file under .oalo/, as absolute paths. */
254
311
  export function listGraphFiles(cwd = process.cwd()) {
255
312
  const out = [];