@oalo-ai/cli 0.4.2 → 0.4.4
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 +171 -27
- package/package.json +1 -1
- package/plugin/skills/oalo/SKILL.md +30 -7
- package/src/bot-settings.json +62 -0
- package/src/commands/bots.js +40 -3
- package/src/commands/call.js +66 -16
- package/src/commands/deploy.js +25 -2
- package/src/commands/docs.js +3 -1
- package/src/commands/emit.js +25 -6
- package/src/commands/env.js +5 -0
- package/src/commands/graphs.js +18 -7
- package/src/commands/incidents.js +24 -1
- package/src/commands/link.js +2 -0
- package/src/commands/login.js +2 -2
- package/src/commands/mcp.js +9 -26
- package/src/commands/qa.js +3 -0
- package/src/commands/run.js +19 -0
- package/src/commands/sources.js +30 -5
- package/src/commands/switches.js +68 -13
- package/src/commands/tokens.js +35 -1
- package/src/config.js +69 -6
- package/src/coord-release.json +9 -9
- package/src/data.js +14 -5
- package/src/graphfiles.js +44 -1
- package/src/help.js +96 -28
- package/src/mcp/describe.js +112 -0
- package/src/mcp/fit.js +94 -0
- package/src/mcp/tools.js +80 -29
- package/src/workspace.js +4 -3
package/src/commands/mcp.js
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
|
|
8
8
|
import { OaloChannel } from "../channel.js";
|
|
9
9
|
import { TOOLS, BY_NAME } from "../mcp/tools.js";
|
|
10
|
+
import { fitReply } from "../mcp/fit.js";
|
|
10
11
|
import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
|
|
11
12
|
import { CLI_VERSION } from "../server.js";
|
|
12
13
|
|
|
@@ -57,12 +58,7 @@ export async function mcp(flags) {
|
|
|
57
58
|
await ensureConnected();
|
|
58
59
|
let result;
|
|
59
60
|
|
|
60
|
-
if (spec.
|
|
61
|
-
result = await describe(oalo, url);
|
|
62
|
-
} else if (spec.raw) {
|
|
63
|
-
if (!args.event) throw new Error("event is required");
|
|
64
|
-
result = await oalo.call(args.event, args.params || {});
|
|
65
|
-
} else if (spec.run) {
|
|
61
|
+
if (spec.run) {
|
|
66
62
|
result = await spec.run(oalo, args, { cfg, url, token });
|
|
67
63
|
} else if (spec.route) {
|
|
68
64
|
const { event, params } = spec.route(args);
|
|
@@ -75,7 +71,13 @@ export async function mcp(flags) {
|
|
|
75
71
|
: await oalo.call(spec.event, params);
|
|
76
72
|
}
|
|
77
73
|
|
|
78
|
-
|
|
74
|
+
// Claude Code refuses a reply over its token limit and gives the agent a
|
|
75
|
+
// file path instead, so a long one is cut to fit, saying how to get the rest.
|
|
76
|
+
const text = fitReply(result, {
|
|
77
|
+
hint: spec.cutHint || "Ask for less: most tools take an id, a name, a filter or a limit.",
|
|
78
|
+
offset: Number(args.offset) || 0,
|
|
79
|
+
});
|
|
80
|
+
return { content: [{ type: "text", text }] };
|
|
79
81
|
} catch (err) {
|
|
80
82
|
// Surface failures as tool content, not protocol errors, so the agent can
|
|
81
83
|
// read the reason and correct itself instead of the call just blowing up.
|
|
@@ -104,22 +106,3 @@ export async function mcp(flags) {
|
|
|
104
106
|
await server.connect(new StdioServerTransport());
|
|
105
107
|
process.stderr.write(`oalo mcp: ready (${url})\n`);
|
|
106
108
|
}
|
|
107
|
-
|
|
108
|
-
/** One round trip for orientation, so an agent does not burn three tool calls. */
|
|
109
|
-
async function describe(oalo, url) {
|
|
110
|
-
const settle = async (p) => {
|
|
111
|
-
try {
|
|
112
|
-
return await p;
|
|
113
|
-
} catch (err) {
|
|
114
|
-
return { error: err.message };
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
const [apps, bots, loops] = await Promise.all([
|
|
119
|
-
settle(oalo.call("list_apps", {})),
|
|
120
|
-
settle(oalo.call("chat:bots:list", {})),
|
|
121
|
-
settle(oalo.call("loops:list_for_org", {})),
|
|
122
|
-
]);
|
|
123
|
-
|
|
124
|
-
return { workspace: url, apps, bots, loops };
|
|
125
|
-
}
|
package/src/commands/qa.js
CHANGED
|
@@ -25,6 +25,9 @@ function printTurn(t) {
|
|
|
25
25
|
if (extra.length) console.log(dim(` [${extra.join(", ")}]`));
|
|
26
26
|
}
|
|
27
27
|
if ((t.replies || []).length === 0) console.log(dim(" (no reply)"));
|
|
28
|
+
if ((t.tools || []).length) {
|
|
29
|
+
console.log(dim(` called: ${t.tools.map((x) => (x.status === "success" ? x.tool : `${x.tool} (${x.status})`)).join(", ")}`));
|
|
30
|
+
}
|
|
28
31
|
for (const f of t.flows || []) {
|
|
29
32
|
console.log(dim(` flow ${f.flow}: ${f.status} at ${f.at}${f.waiting_for ? `, waiting for ${f.waiting_for}` : ""}`));
|
|
30
33
|
}
|
package/src/commands/run.js
CHANGED
|
@@ -81,6 +81,25 @@ export async function run(flags, rest) {
|
|
|
81
81
|
const params = { name, env: flags.env || env };
|
|
82
82
|
// A loop pinned to one app: by slug (`oalo apps`) or id.
|
|
83
83
|
if (typeof flags.app === "string") params.app_id = await appIdFor(ch, flags.app);
|
|
84
|
+
// What the run starts with: --payload as an event's payload
|
|
85
|
+
// ({{trigger.payload.x}}), or --input as the trigger's whole output.
|
|
86
|
+
for (const key of ["payload", "input"]) {
|
|
87
|
+
if (flags[key] === undefined) continue;
|
|
88
|
+
let v;
|
|
89
|
+
try {
|
|
90
|
+
v = JSON.parse(String(flags[key]));
|
|
91
|
+
} catch (e) {
|
|
92
|
+
console.error(`--${key} must be a JSON object: ${e.message}`);
|
|
93
|
+
process.exitCode = 2;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) {
|
|
97
|
+
console.error(`--${key} must be a JSON object`);
|
|
98
|
+
process.exitCode = 2;
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
params[key] = v;
|
|
102
|
+
}
|
|
84
103
|
|
|
85
104
|
const reply = await ch.call("loops:run_now", params);
|
|
86
105
|
const runId = reply?.run_id ?? reply?.["run_id"];
|
package/src/commands/sources.js
CHANGED
|
@@ -19,6 +19,7 @@ import { dim } from "../events.js";
|
|
|
19
19
|
* oalo sources create <name> --from-postgres <url> --relation <schema.view> [--key c] [--cursor c] [--every m] [--now]
|
|
20
20
|
* oalo sources push <name> <file.csv|.json|.jsonl>
|
|
21
21
|
* oalo sources push <name> <doc.pdf> [more...] into a knowledge source
|
|
22
|
+
* oalo sources push <name> <docs...> --prune and remove the documents not sent
|
|
22
23
|
* oalo sources remove <name> <document> a knowledge source's document
|
|
23
24
|
* oalo sources fetch <name> <url> [--every 60] [--header "Name: value"]... [--records-at a.b] [--document name]
|
|
24
25
|
* oalo sources fetch <name> --now | --off Oalo fetches the address instead of a sender posting
|
|
@@ -88,7 +89,7 @@ const USAGE = [
|
|
|
88
89
|
" oalo sources fields <name> a,b | retention <name> <days|off>",
|
|
89
90
|
" oalo sources create <name> --bot <bot> [--auth ...] documents into the bot's knowledge",
|
|
90
91
|
" oalo sources create <name> --from-postgres <postgres url> --relation <schema.view> [--key <column>] [--cursor <column>] [--every <minutes>] [--now]",
|
|
91
|
-
" oalo sources push <name> <file.csv|.json|.jsonl> or, for --bot, <doc.pdf|.docx|.md|.html|.txt> ...",
|
|
92
|
+
" oalo sources push <name> <file.csv|.json|.jsonl> or, for --bot, <doc.pdf|.docx|.md|.html|.txt> ... [--prune]",
|
|
92
93
|
" oalo sources remove <name> <document>",
|
|
93
94
|
" oalo sources fetch <name> <https url> [--every <minutes>] [--header \"Name: value\"] [--records-at <a.b>] [--document <name>]",
|
|
94
95
|
" oalo sources fetch <name> --now | --off",
|
|
@@ -106,13 +107,13 @@ async function list(ch, flags) {
|
|
|
106
107
|
console.log(`${s.name} ${dim(`-> ${s.bot}'s knowledge, ${s.auth}, ${s.received_count} documents sent${s.last_received_at ? `, last ${s.last_received_at}` : ""}`)}`);
|
|
107
108
|
continue;
|
|
108
109
|
}
|
|
109
|
-
console.log(`${s.name} ${dim(`-> ${s.table} (${s.env}), ${s.mode}, ${s.auth}, ${s.received_count}
|
|
110
|
+
console.log(`${s.name} ${dim(`-> ${s.table} (${s.env}), ${s.mode}, ${s.auth}, ${s.received_count} record${s.received_count === 1 ? "" : "s"} received${s.last_received_at ? `, last ${s.last_received_at}` : ""}`)}`);
|
|
110
111
|
}
|
|
111
112
|
}
|
|
112
113
|
|
|
113
114
|
async function create(ch, name, flags) {
|
|
114
115
|
const params = { name };
|
|
115
|
-
for (const [flag, key] of [["bot", "bot"], ["table", "table"], ["id-field", "id_field"], ["mode", "mode"], ["auth", "auth"], ["env", "env"], ["hmac-header", "hmac_header"], ["hmac-format", "hmac_format"]]) {
|
|
116
|
+
for (const [flag, key] of [["bot", "bot"], ["table", "table"], ["id-field", "id_field"], ["mode", "mode"], ["auth", "auth"], ["env", "env"], ["hmac-header", "hmac_header"], ["hmac-format", "hmac_format"], ["records-at", "records_at"]]) {
|
|
116
117
|
if (flags[flag] === true) return fail(`--${flag} needs a value`, 2);
|
|
117
118
|
if (typeof flags[flag] === "string") params[key] = flags[flag];
|
|
118
119
|
}
|
|
@@ -175,11 +176,14 @@ async function create(ch, name, flags) {
|
|
|
175
176
|
if (s.keep_from_ai?.length) console.log(` kept from AI ${s.keep_from_ai.join(", ")}`);
|
|
176
177
|
if (s.retention_days) console.log(` retention rows not sent in ${s.retention_days} days are dropped`);
|
|
177
178
|
console.log(` id field ${s.id_field}${s.mode === "snapshot" ? ", snapshot (each upload is the whole set)" : ""}`);
|
|
179
|
+
if (s.records_at) console.log(` records at ${s.records_at} (each record is read from there in what's sent)`);
|
|
180
|
+
if (s.auth === "hmac") console.log(` signature header ${s.hmac_header}, ${s.hmac_format}`);
|
|
178
181
|
console.log(` address ${s.url}`);
|
|
179
182
|
console.log(` secret ${s.secret}`);
|
|
180
183
|
console.log(dim("\nThe secret is shown only now. Keep it where the sender keeps secrets; `oalo sources rotate` replaces it."));
|
|
181
184
|
console.log(dim(sendExample(s)));
|
|
182
185
|
console.log(dim(`Fields a sender adds that aren't listed above are dropped, and each upload says which. A workflow can start on ${s.event}.`));
|
|
186
|
+
for (const w of s.warnings || []) console.error(`warning: ${w}`);
|
|
183
187
|
}
|
|
184
188
|
|
|
185
189
|
function sendExample(s) {
|
|
@@ -247,11 +251,29 @@ async function pushDocuments(ch, name, files, flags, opts = {}) {
|
|
|
247
251
|
failed++;
|
|
248
252
|
}
|
|
249
253
|
}
|
|
254
|
+
// --prune: the files sent are the whole set, so a document the source has
|
|
255
|
+
// and they don't is removed. Skipped when a file failed, so a bad upload
|
|
256
|
+
// never removes the page it was replacing.
|
|
257
|
+
let pruneNote = null;
|
|
258
|
+
if (flags.prune && failed) {
|
|
259
|
+
pruneNote = `not pruning: ${failed} file${failed === 1 ? "" : "s"} failed, so nothing was removed`;
|
|
260
|
+
} else if (flags.prune) {
|
|
261
|
+
const sent = new Set(files.map((f) => basename(f).trim()));
|
|
262
|
+
const { documents = [] } = await ch.call("sources:get", { name });
|
|
263
|
+
for (const d of documents) {
|
|
264
|
+
if (sent.has(d.name)) continue;
|
|
265
|
+
const r = await ch.call("sources:remove_document", { name, document: d.name });
|
|
266
|
+
if (r.removed) results.push({ document: d.name, removed: true });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
250
270
|
if (failed) process.exitCode = 1;
|
|
251
271
|
if (flags.json) return void console.log(JSON.stringify(results, null, 2));
|
|
252
272
|
for (const r of results) {
|
|
253
|
-
|
|
273
|
+
if (r.removed) console.log(`${r.document}: removed (not in the files sent)`);
|
|
274
|
+
else console.log(r.error ? `${r.document}: refused: ${r.error}` : `${r.document}: ${r.replaced ? "replaced" : "added"}, ${r.chars} characters, indexing`);
|
|
254
275
|
}
|
|
276
|
+
if (pruneNote) console.log(pruneNote);
|
|
255
277
|
}
|
|
256
278
|
|
|
257
279
|
// Oalo fetches the address on a schedule. The header's value goes to the
|
|
@@ -327,7 +349,9 @@ async function show(ch, name, flags) {
|
|
|
327
349
|
if (s.retention_days) console.log(` retention ${s.retention_days} days`);
|
|
328
350
|
console.log(` event ${s.event}`);
|
|
329
351
|
printFetch(s.fetch);
|
|
330
|
-
|
|
352
|
+
// received_count counts every record sent, re-sends of a row included, so
|
|
353
|
+
// it is not the table's row count.
|
|
354
|
+
console.log(` received ${s.received_count} record${s.received_count === 1 ? "" : "s"} in all${s.last_received_at ? `, last ${s.last_received_at}` : ""} ${dim(`(a re-sent row counts again; \`oalo data list ${s.table} --env ${s.env}\` has the rows)`)}`);
|
|
331
355
|
if (s.log?.length) {
|
|
332
356
|
console.log("\nRecent arrivals:");
|
|
333
357
|
for (const l of s.log) {
|
|
@@ -342,6 +366,7 @@ async function push(ch, name, files, flags, opts = {}) {
|
|
|
342
366
|
if (!file) return fail(`usage: oalo sources push ${name} <file.csv|.json|.jsonl> (a knowledge source: <doc> [more...])`, 2);
|
|
343
367
|
const s = await ch.call("sources:get", { name });
|
|
344
368
|
if (s.kind === "knowledge") return pushDocuments(ch, name, files, flags, opts);
|
|
369
|
+
if (flags.prune) return fail(`--prune is for a knowledge source's documents. A table source made with --mode snapshot drops missing rows itself`, 2);
|
|
345
370
|
if (files.length > 1) return fail(`${name} takes records: push one file at a time`, 2);
|
|
346
371
|
const records = parseRecords(readFileSync(file, "utf8"), { name: basename(file) });
|
|
347
372
|
if (records.length === 0) return fail(`${file} has no records`, 2);
|
package/src/commands/switches.js
CHANGED
|
@@ -21,7 +21,7 @@ export async function loops(flags, rest, opts = {}) {
|
|
|
21
21
|
if (sub === "runs") return runs(flags, name, opts);
|
|
22
22
|
if (sub === "list") return list(flags, opts);
|
|
23
23
|
if (!["test", "on", "off", "delete"].includes(sub) || !name) {
|
|
24
|
-
return fail("usage: oalo loops list, 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);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
let input;
|
|
@@ -29,11 +29,11 @@ export async function loops(flags, rest, opts = {}) {
|
|
|
29
29
|
try {
|
|
30
30
|
input = readInput(flags.input);
|
|
31
31
|
} catch (e) {
|
|
32
|
-
return fail(e.message, 2);
|
|
32
|
+
return fail(e.message, 2, flags);
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
if (flags.sample !== undefined && !["latest", "example"].includes(flags.sample)) {
|
|
36
|
-
return fail("--sample is latest or example", 2);
|
|
36
|
+
return fail("--sample is latest or example", 2, flags);
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
return withChannel(flags, opts, async (ch) => {
|
|
@@ -60,7 +60,7 @@ export async function loops(flags, rest, opts = {}) {
|
|
|
60
60
|
export async function flows(flags, rest, opts = {}) {
|
|
61
61
|
const [, sub, bot, flow] = rest;
|
|
62
62
|
if (!["on", "off", "delete"].includes(sub) || !bot || !flow) {
|
|
63
|
-
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);
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
return withChannel(flags, opts, async (ch) => {
|
|
@@ -96,7 +96,7 @@ async function runs(flags, name, opts) {
|
|
|
96
96
|
const r = await ch.call("loops:get_run", { run_id: Number(flags.id) });
|
|
97
97
|
if (flags.json) return void console.log(JSON.stringify(r, null, 2));
|
|
98
98
|
const run = r.run || {};
|
|
99
|
-
console.log(`${run.name} run ${run.id}: ${run.status}${run.error ? `: ${oneLine(run.error)}` : ""} ${dim(`(${run.trigger || "?"}, ${
|
|
99
|
+
console.log(`${run.name} run ${run.id}: ${run.status}${run.error ? `: ${oneLine(run.error)}` : ""} ${dim(`(${run.trigger || "?"}, ${utc(run.started_at, true)})`)}`);
|
|
100
100
|
for (const n of r.nodes || []) {
|
|
101
101
|
console.log(` ${n.node_id} ${dim(`(${n.node_type}${n.status ? `, ${n.status}` : ""})`)}`);
|
|
102
102
|
const out = n.error || n.output;
|
|
@@ -109,7 +109,7 @@ async function runs(flags, name, opts) {
|
|
|
109
109
|
if (flags.json) return void console.log(JSON.stringify(r.runs, null, 2));
|
|
110
110
|
if (!r.runs?.length) return void console.log(name ? `no runs of ${name} yet` : "no loop runs yet");
|
|
111
111
|
for (const x of r.runs) {
|
|
112
|
-
const when =
|
|
112
|
+
const when = utc(x.started_at);
|
|
113
113
|
const test = x.rehearsal ? ", test" : "";
|
|
114
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}`)}`);
|
|
115
115
|
}
|
|
@@ -123,10 +123,54 @@ function printTest(r) {
|
|
|
123
123
|
const tag = s.error ? "failed" : s.simulated ? "simulated" : "ran";
|
|
124
124
|
const ms = Number.isFinite(s.duration_ms) ? `, ${s.duration_ms} ms` : "";
|
|
125
125
|
console.log(` ${s.node_id} ${dim(`(${s.type}, ${tag}${ms})`)}`);
|
|
126
|
-
|
|
127
|
-
|
|
126
|
+
if (s.error) {
|
|
127
|
+
console.log(dim(` ${clip(s.error)}`));
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const message = messageParts(s.output);
|
|
131
|
+
if (message) {
|
|
132
|
+
// A message step (email, WhatsApp, team chat, ...): what it would send,
|
|
133
|
+
// whole, since checking that text is why the test was run.
|
|
134
|
+
for (const [key, text] of message.texts) console.log(` ${key}: ${indentRest(text, " ")}`);
|
|
135
|
+
if (Object.keys(message.rest).length) console.log(dim(` ${clip(message.rest)}`));
|
|
136
|
+
} else if (s.output !== undefined && s.output !== null) {
|
|
137
|
+
console.log(dim(` ${clip(s.output)}`));
|
|
138
|
+
}
|
|
128
139
|
}
|
|
129
|
-
if (r.final_output !== undefined && r.final_output !== null) console.log(`output: ${
|
|
140
|
+
if (r.final_output !== undefined && r.final_output !== null) console.log(`output: ${clip(r.final_output)}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// The params a simulated send would have used that hold the message itself.
|
|
144
|
+
const MESSAGE_KEYS = ["subject", "title", "text", "body", "message", "content", "html", "caption", "note"];
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* A simulated step's message text, `{texts: [[key, text]], rest}`, or null
|
|
148
|
+
* when the output isn't a simulated send with a text param.
|
|
149
|
+
*/
|
|
150
|
+
export function messageParts(output) {
|
|
151
|
+
if (!output || typeof output !== "object" || output.simulated !== true) return null;
|
|
152
|
+
const params = output.params && typeof output.params === "object" ? output.params : {};
|
|
153
|
+
const texts = MESSAGE_KEYS.filter((k) => typeof params[k] === "string" && params[k].trim()).map((k) => [k, params[k]]);
|
|
154
|
+
if (!texts.length) return null;
|
|
155
|
+
const rest = Object.fromEntries(Object.entries(params).filter(([k]) => !texts.some(([t]) => t === k)));
|
|
156
|
+
return { texts, rest: output.action ? { action: output.action, ...rest } : rest };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function indentRest(text, pad) {
|
|
160
|
+
return String(text).replace(/\r?\n/g, `\n${pad}`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A run's start time as "2026-11-07 08:00 UTC" (with seconds when asked). The
|
|
165
|
+
* server's times are UTC; one without a zone is read as UTC too.
|
|
166
|
+
*/
|
|
167
|
+
export function utc(ts, seconds = false) {
|
|
168
|
+
if (!ts) return "?";
|
|
169
|
+
const s = String(ts);
|
|
170
|
+
const zoned = /(Z|[+-]\d\d:?\d\d)$/i.test(s);
|
|
171
|
+
const d = new Date(zoned ? s : `${s}Z`);
|
|
172
|
+
if (Number.isNaN(d.getTime())) return s;
|
|
173
|
+
return `${d.toISOString().slice(0, seconds ? 19 : 16).replace("T", " ")} UTC`;
|
|
130
174
|
}
|
|
131
175
|
|
|
132
176
|
function oneLine(v) {
|
|
@@ -134,6 +178,12 @@ function oneLine(v) {
|
|
|
134
178
|
return text.length > 300 ? text.slice(0, 300) + "..." : text;
|
|
135
179
|
}
|
|
136
180
|
|
|
181
|
+
/** A test step's output on one line, up to 2,000 characters, saying what was left out. */
|
|
182
|
+
export function clip(v, max = 2000) {
|
|
183
|
+
const text = typeof v === "string" ? v : JSON.stringify(v);
|
|
184
|
+
return text.length > max ? `${text.slice(0, max)}... (${text.length - max} more chars, --json for all)` : text;
|
|
185
|
+
}
|
|
186
|
+
|
|
137
187
|
/** `--input '{"type": ...}'` or `--input @event.json`. */
|
|
138
188
|
function readInput(raw) {
|
|
139
189
|
if (raw === true) throw new Error("--input needs JSON, or @file.json");
|
|
@@ -154,20 +204,25 @@ async function pinnedApp(ch, flags) {
|
|
|
154
204
|
async function withChannel(flags, opts, fn) {
|
|
155
205
|
const cfg = resolveConfig(flags);
|
|
156
206
|
const { url, token } = controlPlane(cfg);
|
|
157
|
-
if (!url || !token) return fail(`this needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
|
|
207
|
+
if (!url || !token) return fail(`this needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2, flags);
|
|
158
208
|
|
|
159
209
|
const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
|
|
160
210
|
try {
|
|
161
211
|
await ch.connect();
|
|
162
212
|
await fn(ch);
|
|
163
213
|
} catch (e) {
|
|
164
|
-
fail(e.message, 1);
|
|
214
|
+
fail(e.message, 1, flags, e.code);
|
|
165
215
|
} finally {
|
|
166
216
|
ch.close();
|
|
167
217
|
}
|
|
168
218
|
}
|
|
169
219
|
|
|
170
|
-
|
|
220
|
+
/**
|
|
221
|
+
* Print an error and set the exit code. Under --json it is also printed to
|
|
222
|
+
* stdout as {"error", "code"?}, so a program reading stdout sees why it failed.
|
|
223
|
+
*/
|
|
224
|
+
function fail(message, exitCode, flags = {}, code = undefined) {
|
|
171
225
|
console.error(message);
|
|
172
|
-
|
|
226
|
+
if (flags.json) console.log(JSON.stringify({ error: message, ...(code ? { code } : {}) }));
|
|
227
|
+
process.exitCode = exitCode;
|
|
173
228
|
}
|
package/src/commands/tokens.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { OaloChannel } from "../channel.js";
|
|
2
|
-
import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
|
|
2
|
+
import { resolve as resolveConfig, controlPlane, readToken, HOW_TO_CONNECT } from "../config.js";
|
|
3
|
+
import { listModels } from "../data.js";
|
|
3
4
|
import { dim } from "../events.js";
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -49,6 +50,12 @@ export async function tokens(flags, rest) {
|
|
|
49
50
|
process.exitCode = 2;
|
|
50
51
|
return;
|
|
51
52
|
}
|
|
53
|
+
// A table scope only works on an Oalo data model (what `oalo data models`
|
|
54
|
+
// lists): the Sync API can't serve a plain table, such as one `oalo db
|
|
55
|
+
// restore` made, so a token for one could never read it. Warn when the
|
|
56
|
+
// workspace's model list says so; skip the check when it can't be read.
|
|
57
|
+
const models = await modelNames(url, cfg);
|
|
58
|
+
for (const line of tableScopeWarnings(scopes, models)) console.error(line);
|
|
52
59
|
const days = Number(flags.days || 90);
|
|
53
60
|
const expires_at = days > 0 ? new Date(Date.now() + days * 86_400_000).toISOString() : undefined;
|
|
54
61
|
const r = await ch.call("sync_api:create_token", { name: flags.name, scopes, ...(expires_at ? { expires_at } : {}) });
|
|
@@ -83,3 +90,30 @@ export async function tokens(flags, rest) {
|
|
|
83
90
|
ch.close();
|
|
84
91
|
}
|
|
85
92
|
}
|
|
93
|
+
|
|
94
|
+
/** The workspace's data model names, or null when they can't be read (no data token, an older Base). */
|
|
95
|
+
async function modelNames(url, cfg) {
|
|
96
|
+
const token = (cfg.serverUrl === url && cfg.token) || readToken({ serverUrl: url, appId: cfg.appId }, "sync");
|
|
97
|
+
if (!token) return null;
|
|
98
|
+
try {
|
|
99
|
+
const m = await listModels({ serverUrl: url, token, env: "dev" });
|
|
100
|
+
return m?.models ? Object.keys(m.models) : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** One warning per read:<table> / write:<table> scope naming no data model. */
|
|
107
|
+
export function tableScopeWarnings(scopes, models) {
|
|
108
|
+
if (!Array.isArray(models)) return [];
|
|
109
|
+
const known = new Set(models);
|
|
110
|
+
return scopes
|
|
111
|
+
.map((s) => /^(read|write):(.+)$/.exec(s))
|
|
112
|
+
.filter((m) => m && !known.has(m[2]))
|
|
113
|
+
.map(
|
|
114
|
+
(m) =>
|
|
115
|
+
`warning: ${m[0]} names no Oalo data model, so this token can't ${m[1]} it. Table scopes work only on data models (\`oalo data models\` lists them); ` +
|
|
116
|
+
`the Sync API can't serve a plain Postgres table, such as one made by \`oalo db restore\` or by the app itself. ` +
|
|
117
|
+
`To serve its rows over the Sync API, copy them into a data model (\`oalo data models create\`, then \`oalo data push\`); an app's server can read the table itself over DATABASE_URL.`,
|
|
118
|
+
);
|
|
119
|
+
}
|
package/src/config.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync, writeFileSync, mkdirSync, existsSync, appendFileSync, chmodSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { join, dirname } from "node:path";
|
|
3
|
+
import { join, dirname, parse, relative, resolve as resolvePath } from "node:path";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Two stores, deliberately split.
|
|
@@ -40,6 +40,61 @@ export function readConfig(cwd = process.cwd()) {
|
|
|
40
40
|
return readJson(join(cwd, PROJECT_CONFIG), null);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* The link that applies in `cwd`: its own .oalo/config.json, else the nearest
|
|
45
|
+
* one in a parent folder of the same git repository, as git finds its own
|
|
46
|
+
* folder. The walk stops at the repository's root (the folder holding .git):
|
|
47
|
+
* a folder above it, or a different repository nested in a linked folder, may
|
|
48
|
+
* belong to another workspace, and taking that link silently would send this
|
|
49
|
+
* project's deploys and writes there. It never reads the home folder, whose
|
|
50
|
+
* .oalo is the credential store. Returns {dir, config} or null.
|
|
51
|
+
*/
|
|
52
|
+
export function findConfig(cwd = process.cwd()) {
|
|
53
|
+
const own = readConfig(cwd);
|
|
54
|
+
if (own) return { dir: cwd, config: own };
|
|
55
|
+
const top = repoRoot(cwd);
|
|
56
|
+
if (!top) return null;
|
|
57
|
+
for (const dir of parents(cwd)) {
|
|
58
|
+
const config = readConfig(dir);
|
|
59
|
+
if (config) return { dir, config };
|
|
60
|
+
if (dir === top) break;
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The nearest linked folder above `cwd` that findConfig didn't use (it is
|
|
67
|
+
* outside this repository), for an error to point at. Never used as the link.
|
|
68
|
+
*/
|
|
69
|
+
export function nearestLinkAbove(cwd = process.cwd()) {
|
|
70
|
+
for (const dir of parents(cwd)) {
|
|
71
|
+
const config = readConfig(dir);
|
|
72
|
+
if (config?.serverUrl) return { dir, serverUrl: config.serverUrl };
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The folders above `cwd`, nearest first, stopping before the home folder
|
|
78
|
+
// (and OALO_HOME) and the filesystem root.
|
|
79
|
+
function* parents(cwd) {
|
|
80
|
+
const stops = new Set([resolvePath(homedir()), resolvePath(process.env.OALO_HOME || homedir())]);
|
|
81
|
+
let dir = resolvePath(cwd);
|
|
82
|
+
for (;;) {
|
|
83
|
+
const up = dirname(dir);
|
|
84
|
+
if (up === dir || stops.has(up) || up === parse(up).root) return;
|
|
85
|
+
dir = up;
|
|
86
|
+
yield dir;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The nearest folder at or above `cwd` holding .git (a folder, or a file in a
|
|
91
|
+
// worktree), below the home folder. Read from disk: no git process.
|
|
92
|
+
function repoRoot(cwd) {
|
|
93
|
+
if (existsSync(join(cwd, ".git"))) return resolvePath(cwd);
|
|
94
|
+
for (const dir of parents(cwd)) if (existsSync(join(dir, ".git"))) return dir;
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
43
98
|
export function writeConfig(config, cwd = process.cwd()) {
|
|
44
99
|
writeJson(join(cwd, PROJECT_CONFIG), config);
|
|
45
100
|
}
|
|
@@ -128,7 +183,7 @@ export function controlPlane(cfg) {
|
|
|
128
183
|
const saved = listWorkspaces("cli");
|
|
129
184
|
if (!cfg.serverUrl) {
|
|
130
185
|
const urls = [...new Set(saved.map((w) => w.serverUrl))];
|
|
131
|
-
if (urls.length > 1) throw new WhichWorkspace(urls);
|
|
186
|
+
if (urls.length > 1) throw new WhichWorkspace(urls, cfg.nearestLink);
|
|
132
187
|
}
|
|
133
188
|
const match = cfg.serverUrl ? saved.find((w) => w.serverUrl === cfg.serverUrl) : saved[0];
|
|
134
189
|
return { url: cfg.serverUrl || match?.serverUrl || null, token: match?.token || null };
|
|
@@ -136,11 +191,14 @@ export function controlPlane(cfg) {
|
|
|
136
191
|
|
|
137
192
|
/** Several workspaces are saved and nothing says which one a command is for. */
|
|
138
193
|
export class WhichWorkspace extends Error {
|
|
139
|
-
constructor(urls) {
|
|
194
|
+
constructor(urls, nearest = null) {
|
|
140
195
|
super(
|
|
141
196
|
"This machine has more than one workspace saved, and nothing here says which one to use:\n" +
|
|
142
197
|
urls.map((u) => ` ${u}`).join("\n") +
|
|
143
|
-
"\n\
|
|
198
|
+
"\n\n" +
|
|
199
|
+
(nearest
|
|
200
|
+
? `There is no .oalo/config.json in this folder or its repository. The nearest linked folder is ${nearest.dir} (${nearest.serverUrl}), but it is outside this repository, so its link isn't used here. If this project belongs to that workspace too, run \`oalo link --server ${nearest.serverUrl}\` here, or pass --server ${nearest.serverUrl}.`
|
|
201
|
+
: "Link this folder to one with `oalo link --server <url>`, or pass --server <url>, or set OALO_URL.")
|
|
144
202
|
);
|
|
145
203
|
this.code = "OALO_WHICH_WORKSPACE";
|
|
146
204
|
this.urls = urls;
|
|
@@ -164,12 +222,17 @@ export function ensureGitignored(cwd = process.cwd()) {
|
|
|
164
222
|
|
|
165
223
|
/** Resolve config + token, preferring explicit flags, then config, then env. */
|
|
166
224
|
export function resolve(flags = {}, cwd = process.cwd()) {
|
|
167
|
-
const
|
|
225
|
+
const found = findConfig(cwd);
|
|
226
|
+
const cfg = found?.config || {};
|
|
168
227
|
const serverUrl = flags.server || cfg.serverUrl || process.env.OALO_URL || null;
|
|
169
228
|
const appId = flags.app || cfg.appId || null;
|
|
170
229
|
const env = flags.env || cfg.env || "dev";
|
|
171
230
|
const base = { serverUrl, appId, env };
|
|
172
231
|
const token = flags.token || process.env.OALO_SYNC_TOKEN || readToken(base, "sync");
|
|
173
232
|
const cliToken = flags["cli-token"] || process.env.OALO_CLI_TOKEN || readToken(base, "cli");
|
|
174
|
-
|
|
233
|
+
// Nothing links this folder: remember the nearest link further up, so the
|
|
234
|
+
// "which workspace?" error can point at it (it is never used as the link).
|
|
235
|
+
const above = found || serverUrl ? null : nearestLinkAbove(cwd);
|
|
236
|
+
const nearestLink = above ? { dir: relative(cwd, above.dir), serverUrl: above.serverUrl } : null;
|
|
237
|
+
return { ...base, token, cliToken, schemaVersion: cfg.schemaVersion ?? null, ...(found ? { configDir: found.dir } : {}), ...(nearestLink ? { nearestLink } : {}) };
|
|
175
238
|
}
|
package/src/coord-release.json
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.4.
|
|
2
|
+
"version": "0.4.4",
|
|
3
3
|
"targets": {
|
|
4
4
|
"darwin-arm64": {
|
|
5
5
|
"file": "oalo-coord-darwin-arm64.gz",
|
|
6
|
-
"sha256": "
|
|
7
|
-
"bytes":
|
|
6
|
+
"sha256": "d82fe7975cbb4311857fde63f5926af07ff280cf01e8052a88cd9dadafcb1d11",
|
|
7
|
+
"bytes": 24855680
|
|
8
8
|
},
|
|
9
9
|
"darwin-x64": {
|
|
10
10
|
"file": "oalo-coord-darwin-x64.gz",
|
|
11
|
-
"sha256": "
|
|
12
|
-
"bytes":
|
|
11
|
+
"sha256": "ff9fc290777d89f6c3a573dc9d052e79818be3222518c0c7785a798eada11f15",
|
|
12
|
+
"bytes": 26994220
|
|
13
13
|
},
|
|
14
14
|
"linux-x64": {
|
|
15
15
|
"file": "oalo-coord-linux-x64.gz",
|
|
16
|
-
"sha256": "
|
|
17
|
-
"bytes":
|
|
16
|
+
"sha256": "91fa4f0fc1b37568efdba5893940a181634951b1efad6277facc9ea767f21f0c",
|
|
17
|
+
"bytes": 36886784
|
|
18
18
|
},
|
|
19
19
|
"linux-arm64": {
|
|
20
20
|
"file": "oalo-coord-linux-arm64.gz",
|
|
21
|
-
"sha256": "
|
|
22
|
-
"bytes":
|
|
21
|
+
"sha256": "f5e9746b60012649bdf60324ef6b0cbdf6bb63e4a61d99ce5c52819da01c7a73",
|
|
22
|
+
"bytes": 37127431
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
}
|
package/src/data.js
CHANGED
|
@@ -50,8 +50,9 @@ export function parseRecords(text, { format, name = "", types = false } = {}) {
|
|
|
50
50
|
|
|
51
51
|
if (fmt === "json") {
|
|
52
52
|
const data = JSON.parse(clean);
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
// An array of records, {"rows": [...]}, or one record on its own.
|
|
54
|
+
const rows = Array.isArray(data) ? data : Array.isArray(data?.rows) ? data.rows : data && typeof data === "object" ? [data] : null;
|
|
55
|
+
if (!rows) throw new Error("JSON input must be an object, an array of objects, or {\"rows\": [...]}");
|
|
55
56
|
return rows;
|
|
56
57
|
}
|
|
57
58
|
|
|
@@ -330,7 +331,9 @@ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
330
331
|
* Saved per workspace with the tables it covers. When a write needs a table it
|
|
331
332
|
* doesn't cover, a new token is made for the old tables plus the new one and
|
|
332
333
|
* 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.
|
|
334
|
+
* to the tables this machine has written. It expires after 30 days. Every use
|
|
335
|
+
* logs the tables it covers, since any project on this machine may have
|
|
336
|
+
* widened it.
|
|
334
337
|
*
|
|
335
338
|
* `channel` is a connected OaloChannel on the CLI token. `log` reports what was
|
|
336
339
|
* created, since making a credential should never be silent.
|
|
@@ -339,7 +342,12 @@ export async function writeTokenFor(serverUrl, tables, channel, { log = () => {}
|
|
|
339
342
|
const saved = readEntry(serverUrl)?.sync_write;
|
|
340
343
|
const covered = new Set(saved?.tables || []);
|
|
341
344
|
const live = saved?.token && (!saved.expires_at || Date.parse(saved.expires_at) > now + 60_000);
|
|
342
|
-
|
|
345
|
+
// The token is shared by every project on this machine for this workspace,
|
|
346
|
+
// so say what it can write each time it is used.
|
|
347
|
+
if (live && tables.every((t) => covered.has(t))) {
|
|
348
|
+
log(`write token covers: ${[...covered].sort().join(", ")}`);
|
|
349
|
+
return saved.token;
|
|
350
|
+
}
|
|
343
351
|
|
|
344
352
|
const all = [...new Set([...(live ? covered : []), ...tables])].sort();
|
|
345
353
|
const expires_at = new Date(now + WRITE_TOKEN_DAYS * 86_400_000).toISOString();
|
|
@@ -351,7 +359,8 @@ export async function writeTokenFor(serverUrl, tables, channel, { log = () => {}
|
|
|
351
359
|
if (!minted?.token) throw new Error("the workspace did not return a token");
|
|
352
360
|
|
|
353
361
|
writeToken({ serverUrl, appId: null }, minted.token, "sync_write", { id: minted.id, tables: all, expires_at });
|
|
354
|
-
|
|
362
|
+
const until = `(expires ${expires_at.slice(0, 10)}). See it with \`oalo tokens list\`.`;
|
|
363
|
+
log(live ? `widened the write token. It covers: ${all.join(", ")} ${until}` : `made a write token for ${all.join(", ")} ${until}`);
|
|
355
364
|
|
|
356
365
|
if (saved?.id && saved.id !== minted.id) {
|
|
357
366
|
try {
|