@edena-solutions/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/src/args.js +56 -0
- package/dist/src/cli.js +164 -0
- package/dist/src/commands/api.js +55 -0
- package/dist/src/commands/auth.js +115 -0
- package/dist/src/commands/docs.js +92 -0
- package/dist/src/commands/listen.js +155 -0
- package/dist/src/commands/logs.js +49 -0
- package/dist/src/commands/open.js +43 -0
- package/dist/src/commands/operation.js +216 -0
- package/dist/src/commands/skill.js +66 -0
- package/dist/src/config.js +105 -0
- package/dist/src/errors.js +53 -0
- package/dist/src/http.js +83 -0
- package/dist/src/output.js +83 -0
- package/dist/src/reference.js +181 -0
- package/dist/src/schema.js +213 -0
- package/dist/src/sse.js +98 -0
- package/dist/src/version.js +14 -0
- package/package.json +44 -4
- package/skill/SKILL.md +60 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createHmac, randomUUID } from "node:crypto";
|
|
2
|
+
import { flag, hasFlag } from "../args.js";
|
|
3
|
+
import { listenSecret, readConfig, resolveSession, saveForwardTo } from "../config.js";
|
|
4
|
+
import { EXIT, NotSignedInError, UsageError } from "../errors.js";
|
|
5
|
+
import { apiRequest } from "../http.js";
|
|
6
|
+
import { bold, dim, red, wantsJson } from "../output.js";
|
|
7
|
+
import { followStream, sinceOf } from "../sse.js";
|
|
8
|
+
/** The headers every delivery carries, as the API's webhooks send them. */
|
|
9
|
+
const HEADERS = { signature: "Edena-Signature", eventId: "Edena-Event-Id", eventType: "Edena-Event-Type", deliveryId: "Edena-Delivery-Id" };
|
|
10
|
+
/** `t=<unix seconds>,v1=<HMAC-SHA256 of "<t>.<body>">`: the same signature a real endpoint receives. */
|
|
11
|
+
export function signatureHeader(secret, body, timestamp = Math.floor(Date.now() / 1000)) {
|
|
12
|
+
return `t=${timestamp},v1=${createHmac("sha256", secret).update(`${timestamp}.${body}`, "utf8").digest("hex")}`;
|
|
13
|
+
}
|
|
14
|
+
const time = () => new Date().toTimeString().slice(0, 8);
|
|
15
|
+
/**
|
|
16
|
+
* Delivers one event to a local server the way a webhook endpoint gets it: the same body, byte for
|
|
17
|
+
* byte, and the same headers, signed with this machine's listen secret.
|
|
18
|
+
*/
|
|
19
|
+
async function forward(url, body, type, eventId, secret) {
|
|
20
|
+
const started = Date.now();
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetch(url, {
|
|
23
|
+
method: "POST",
|
|
24
|
+
headers: {
|
|
25
|
+
"Content-Type": "application/json",
|
|
26
|
+
"User-Agent": "Edena-Webhooks (edena listen)",
|
|
27
|
+
[HEADERS.signature]: signatureHeader(secret, body),
|
|
28
|
+
[HEADERS.eventId]: eventId,
|
|
29
|
+
[HEADERS.eventType]: type,
|
|
30
|
+
[HEADERS.deliveryId]: `cli_${randomUUID()}`,
|
|
31
|
+
},
|
|
32
|
+
body,
|
|
33
|
+
signal: AbortSignal.timeout(10_000),
|
|
34
|
+
});
|
|
35
|
+
await response.arrayBuffer().catch(() => undefined);
|
|
36
|
+
return { status: response.status, durationMs: Date.now() - started, error: null };
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
return { status: null, durationMs: Date.now() - started, error: error.message };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function printDelivery(json, type, eventId, result) {
|
|
43
|
+
if (json) {
|
|
44
|
+
process.stdout.write(`${JSON.stringify({ type, eventId, forward: result })}\n`);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const outcome = !result
|
|
48
|
+
? ""
|
|
49
|
+
: result.status === null
|
|
50
|
+
? red(`→ failed: ${result.error}`)
|
|
51
|
+
: result.status < 300
|
|
52
|
+
? `→ ${result.status} ${dim(`(${result.durationMs} ms)`)}`
|
|
53
|
+
: red(`→ ${result.status} (${result.durationMs} ms)`);
|
|
54
|
+
process.stdout.write(`${dim(time())} ${bold(type.padEnd(28))} ${dim(eventId)} ${outcome}\n`);
|
|
55
|
+
}
|
|
56
|
+
async function signedIn(args) {
|
|
57
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
58
|
+
if (!session.apiKey)
|
|
59
|
+
throw new NotSignedInError();
|
|
60
|
+
return session;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* `edena listen --forward-to http://localhost:3000/webhooks`: the organization's events as they happen,
|
|
64
|
+
* forwarded to a local server, so webhooks can be built without a public address. Without
|
|
65
|
+
* `--forward-to` it prints them. `--events client.*,invoice.updated` narrows them; `--since 1h`
|
|
66
|
+
* replays the last hour first.
|
|
67
|
+
*/
|
|
68
|
+
export async function listen(args) {
|
|
69
|
+
const session = await signedIn(args);
|
|
70
|
+
const secret = await listenSecret();
|
|
71
|
+
if (hasFlag(args, "printSecret")) {
|
|
72
|
+
process.stdout.write(`${secret}\n`);
|
|
73
|
+
return EXIT.ok;
|
|
74
|
+
}
|
|
75
|
+
const forwardTo = flag(args, "forwardTo");
|
|
76
|
+
if (forwardTo) {
|
|
77
|
+
if (!/^https?:\/\//.test(forwardTo))
|
|
78
|
+
throw new UsageError(`--forward-to takes a URL, not “${forwardTo}”.`);
|
|
79
|
+
await saveForwardTo(forwardTo);
|
|
80
|
+
}
|
|
81
|
+
const url = new URL(`${session.apiUrl}/webhook-events/stream`);
|
|
82
|
+
const events = flag(args, "events");
|
|
83
|
+
if (events)
|
|
84
|
+
url.searchParams.set("types", events);
|
|
85
|
+
const since = flag(args, "since");
|
|
86
|
+
if (since)
|
|
87
|
+
url.searchParams.set("since", sinceOf(since));
|
|
88
|
+
const json = wantsJson(hasFlag(args, "json"));
|
|
89
|
+
const where = session.profile ? `${session.profile.organization.name} (${session.profile.organization.environment})` : session.apiUrl;
|
|
90
|
+
const controller = new AbortController();
|
|
91
|
+
process.once("SIGINT", () => controller.abort());
|
|
92
|
+
await followStream({
|
|
93
|
+
url: url.toString(),
|
|
94
|
+
apiKey: session.apiKey,
|
|
95
|
+
signal: controller.signal,
|
|
96
|
+
onOpen: (reconnected) => {
|
|
97
|
+
if (reconnected || json)
|
|
98
|
+
return;
|
|
99
|
+
process.stderr.write(`Listening to ${bold(where)}${events ? ` (${events})` : ""}${forwardTo ? `, forwarding to ${bold(forwardTo)}` : ""}.\n` +
|
|
100
|
+
(forwardTo ? `Signing secret: ${secret}\n${dim("Verify Edena-Signature with it, as you would with an endpoint's secret.")}\n` : "") +
|
|
101
|
+
dim("Ctrl+C to stop.\n\n"));
|
|
102
|
+
},
|
|
103
|
+
onDisconnect: () => {
|
|
104
|
+
if (!json)
|
|
105
|
+
process.stderr.write(dim("Connection lost; reconnecting…\n"));
|
|
106
|
+
},
|
|
107
|
+
onMessage: async (message) => {
|
|
108
|
+
if (message.event !== "event")
|
|
109
|
+
return;
|
|
110
|
+
const event = JSON.parse(message.data);
|
|
111
|
+
const result = forwardTo ? await forward(forwardTo, message.data, event.type, event.id, secret) : null;
|
|
112
|
+
if (!forwardTo && json)
|
|
113
|
+
process.stdout.write(`${message.data}\n`);
|
|
114
|
+
else
|
|
115
|
+
printDelivery(json, event.type, event.id, result);
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
return EXIT.ok;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* `edena trigger client.updated`: sends an event of that type to the local server `edena listen` forwards
|
|
122
|
+
* to (or `--forward-to`), without changing any data. It resends the organization's latest real event of
|
|
123
|
+
* the type, so the body is a true one; `--event <id>` resends a given one.
|
|
124
|
+
*/
|
|
125
|
+
export async function trigger(args) {
|
|
126
|
+
const session = await signedIn(args);
|
|
127
|
+
const type = args.positionals[1];
|
|
128
|
+
const eventId = flag(args, "event");
|
|
129
|
+
if (!type && !eventId)
|
|
130
|
+
throw new UsageError("Which event?", "Usage: edena trigger <type> or edena trigger --event <id>. Types: edena webhook-events types");
|
|
131
|
+
const forwardTo = flag(args, "forwardTo") ?? (await readConfig()).forwardTo;
|
|
132
|
+
if (!forwardTo)
|
|
133
|
+
throw new UsageError("Where to?", "Pass --forward-to <url>, or run edena listen --forward-to <url> first.");
|
|
134
|
+
const event = await findEvent(session, type, eventId);
|
|
135
|
+
const body = JSON.stringify(event);
|
|
136
|
+
const secret = await listenSecret();
|
|
137
|
+
const result = await forward(forwardTo, body, event.type, event.id, secret);
|
|
138
|
+
printDelivery(wantsJson(hasFlag(args, "json")), event.type, event.id, result);
|
|
139
|
+
return result.status !== null && result.status < 300 ? EXIT.ok : EXIT.failure;
|
|
140
|
+
}
|
|
141
|
+
/** The event to send: the one asked for by id, or the latest real one of the type. */
|
|
142
|
+
async function findEvent(session, type, eventId) {
|
|
143
|
+
const call = (path, query) => apiRequest({ apiUrl: session.apiUrl, apiKey: session.apiKey, method: "GET", path, query });
|
|
144
|
+
if (eventId) {
|
|
145
|
+
const response = await call(`/webhook-events/${encodeURIComponent(eventId)}`);
|
|
146
|
+
if (response.kind === "json")
|
|
147
|
+
return response.data;
|
|
148
|
+
throw new UsageError(`No event ${eventId}.`);
|
|
149
|
+
}
|
|
150
|
+
const response = await call("/webhook-events", { type: type, pageSize: "1" });
|
|
151
|
+
const latest = response.kind === "json" ? response.data.data[0] : undefined;
|
|
152
|
+
if (latest)
|
|
153
|
+
return latest;
|
|
154
|
+
throw new UsageError(`There is no ${type} event in the last 30 days to send.`, "Make that change in the sandbox (from the apps or with the CLI) and it will be there; edena webhook-events types lists every type.");
|
|
155
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { flag, hasFlag } from "../args.js";
|
|
2
|
+
import { resolveSession } from "../config.js";
|
|
3
|
+
import { EXIT, NotSignedInError } from "../errors.js";
|
|
4
|
+
import { apiRequest } from "../http.js";
|
|
5
|
+
import { bold, dim, red, wantsJson } from "../output.js";
|
|
6
|
+
import { followStream, sinceOf } from "../sse.js";
|
|
7
|
+
/**
|
|
8
|
+
* `edena logs`: the organization's API requests as they happen, the way the console's Requests shows
|
|
9
|
+
* them. `--mine` keeps this terminal's key; `--since 15m` shows the last ones first.
|
|
10
|
+
*/
|
|
11
|
+
export async function logs(args) {
|
|
12
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
13
|
+
if (!session.apiKey)
|
|
14
|
+
throw new NotSignedInError();
|
|
15
|
+
const url = new URL(`${session.apiUrl}/cli/logs`);
|
|
16
|
+
if (hasFlag(args, "mine")) {
|
|
17
|
+
const response = await apiRequest({ apiUrl: session.apiUrl, apiKey: session.apiKey, method: "GET", path: "/cli/whoami" });
|
|
18
|
+
if (response.kind === "json")
|
|
19
|
+
url.searchParams.set("apiKeyId", response.data.key.id);
|
|
20
|
+
}
|
|
21
|
+
const since = flag(args, "since");
|
|
22
|
+
if (since)
|
|
23
|
+
url.searchParams.set("since", sinceOf(since));
|
|
24
|
+
const json = wantsJson(hasFlag(args, "json"));
|
|
25
|
+
const controller = new AbortController();
|
|
26
|
+
process.once("SIGINT", () => controller.abort());
|
|
27
|
+
await followStream({
|
|
28
|
+
url: url.toString(),
|
|
29
|
+
apiKey: session.apiKey,
|
|
30
|
+
signal: controller.signal,
|
|
31
|
+
onOpen: (reconnected) => {
|
|
32
|
+
if (!reconnected && !json)
|
|
33
|
+
process.stderr.write(dim("Following the API's requests. Ctrl+C to stop.\n\n"));
|
|
34
|
+
},
|
|
35
|
+
onMessage: (message) => {
|
|
36
|
+
if (message.event !== "request")
|
|
37
|
+
return;
|
|
38
|
+
if (json) {
|
|
39
|
+
process.stdout.write(`${message.data}\n`);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const log = JSON.parse(message.data);
|
|
43
|
+
const status = log.statusCode >= 400 ? red(String(log.statusCode)) : String(log.statusCode);
|
|
44
|
+
const at = new Date(log.createdAt).toTimeString().slice(0, 8);
|
|
45
|
+
process.stdout.write(`${dim(at)} ${bold(log.method.padEnd(6))} ${status} ${String(log.durationMs).padStart(5)} ms ${log.route} ${dim(`${log.apiKey.name} · ${log.requestId}`)}\n`);
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
return EXIT.ok;
|
|
49
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { flag } from "../args.js";
|
|
3
|
+
import { resolveSession } from "../config.js";
|
|
4
|
+
import { EXIT, NotSignedInError, UsageError } from "../errors.js";
|
|
5
|
+
import { apiRequest } from "../http.js";
|
|
6
|
+
import { loadReference } from "../reference.js";
|
|
7
|
+
const SECTIONS = ["overview", "keys", "webhooks", "environment", "docs", "requests", "team"];
|
|
8
|
+
export function openUrl(url) {
|
|
9
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
10
|
+
try {
|
|
11
|
+
spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => undefined).unref();
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
// Nowhere to open it: the printed link is enough.
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* `edena open [section]`: the organization's developer console in the browser. `edena open docs
|
|
19
|
+
* students list` opens that operation in the reference.
|
|
20
|
+
*/
|
|
21
|
+
export async function open(args) {
|
|
22
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
23
|
+
if (!session.apiKey)
|
|
24
|
+
throw new NotSignedInError();
|
|
25
|
+
const [, section = "overview", ...rest] = args.positionals;
|
|
26
|
+
if (!SECTIONS.includes(section))
|
|
27
|
+
throw new UsageError(`No section “${section}”.`, `Sections: ${SECTIONS.join(", ")}.`);
|
|
28
|
+
const response = await apiRequest({ apiUrl: session.apiUrl, apiKey: session.apiKey, method: "GET", path: "/cli/whoami" });
|
|
29
|
+
const consoleUrl = response.kind === "json" ? response.data.consoleUrl : undefined;
|
|
30
|
+
if (!consoleUrl)
|
|
31
|
+
throw new Error("The API did not say where its console is.");
|
|
32
|
+
let url = `${consoleUrl}/${section}`;
|
|
33
|
+
if (section === "docs" && rest.length > 0) {
|
|
34
|
+
const operation = (await loadReference(session.apiUrl)).find(rest.join(" "));
|
|
35
|
+
if (!operation)
|
|
36
|
+
throw new UsageError(`No operation “${rest.join(" ")}”.`);
|
|
37
|
+
url += `?op=${encodeURIComponent(operation.id)}`;
|
|
38
|
+
}
|
|
39
|
+
process.stdout.write(`${url}\n`);
|
|
40
|
+
if (process.stdout.isTTY)
|
|
41
|
+
openUrl(url);
|
|
42
|
+
return EXIT.ok;
|
|
43
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
3
|
+
import { flag, hasFlag } from "../args.js";
|
|
4
|
+
import { resolveSession } from "../config.js";
|
|
5
|
+
import { EXIT, NotSignedInError, UsageError } from "../errors.js";
|
|
6
|
+
import { apiRequest } from "../http.js";
|
|
7
|
+
import { bold, dim, printHuman, printJson, wantsJson } from "../output.js";
|
|
8
|
+
import { TypeCollector, bodySchemaOf, oneLine, parametersOf, resolve } from "../schema.js";
|
|
9
|
+
/** Flags every command takes, which are never an operation's own. */
|
|
10
|
+
const GLOBAL_FLAGS = new Set(["json", "yes", "all", "help", "profile", "data", "output", "idempotencyKey", "apiUrl"]);
|
|
11
|
+
const MAX_PAGES = 200;
|
|
12
|
+
/** A flag's text as the value its schema asks for: a number, a boolean, a list, an object. */
|
|
13
|
+
function coerce(values, schema, document) {
|
|
14
|
+
const target = resolve(document, schema);
|
|
15
|
+
const one = values[values.length - 1];
|
|
16
|
+
switch (target.type) {
|
|
17
|
+
case "integer":
|
|
18
|
+
case "number": {
|
|
19
|
+
const number = Number(one);
|
|
20
|
+
if (Number.isNaN(number))
|
|
21
|
+
throw new UsageError(`“${one}” is not a number.`);
|
|
22
|
+
return number;
|
|
23
|
+
}
|
|
24
|
+
case "boolean":
|
|
25
|
+
return one === "true" || one === "1" || one === "yes";
|
|
26
|
+
case "array":
|
|
27
|
+
return values.flatMap((value) => (value.trim().startsWith("[") ? JSON.parse(value) : value.split(",")));
|
|
28
|
+
case "object":
|
|
29
|
+
return JSON.parse(one);
|
|
30
|
+
default:
|
|
31
|
+
return one;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function readData(raw) {
|
|
35
|
+
if (raw === "-") {
|
|
36
|
+
const chunks = [];
|
|
37
|
+
for await (const chunk of process.stdin)
|
|
38
|
+
chunks.push(chunk);
|
|
39
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
40
|
+
}
|
|
41
|
+
if (raw.startsWith("@"))
|
|
42
|
+
return JSON.parse(await readFile(raw.slice(1), "utf8"));
|
|
43
|
+
return JSON.parse(raw);
|
|
44
|
+
}
|
|
45
|
+
/** A write needs the person's yes; without anyone at the keyboard (an agent, a script) it needs `--yes`. */
|
|
46
|
+
async function confirm(operation, session, args) {
|
|
47
|
+
if (hasFlag(args, "yes"))
|
|
48
|
+
return true;
|
|
49
|
+
const where = session.profile ? `${session.profile.organization.name} (${session.profile.organization.environment})` : session.apiUrl;
|
|
50
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
51
|
+
throw new UsageError(`edena ${operation.command} changes data in ${where}.`, "Run it again with --yes once it is confirmed.");
|
|
52
|
+
}
|
|
53
|
+
const readline = createInterface({ input: process.stdin, output: process.stdout });
|
|
54
|
+
const answer = await readline.question(`${operation.method} ${operation.path} in ${bold(where)}. Go ahead? [y/N] `);
|
|
55
|
+
readline.close();
|
|
56
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
57
|
+
}
|
|
58
|
+
/** The request an operation makes from the words and flags given: path, query, headers and body. */
|
|
59
|
+
export async function buildRequest(reference, operation, args) {
|
|
60
|
+
const { path: pathParams, query: queryParams, headers: headerParams } = parametersOf(operation);
|
|
61
|
+
const positionals = args.positionals.slice(2);
|
|
62
|
+
const used = new Set();
|
|
63
|
+
let path = operation.path;
|
|
64
|
+
for (const parameter of pathParams) {
|
|
65
|
+
const value = flag(args, parameter.name) ?? positionals.shift();
|
|
66
|
+
if (value === undefined)
|
|
67
|
+
throw new UsageError(`Missing <${parameter.name}>.`, usageLine(operation));
|
|
68
|
+
used.add(parameter.name);
|
|
69
|
+
path = path.replace(`{${parameter.name}}`, encodeURIComponent(value));
|
|
70
|
+
}
|
|
71
|
+
if (positionals.length > 0)
|
|
72
|
+
throw new UsageError(`Unexpected “${positionals.join(" ")}”.`, usageLine(operation));
|
|
73
|
+
const query = {};
|
|
74
|
+
const headers = {};
|
|
75
|
+
for (const parameter of [...queryParams, ...headerParams]) {
|
|
76
|
+
const values = args.flags.get(parameter.name);
|
|
77
|
+
if (!values) {
|
|
78
|
+
if (parameter.required && parameter.in === "query")
|
|
79
|
+
throw new UsageError(`Missing --${parameter.name}.`, usageLine(operation));
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
used.add(parameter.name);
|
|
83
|
+
if (parameter.in === "query")
|
|
84
|
+
query[parameter.name] = values.flatMap((value) => value.split(","));
|
|
85
|
+
else
|
|
86
|
+
headers[parameter.name] = values[values.length - 1];
|
|
87
|
+
}
|
|
88
|
+
const body = bodySchemaOf(operation);
|
|
89
|
+
let data = undefined;
|
|
90
|
+
const raw = flag(args, "data");
|
|
91
|
+
if (raw !== undefined)
|
|
92
|
+
data = await readData(raw);
|
|
93
|
+
if (body) {
|
|
94
|
+
const properties = resolve(reference.document, body.schema).properties ?? {};
|
|
95
|
+
for (const [name, values] of args.flags) {
|
|
96
|
+
if (GLOBAL_FLAGS.has(name) || used.has(name) || !(name in properties))
|
|
97
|
+
continue;
|
|
98
|
+
data = { ...(typeof data === "object" && data !== null ? data : {}), [name]: coerce(values, properties[name], reference.document) };
|
|
99
|
+
used.add(name);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const unknown = [...args.flags.keys()].filter((name) => !GLOBAL_FLAGS.has(name) && !used.has(name));
|
|
103
|
+
if (unknown.length > 0)
|
|
104
|
+
throw new UsageError(`Unknown flag ${unknown.map((name) => `--${name}`).join(", ")}.`, `Run edena ${operation.command} --help.`);
|
|
105
|
+
return { path, query, headers, body: data };
|
|
106
|
+
}
|
|
107
|
+
/** Runs an operation: builds the request, asks before a write, follows pages with --all, prints the answer. */
|
|
108
|
+
export async function runOperation(reference, operation, args) {
|
|
109
|
+
const session = await resolveSession(flag(args, "profile"));
|
|
110
|
+
if (!session.apiKey)
|
|
111
|
+
throw new NotSignedInError();
|
|
112
|
+
const request = await buildRequest(reference, operation, args);
|
|
113
|
+
if (operation.method !== "GET" && !(await confirm(operation, session, args))) {
|
|
114
|
+
process.stderr.write("Nothing was changed.\n");
|
|
115
|
+
return EXIT.ok;
|
|
116
|
+
}
|
|
117
|
+
const call = (page) => apiRequest({
|
|
118
|
+
apiUrl: session.apiUrl,
|
|
119
|
+
apiKey: session.apiKey,
|
|
120
|
+
method: operation.method,
|
|
121
|
+
path: request.path,
|
|
122
|
+
query: page ? { ...request.query, page: String(page) } : request.query,
|
|
123
|
+
body: request.body,
|
|
124
|
+
headers: request.headers,
|
|
125
|
+
idempotencyKey: flag(args, "idempotencyKey"),
|
|
126
|
+
});
|
|
127
|
+
let response = await call();
|
|
128
|
+
if (hasFlag(args, "all") && response.kind === "json")
|
|
129
|
+
response = await allPages(response, call);
|
|
130
|
+
return print(response, args);
|
|
131
|
+
}
|
|
132
|
+
/** Every page of a paginated list, one after another, as one list. */
|
|
133
|
+
async function allPages(first, call) {
|
|
134
|
+
const page = first.data;
|
|
135
|
+
if (!Array.isArray(page.data) || typeof page.meta?.pages !== "number")
|
|
136
|
+
return first;
|
|
137
|
+
const rows = [...page.data];
|
|
138
|
+
for (let next = 2; next <= Math.min(page.meta.pages, MAX_PAGES); next++) {
|
|
139
|
+
const response = await call(next);
|
|
140
|
+
if (response.kind === "json")
|
|
141
|
+
rows.push(...((response.data.data) ?? []));
|
|
142
|
+
}
|
|
143
|
+
return { ...first, data: { data: rows, meta: { ...page.meta, page: 1, pages: 1, pageSize: rows.length, total: page.meta.total ?? rows.length } } };
|
|
144
|
+
}
|
|
145
|
+
async function print(response, args) {
|
|
146
|
+
if (response.kind === "empty") {
|
|
147
|
+
if (!wantsJson(hasFlag(args, "json")))
|
|
148
|
+
process.stdout.write(dim("Done.\n"));
|
|
149
|
+
return EXIT.ok;
|
|
150
|
+
}
|
|
151
|
+
if (response.kind === "file") {
|
|
152
|
+
const output = flag(args, "output");
|
|
153
|
+
if (output) {
|
|
154
|
+
await writeFile(output, response.data);
|
|
155
|
+
process.stderr.write(`Saved ${response.data.length} bytes to ${output}.\n`);
|
|
156
|
+
}
|
|
157
|
+
else if (process.stdout.isTTY) {
|
|
158
|
+
throw new UsageError(`The answer is a file (${response.contentType}).`, "Save it with --output <file>.");
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
process.stdout.write(response.data);
|
|
162
|
+
}
|
|
163
|
+
return EXIT.ok;
|
|
164
|
+
}
|
|
165
|
+
if (wantsJson(hasFlag(args, "json")))
|
|
166
|
+
printJson(response.data);
|
|
167
|
+
else
|
|
168
|
+
printHuman(response.data);
|
|
169
|
+
return EXIT.ok;
|
|
170
|
+
}
|
|
171
|
+
function usageLine(operation) {
|
|
172
|
+
const { path } = parametersOf(operation);
|
|
173
|
+
return `Usage: edena ${operation.command}${path.map((parameter) => ` <${parameter.name}>`).join("")} [flags]`;
|
|
174
|
+
}
|
|
175
|
+
function describe(parameter, types) {
|
|
176
|
+
const type = parameter.schema ? types.ts(parameter.schema) : "string";
|
|
177
|
+
return `${type}${parameter.required ? ", required" : ""}${parameter.description ? `. ${oneLine(parameter.description)}` : ""}`;
|
|
178
|
+
}
|
|
179
|
+
/** `edena students list --help`: what it does, what it takes and what it answers. */
|
|
180
|
+
export function operationHelp(reference, operation) {
|
|
181
|
+
const types = new TypeCollector(reference.document);
|
|
182
|
+
const { path, query, headers } = parametersOf(operation);
|
|
183
|
+
const lines = [bold(`edena ${operation.command}`), operation.summary, "", dim(`${operation.method} ${operation.path} (${operation.id})`), "", usageLine(operation)];
|
|
184
|
+
if (path.length > 0)
|
|
185
|
+
lines.push("", "Arguments:", ...path.map((parameter) => ` <${parameter.name}> ${describe(parameter, types)}`));
|
|
186
|
+
if (query.length + headers.length > 0)
|
|
187
|
+
lines.push("", "Flags:", ...[...query, ...headers].map((parameter) => ` --${parameter.name} ${describe(parameter, types)}`));
|
|
188
|
+
const body = bodySchemaOf(operation);
|
|
189
|
+
if (body) {
|
|
190
|
+
const schema = resolve(reference.document, body.schema);
|
|
191
|
+
const required = new Set(schema.required ?? []);
|
|
192
|
+
lines.push("", `Body: --data '<json>' | --data @file.json | --data - (${types.ts(body.schema)}), or a flag per field:`);
|
|
193
|
+
for (const [name, property] of Object.entries(schema.properties ?? {})) {
|
|
194
|
+
lines.push(` --${name} ${types.ts(property)}${required.has(name) ? ", required" : ""}${property.description ? `. ${oneLine(property.description)}` : ""}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const success = Object.entries(operation.responses).find(([status]) => status.startsWith("2"));
|
|
198
|
+
const json = success?.[1].content?.["application/json"]?.schema;
|
|
199
|
+
if (success)
|
|
200
|
+
lines.push("", `Answers ${success[0]}: ${json ? types.ts(json) : success[1].content ? "a file (save it with --output)" : "no body"}`);
|
|
201
|
+
lines.push("", dim("Also: --json --yes (writes without asking) --all (every page) --profile <name> --output <file>"), dim(`Types: edena docs show ${operation.command}`));
|
|
202
|
+
return `${lines.join("\n")}\n`;
|
|
203
|
+
}
|
|
204
|
+
/** `edena students`: the actions of a category. */
|
|
205
|
+
export function groupHelp(group) {
|
|
206
|
+
const width = Math.max(...group.operations.map((operation) => operation.action.length));
|
|
207
|
+
return [
|
|
208
|
+
bold(`edena ${group.name}`) + dim(` ${group.category}`),
|
|
209
|
+
group.description,
|
|
210
|
+
"",
|
|
211
|
+
...group.operations.map((operation) => ` ${operation.action.padEnd(width)} ${operation.summary}`),
|
|
212
|
+
"",
|
|
213
|
+
dim(`Run edena ${group.name} <action> --help for what one takes.`),
|
|
214
|
+
"",
|
|
215
|
+
].join("\n");
|
|
216
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { flag, hasFlag } from "../args.js";
|
|
6
|
+
import { EXIT, UsageError } from "../errors.js";
|
|
7
|
+
import { bold, dim } from "../output.js";
|
|
8
|
+
import { PACKAGE_ROOT } from "../version.js";
|
|
9
|
+
/**
|
|
10
|
+
* Where each agent reads skills (the open `SKILL.md` format): for every project of the user, or for
|
|
11
|
+
* the project in the current folder. Codex reads the shared `.agents/skills`.
|
|
12
|
+
*/
|
|
13
|
+
const AGENTS = {
|
|
14
|
+
claude: { name: "Claude Code", home: ".claude", user: [".claude", "skills"], project: [".claude", "skills"] },
|
|
15
|
+
codex: { name: "Codex", home: ".codex", user: [".agents", "skills"], project: [".agents", "skills"] },
|
|
16
|
+
gemini: { name: "Gemini CLI", home: ".gemini", user: [".gemini", "skills"], project: [".gemini", "skills"] },
|
|
17
|
+
};
|
|
18
|
+
const SKILL_NAME = "edena";
|
|
19
|
+
const skillSource = () => join(PACKAGE_ROOT, "skill", "SKILL.md");
|
|
20
|
+
function targets(args) {
|
|
21
|
+
const chosen = flag(args, "agent");
|
|
22
|
+
if (chosen === "all")
|
|
23
|
+
return Object.keys(AGENTS);
|
|
24
|
+
if (chosen) {
|
|
25
|
+
if (!(chosen in AGENTS))
|
|
26
|
+
throw new UsageError(`Unknown agent “${chosen}”.`, `Agents: ${Object.keys(AGENTS).join(", ")}, all.`);
|
|
27
|
+
return [chosen];
|
|
28
|
+
}
|
|
29
|
+
// The agents this machine has; with none found, all of them, since the files cost nothing.
|
|
30
|
+
const found = Object.keys(AGENTS).filter((agent) => existsSync(join(homedir(), AGENTS[agent].home)));
|
|
31
|
+
return found.length > 0 ? found : Object.keys(AGENTS);
|
|
32
|
+
}
|
|
33
|
+
function folder(agent, project) {
|
|
34
|
+
const parts = project ? AGENTS[agent].project : AGENTS[agent].user;
|
|
35
|
+
return join(project ? process.cwd() : homedir(), ...parts, SKILL_NAME);
|
|
36
|
+
}
|
|
37
|
+
/** `edena skill install`: teaches the agents on this machine to use the CLI. */
|
|
38
|
+
export async function skillInstall(args) {
|
|
39
|
+
const content = await readFile(skillSource(), "utf8");
|
|
40
|
+
const project = hasFlag(args, "project");
|
|
41
|
+
for (const agent of targets(args)) {
|
|
42
|
+
const dir = folder(agent, project);
|
|
43
|
+
await mkdir(dir, { recursive: true });
|
|
44
|
+
await writeFile(join(dir, "SKILL.md"), content);
|
|
45
|
+
process.stdout.write(`${bold(AGENTS[agent].name)} ${dim(join(dir, "SKILL.md"))}\n`);
|
|
46
|
+
}
|
|
47
|
+
process.stdout.write(`\nDone. Ask your agent in your own words, for example: “how many active students have no payer?”\n${dim("Restart the agent if it was open, so it finds the skill.")}\n`);
|
|
48
|
+
return EXIT.ok;
|
|
49
|
+
}
|
|
50
|
+
/** `edena skill uninstall`: removes what `install` wrote. */
|
|
51
|
+
export async function skillUninstall(args) {
|
|
52
|
+
const project = hasFlag(args, "project");
|
|
53
|
+
for (const agent of targets(args)) {
|
|
54
|
+
const dir = folder(agent, project);
|
|
55
|
+
if (!existsSync(dir))
|
|
56
|
+
continue;
|
|
57
|
+
await rm(dir, { recursive: true, force: true });
|
|
58
|
+
process.stdout.write(`Removed from ${AGENTS[agent].name}.\n`);
|
|
59
|
+
}
|
|
60
|
+
return EXIT.ok;
|
|
61
|
+
}
|
|
62
|
+
/** `edena skill show`: the skill itself, to read or to copy where an agent not listed reads skills. */
|
|
63
|
+
export async function skillShow() {
|
|
64
|
+
process.stdout.write(await readFile(skillSource(), "utf8"));
|
|
65
|
+
return EXIT.ok;
|
|
66
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
export const DEFAULT_API_URL = "https://api.edena.es";
|
|
6
|
+
/** `~/.config/edena` (or `$XDG_CONFIG_HOME/edena`, `%APPDATA%\edena`); `EDENA_CONFIG_DIR` overrides it. */
|
|
7
|
+
export function configDir() {
|
|
8
|
+
if (process.env.EDENA_CONFIG_DIR)
|
|
9
|
+
return process.env.EDENA_CONFIG_DIR;
|
|
10
|
+
if (process.platform === "win32" && process.env.APPDATA)
|
|
11
|
+
return join(process.env.APPDATA, "edena");
|
|
12
|
+
return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "edena");
|
|
13
|
+
}
|
|
14
|
+
/** `~/.cache/edena`, for the API reference; `EDENA_CACHE_DIR` overrides it. */
|
|
15
|
+
export function cacheDir() {
|
|
16
|
+
if (process.env.EDENA_CACHE_DIR)
|
|
17
|
+
return process.env.EDENA_CACHE_DIR;
|
|
18
|
+
if (process.platform === "win32" && process.env.LOCALAPPDATA)
|
|
19
|
+
return join(process.env.LOCALAPPDATA, "edena");
|
|
20
|
+
return join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "edena");
|
|
21
|
+
}
|
|
22
|
+
const configFile = () => join(configDir(), "config.json");
|
|
23
|
+
/** The keys, apart from the rest and readable only by their owner. */
|
|
24
|
+
const credentialsFile = () => join(configDir(), "credentials.json");
|
|
25
|
+
async function readJson(path, fallback) {
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return fallback;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function writeJson(path, value, mode) {
|
|
34
|
+
await mkdir(configDir(), { recursive: true, mode: 0o700 });
|
|
35
|
+
await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, { mode });
|
|
36
|
+
if (mode !== undefined)
|
|
37
|
+
await chmod(path, mode);
|
|
38
|
+
}
|
|
39
|
+
export async function readConfig() {
|
|
40
|
+
return readJson(configFile(), { current: null, profiles: {} });
|
|
41
|
+
}
|
|
42
|
+
/** Keeps a signed-in organization, and makes it the one commands run in. */
|
|
43
|
+
export async function saveProfile(name, profile, apiKey) {
|
|
44
|
+
const config = await readConfig();
|
|
45
|
+
config.profiles[name] = profile;
|
|
46
|
+
config.current = name;
|
|
47
|
+
await writeJson(configFile(), config);
|
|
48
|
+
const credentials = await readJson(credentialsFile(), {});
|
|
49
|
+
credentials[name] = apiKey;
|
|
50
|
+
await writeJson(credentialsFile(), credentials, 0o600);
|
|
51
|
+
}
|
|
52
|
+
export async function useProfile(name) {
|
|
53
|
+
const config = await readConfig();
|
|
54
|
+
config.current = name;
|
|
55
|
+
await writeJson(configFile(), config);
|
|
56
|
+
}
|
|
57
|
+
/** Forgets a profile and its key; the next one left becomes the current one. */
|
|
58
|
+
export async function removeProfile(name) {
|
|
59
|
+
const config = await readConfig();
|
|
60
|
+
delete config.profiles[name];
|
|
61
|
+
if (config.current === name)
|
|
62
|
+
config.current = Object.keys(config.profiles)[0] ?? null;
|
|
63
|
+
await writeJson(configFile(), config);
|
|
64
|
+
const credentials = await readJson(credentialsFile(), {});
|
|
65
|
+
delete credentials[name];
|
|
66
|
+
if (Object.keys(credentials).length === 0)
|
|
67
|
+
await rm(credentialsFile(), { force: true });
|
|
68
|
+
else
|
|
69
|
+
await writeJson(credentialsFile(), credentials, 0o600);
|
|
70
|
+
}
|
|
71
|
+
/** Remembers where `edena listen` forwards, for `edena trigger`. */
|
|
72
|
+
export async function saveForwardTo(url) {
|
|
73
|
+
const config = await readConfig();
|
|
74
|
+
config.forwardTo = url;
|
|
75
|
+
await writeJson(configFile(), config);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The secret `edena listen` and `edena trigger` sign local deliveries with: one per machine, kept
|
|
79
|
+
* apart and readable only by its owner, so a local server verifies `Edena-Signature` with a stable
|
|
80
|
+
* value, as it would with an endpoint's.
|
|
81
|
+
*/
|
|
82
|
+
export async function listenSecret() {
|
|
83
|
+
const file = join(configDir(), "listen-secret.json");
|
|
84
|
+
const existing = await readJson(file, "");
|
|
85
|
+
if (existing)
|
|
86
|
+
return existing;
|
|
87
|
+
const secret = `whsec_${randomBytes(32).toString("base64url")}`;
|
|
88
|
+
await writeJson(file, secret, 0o600);
|
|
89
|
+
return secret;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The session a command runs in: `EDENA_API_KEY` when set (CI, a script), else the profile named by
|
|
93
|
+
* `--profile` or `EDENA_PROFILE`, else the current one. `EDENA_API_URL` points it at another API.
|
|
94
|
+
*/
|
|
95
|
+
export async function resolveSession(profileFlag) {
|
|
96
|
+
const config = await readConfig();
|
|
97
|
+
const envKey = process.env.EDENA_API_KEY?.trim() || null;
|
|
98
|
+
const name = profileFlag ?? process.env.EDENA_PROFILE ?? config.current;
|
|
99
|
+
const profile = name ? (config.profiles[name] ?? null) : null;
|
|
100
|
+
const apiUrl = (process.env.EDENA_API_URL ?? profile?.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "");
|
|
101
|
+
if (envKey)
|
|
102
|
+
return { apiUrl, apiKey: envKey, profileName: null, profile: null };
|
|
103
|
+
const credentials = await readJson(credentialsFile(), {});
|
|
104
|
+
return { apiUrl, apiKey: name ? (credentials[name] ?? null) : null, profileName: profile ? name : null, profile };
|
|
105
|
+
}
|