@prudai/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/dist/api.d.ts +3 -0
- package/dist/approvals.d.ts +13 -0
- package/dist/args.d.ts +14 -0
- package/dist/auth.d.ts +36 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +4452 -0
- package/dist/catalog.d.ts +115 -0
- package/dist/cli.d.ts +8 -0
- package/dist/config.d.ts +70 -0
- package/dist/context.d.ts +55 -0
- package/dist/core.d.ts +91 -0
- package/dist/discovery.d.ts +103 -0
- package/dist/exchange.d.ts +25 -0
- package/dist/execute.d.ts +57 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +4622 -0
- package/dist/keycloak.d.ts +54 -0
- package/dist/openapi.d.ts +116 -0
- package/dist/output.d.ts +27 -0
- package/dist/parity.d.ts +16 -0
- package/dist/platform.d.ts +110 -0
- package/dist/products.d.ts +31 -0
- package/dist/projects.d.ts +36 -0
- package/dist/scopes.d.ts +66 -0
- package/dist/session.d.ts +49 -0
- package/dist/skill.d.ts +6 -0
- package/dist/specs/irma.json +1 -0
- package/dist/specs/manifest.json +12 -0
- package/dist/system.d.ts +10 -0
- package/dist/transfer.d.ts +30 -0
- package/dist/trust.d.ts +7 -0
- package/dist/version.d.ts +2 -0
- package/package.json +27 -4
package/dist/bin.js
ADDED
|
@@ -0,0 +1,4452 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { resolve as resolvePath } from "node:path";
|
|
5
|
+
|
|
6
|
+
// src/core.ts
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
|
|
9
|
+
// src/trust.ts
|
|
10
|
+
var LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
11
|
+
function optInOrigins(env) {
|
|
12
|
+
const allowed = new Set;
|
|
13
|
+
for (const raw of (env.PRUDAI_ALLOW_ORIGIN ?? "").split(",").map((value) => value.trim()).filter(Boolean)) {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(raw);
|
|
16
|
+
if (url.origin !== "null" && raw.replace(/\/+$/, "") === url.origin && (url.protocol === "https:" || LOCAL_HOSTS.has(url.hostname)))
|
|
17
|
+
allowed.add(url.origin);
|
|
18
|
+
} catch {}
|
|
19
|
+
}
|
|
20
|
+
return allowed;
|
|
21
|
+
}
|
|
22
|
+
function isTrustedOrigin(raw, env = {}) {
|
|
23
|
+
let url;
|
|
24
|
+
try {
|
|
25
|
+
url = new URL(raw);
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
if (url.username || url.password)
|
|
30
|
+
return false;
|
|
31
|
+
if (LOCAL_HOSTS.has(url.hostname))
|
|
32
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
33
|
+
if (url.protocol === "https:" && url.port === "" && url.hostname.endsWith(".prudai.com"))
|
|
34
|
+
return true;
|
|
35
|
+
return optInOrigins(env).has(url.origin);
|
|
36
|
+
}
|
|
37
|
+
function requireTrustedOrigin(raw, env = {}) {
|
|
38
|
+
if (!isTrustedOrigin(raw, env)) {
|
|
39
|
+
throw new CliError("Refusing to send credentials outside https://*.prudai.com or localhost. To trust another origin, set PRUDAI_ALLOW_ORIGIN=<exact origin> in the environment.", 2, "untrusted_origin");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/core.ts
|
|
44
|
+
var EXIT = { OK: 0, SERVER: 1, USER: 2 };
|
|
45
|
+
|
|
46
|
+
class CliError extends Error {
|
|
47
|
+
exitCode;
|
|
48
|
+
code;
|
|
49
|
+
constructor(message, exitCode = 2, code = "validation_error") {
|
|
50
|
+
super(message);
|
|
51
|
+
this.exitCode = exitCode;
|
|
52
|
+
this.code = code;
|
|
53
|
+
this.name = "CliError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function statusToExit(status) {
|
|
57
|
+
if (status === 202)
|
|
58
|
+
return 2;
|
|
59
|
+
if (status >= 200 && status < 300)
|
|
60
|
+
return 0;
|
|
61
|
+
return status >= 400 && status < 500 ? 2 : 1;
|
|
62
|
+
}
|
|
63
|
+
function secureUrl(raw) {
|
|
64
|
+
let url;
|
|
65
|
+
try {
|
|
66
|
+
url = new URL(raw);
|
|
67
|
+
} catch {
|
|
68
|
+
throw new CliError("Expected an absolute API URL.");
|
|
69
|
+
}
|
|
70
|
+
if (url.username || url.password || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
71
|
+
throw new CliError("Use HTTPS, or HTTP on localhost, without URL credentials or fragments.");
|
|
72
|
+
}
|
|
73
|
+
return url;
|
|
74
|
+
}
|
|
75
|
+
function prepareRequest(raw, options) {
|
|
76
|
+
const url = secureUrl(raw);
|
|
77
|
+
if (options.token)
|
|
78
|
+
requireTrustedOrigin(url.href, options.env);
|
|
79
|
+
const headers = new Headers(options.headers);
|
|
80
|
+
if (options.accept)
|
|
81
|
+
headers.set("accept", options.accept);
|
|
82
|
+
else if (!headers.has("accept"))
|
|
83
|
+
headers.set("accept", "application/json");
|
|
84
|
+
headers.set("x-prudai-agent", "prudai-cli");
|
|
85
|
+
if (options.token)
|
|
86
|
+
headers.set("authorization", `Bearer ${options.token}`);
|
|
87
|
+
return { url, headers };
|
|
88
|
+
}
|
|
89
|
+
async function readJsonBody(response) {
|
|
90
|
+
const text = await response.text();
|
|
91
|
+
let body;
|
|
92
|
+
try {
|
|
93
|
+
body = text ? JSON.parse(text) : null;
|
|
94
|
+
} catch {
|
|
95
|
+
throw new CliError("Server returned invalid JSON; check state before retrying a write.", 1, "invalid_response");
|
|
96
|
+
}
|
|
97
|
+
return { status: response.status, body, headers: response.headers };
|
|
98
|
+
}
|
|
99
|
+
async function requestJson(fetchImpl, raw, options = {}) {
|
|
100
|
+
const { url, headers } = prepareRequest(raw, options);
|
|
101
|
+
if (options.body !== undefined)
|
|
102
|
+
headers.set("content-type", "application/json");
|
|
103
|
+
try {
|
|
104
|
+
const response = await fetchImpl(url.href, {
|
|
105
|
+
method: options.method ?? "GET",
|
|
106
|
+
headers,
|
|
107
|
+
...options.body !== undefined ? { body: JSON.stringify(options.body) } : {},
|
|
108
|
+
redirect: "error",
|
|
109
|
+
signal: AbortSignal.timeout(15000)
|
|
110
|
+
});
|
|
111
|
+
return await readJsonBody(response);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error instanceof CliError)
|
|
114
|
+
throw error;
|
|
115
|
+
throw new CliError("Network request failed; check state before retrying a write.", 1, "network_error");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function transferTimeout(env = {}) {
|
|
119
|
+
const seconds = Number(env.PRUDAI_TRANSFER_TIMEOUT_SECONDS);
|
|
120
|
+
return Number.isFinite(seconds) && seconds >= 5 && seconds <= 7200 ? seconds * 1000 : 600000;
|
|
121
|
+
}
|
|
122
|
+
function quotedFilename(value) {
|
|
123
|
+
return value.replaceAll("\r", "%0D").replaceAll(`
|
|
124
|
+
`, "%0A").replaceAll('"', "%22");
|
|
125
|
+
}
|
|
126
|
+
async function requestMultipart(fetchImpl, raw, options) {
|
|
127
|
+
const { url, headers } = prepareRequest(raw, options);
|
|
128
|
+
const { file } = options;
|
|
129
|
+
const boundary = `prudai-${crypto.randomUUID().replaceAll("-", "")}`;
|
|
130
|
+
const encoder = new TextEncoder;
|
|
131
|
+
const head = encoder.encode(`--${boundary}\r
|
|
132
|
+
Content-Disposition: form-data; name="${file.field}"; filename="${quotedFilename(file.filename)}"\r
|
|
133
|
+
Content-Type: ${file.contentType}\r
|
|
134
|
+
\r
|
|
135
|
+
`);
|
|
136
|
+
const tail = encoder.encode(`\r
|
|
137
|
+
--${boundary}--\r
|
|
138
|
+
`);
|
|
139
|
+
headers.set("content-type", `multipart/form-data; boundary=${boundary}`);
|
|
140
|
+
headers.set("content-length", String(head.length + file.size + tail.length));
|
|
141
|
+
const hash = createHash("sha256");
|
|
142
|
+
let bytes = 0;
|
|
143
|
+
let failure;
|
|
144
|
+
const chunks = file.open()[Symbol.asyncIterator]();
|
|
145
|
+
let stage = "head";
|
|
146
|
+
const body = new ReadableStream({
|
|
147
|
+
async pull(controller) {
|
|
148
|
+
try {
|
|
149
|
+
if (stage === "head") {
|
|
150
|
+
stage = "file";
|
|
151
|
+
controller.enqueue(head);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const next = await chunks.next();
|
|
155
|
+
if (!next.done) {
|
|
156
|
+
bytes += next.value.length;
|
|
157
|
+
hash.update(next.value);
|
|
158
|
+
if (bytes > file.size)
|
|
159
|
+
throw new CliError("The file grew while it was being uploaded; nothing was committed by this CLI. Check the state before retrying.", 1, "file_changed");
|
|
160
|
+
controller.enqueue(next.value);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (bytes !== file.size)
|
|
164
|
+
throw new CliError("The file shrank while it was being uploaded; check the state before retrying.", 1, "file_changed");
|
|
165
|
+
controller.enqueue(tail);
|
|
166
|
+
controller.close();
|
|
167
|
+
} catch (error) {
|
|
168
|
+
failure = error instanceof CliError ? error : new CliError("The file could not be read while uploading; check the state before retrying.", 1, "file_unreadable");
|
|
169
|
+
controller.error(failure);
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
async cancel() {
|
|
173
|
+
await chunks.return?.(undefined);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
try {
|
|
177
|
+
const response = await fetchImpl(url.href, {
|
|
178
|
+
method: options.method ?? "POST",
|
|
179
|
+
headers,
|
|
180
|
+
body,
|
|
181
|
+
duplex: "half",
|
|
182
|
+
redirect: "error",
|
|
183
|
+
signal: AbortSignal.timeout(transferTimeout(options.env))
|
|
184
|
+
});
|
|
185
|
+
const answer = await readJsonBody(response);
|
|
186
|
+
return { ...answer, sent: { bytes, sha256: hash.digest("hex") } };
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (failure)
|
|
189
|
+
throw failure;
|
|
190
|
+
if (error instanceof CliError)
|
|
191
|
+
throw error;
|
|
192
|
+
throw new CliError("Network request failed; check state before retrying a write.", 1, "network_error");
|
|
193
|
+
} finally {
|
|
194
|
+
await chunks.return?.(undefined);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async function requestBytes(fetchImpl, raw, options) {
|
|
198
|
+
const { url, headers } = prepareRequest(raw, { ...options, accept: "*/*" });
|
|
199
|
+
try {
|
|
200
|
+
const response = await fetchImpl(url.href, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(transferTimeout(options.env)) });
|
|
201
|
+
const bytes = response.status >= 200 && response.status < 300 && response.status !== 202 && response.status !== 204;
|
|
202
|
+
if (!bytes)
|
|
203
|
+
return { kind: "json", ...await readJsonBody(response) };
|
|
204
|
+
const attachment = /^\s*attachment/i.test(response.headers.get("content-disposition") ?? "");
|
|
205
|
+
if (/json/i.test(response.headers.get("content-type") ?? "") && !attachment || !response.body) {
|
|
206
|
+
await response.body?.cancel();
|
|
207
|
+
throw new CliError("Expected the bytes of a file but the server answered with JSON (or nothing); nothing was written.", 1, "invalid_response");
|
|
208
|
+
}
|
|
209
|
+
return { kind: "bytes", status: response.status, headers: response.headers, stream: response.body };
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (error instanceof CliError)
|
|
212
|
+
throw error;
|
|
213
|
+
throw new CliError("Network request failed.", 1, "network_error");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function requireSuccess(status) {
|
|
217
|
+
if (statusToExit(status) !== 0) {
|
|
218
|
+
throw new CliError(`API returned HTTP ${status}.`, statusToExit(status), `http_${status}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function isRecord(value) {
|
|
222
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
223
|
+
}
|
|
224
|
+
function parseEnvelope(body) {
|
|
225
|
+
if (!isRecord(body) || !("data" in body) || !isRecord(body.context) || !isRecord(body.completeness) || !Array.isArray(body.notIncluded) || !isRecord(body.provenance) || !Array.isArray(body.next)) {
|
|
226
|
+
throw new CliError("Server returned an invalid /v1 envelope.", 1, "invalid_envelope");
|
|
227
|
+
}
|
|
228
|
+
return body;
|
|
229
|
+
}
|
|
230
|
+
function renderEnvelope(body) {
|
|
231
|
+
return [
|
|
232
|
+
JSON.stringify(body.data, null, 2),
|
|
233
|
+
`Context: ${JSON.stringify(body.context)}`,
|
|
234
|
+
`Completeness: ${JSON.stringify(body.completeness)}`,
|
|
235
|
+
`Not included: ${JSON.stringify(body.notIncluded)}`,
|
|
236
|
+
`Provenance: ${JSON.stringify(body.provenance)}`,
|
|
237
|
+
`Next: ${JSON.stringify(body.next)}`
|
|
238
|
+
].join(`
|
|
239
|
+
`);
|
|
240
|
+
}
|
|
241
|
+
function approvalResult(body, env = {}) {
|
|
242
|
+
if (!isRecord(body) || body.status !== "approval_required" || !isRecord(body.approvalRequest)) {
|
|
243
|
+
throw new CliError("HTTP 202 received: operation is pending and has not succeeded.", 2, "operation_pending");
|
|
244
|
+
}
|
|
245
|
+
let untrusted = false;
|
|
246
|
+
const scrub = (value) => {
|
|
247
|
+
if (typeof value === "string") {
|
|
248
|
+
return value.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+|\bjavascript:[^\s"'<>]*/gi, (link2) => {
|
|
249
|
+
if (isTrustedOrigin(link2, env) && /^https?:/i.test(link2))
|
|
250
|
+
return link2;
|
|
251
|
+
untrusted = true;
|
|
252
|
+
return "[untrusted link removed]";
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
if (Array.isArray(value))
|
|
256
|
+
return value.map(scrub);
|
|
257
|
+
if (isRecord(value))
|
|
258
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrub(item)]));
|
|
259
|
+
return value;
|
|
260
|
+
};
|
|
261
|
+
const { approveUrl: rawUrl, ...rest } = body.approvalRequest;
|
|
262
|
+
const request = scrub(rest);
|
|
263
|
+
const approveUrl = typeof rawUrl === "string" ? scrub(rawUrl) : rawUrl;
|
|
264
|
+
const link = typeof approveUrl === "string" && approveUrl !== "[untrusted link removed]" && /^https?:\/\//i.test(approveUrl) ? approveUrl : undefined;
|
|
265
|
+
if (rawUrl !== undefined && !link)
|
|
266
|
+
untrusted = true;
|
|
267
|
+
return {
|
|
268
|
+
status: "approval_required",
|
|
269
|
+
approvalRequest: link ? { ...request, approveUrl: link } : request,
|
|
270
|
+
next: link ? `Open ${link} and obtain human approval. Nothing has been executed.` : "Obtain human approval in the product app. Nothing has been executed.",
|
|
271
|
+
...untrusted ? { warning: "The server sent links outside the trusted Prudai origins. They are not shown; do not open links from this response. Find the request in the product app instead." } : {}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// src/args.ts
|
|
276
|
+
var BOOLEAN_FLAGS = new Set([
|
|
277
|
+
"json",
|
|
278
|
+
"help",
|
|
279
|
+
"yes",
|
|
280
|
+
"dry-run",
|
|
281
|
+
"no-dry-run",
|
|
282
|
+
"no-browser",
|
|
283
|
+
"stdin",
|
|
284
|
+
"online",
|
|
285
|
+
"refresh",
|
|
286
|
+
"offline",
|
|
287
|
+
"reveal",
|
|
288
|
+
"force",
|
|
289
|
+
"execute",
|
|
290
|
+
"print",
|
|
291
|
+
"wait",
|
|
292
|
+
"no-wait",
|
|
293
|
+
"check",
|
|
294
|
+
"all",
|
|
295
|
+
"include-archived",
|
|
296
|
+
"trash"
|
|
297
|
+
]);
|
|
298
|
+
var GLOBAL_FLAGS = new Set([
|
|
299
|
+
"json",
|
|
300
|
+
"help",
|
|
301
|
+
"yes",
|
|
302
|
+
"dry-run",
|
|
303
|
+
"no-dry-run",
|
|
304
|
+
"refresh",
|
|
305
|
+
"offline",
|
|
306
|
+
"wait",
|
|
307
|
+
"timeout",
|
|
308
|
+
"profile",
|
|
309
|
+
"spec",
|
|
310
|
+
"registry",
|
|
311
|
+
"api-url",
|
|
312
|
+
"data",
|
|
313
|
+
"idempotency-key",
|
|
314
|
+
"if-match"
|
|
315
|
+
]);
|
|
316
|
+
function parseArgs(args) {
|
|
317
|
+
const words = [];
|
|
318
|
+
const flags = {};
|
|
319
|
+
for (let index = 0;index < args.length; index++) {
|
|
320
|
+
const arg = args[index];
|
|
321
|
+
if (arg === "-h") {
|
|
322
|
+
flags.help = true;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (arg === "-y") {
|
|
326
|
+
flags.yes = true;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (!arg.startsWith("--")) {
|
|
330
|
+
words.push(arg);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
const equals = arg.indexOf("=");
|
|
334
|
+
const name = arg.slice(2, equals === -1 ? undefined : equals);
|
|
335
|
+
if (/(token|secret|password|credential|authorization|api[-_]?key)/i.test(name)) {
|
|
336
|
+
throw new CliError("Credentials must come from the environment or the protected config file; credential flags are forbidden.");
|
|
337
|
+
}
|
|
338
|
+
if (!name || Object.hasOwn(flags, name))
|
|
339
|
+
throw new CliError("Empty or duplicate flag.");
|
|
340
|
+
if (BOOLEAN_FLAGS.has(name)) {
|
|
341
|
+
if (equals !== -1)
|
|
342
|
+
throw new CliError(`--${name} does not accept a value.`);
|
|
343
|
+
flags[name] = true;
|
|
344
|
+
} else {
|
|
345
|
+
const value = equals !== -1 ? arg.slice(equals + 1) : args[++index];
|
|
346
|
+
if (value === undefined || value.startsWith("--"))
|
|
347
|
+
throw new CliError(`--${name} requires a value.`);
|
|
348
|
+
flags[name] = value;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (flags["dry-run"] && flags["no-dry-run"])
|
|
352
|
+
throw new CliError("Conflicting dry-run flags.");
|
|
353
|
+
if (flags.wait && flags["no-wait"])
|
|
354
|
+
throw new CliError("Conflicting wait flags.");
|
|
355
|
+
return { words, flags };
|
|
356
|
+
}
|
|
357
|
+
function str(flags, key) {
|
|
358
|
+
return typeof flags[key] === "string" ? flags[key] : undefined;
|
|
359
|
+
}
|
|
360
|
+
function validateFlags(flags, allowed) {
|
|
361
|
+
const set = new Set(allowed);
|
|
362
|
+
for (const name of Object.keys(flags))
|
|
363
|
+
if (!set.has(name))
|
|
364
|
+
throw new CliError(`Unknown flag --${name}.`);
|
|
365
|
+
}
|
|
366
|
+
function safeApiOrigin(raw) {
|
|
367
|
+
const url = secureUrl(raw);
|
|
368
|
+
if (url.pathname !== "/" || url.search)
|
|
369
|
+
throw new CliError("API URL must be an origin without a path or query.");
|
|
370
|
+
return url.origin;
|
|
371
|
+
}
|
|
372
|
+
function intFlag(flags, key, fallback, min, max) {
|
|
373
|
+
const raw = str(flags, key);
|
|
374
|
+
if (raw === undefined)
|
|
375
|
+
return fallback;
|
|
376
|
+
const value = Number(raw);
|
|
377
|
+
if (!Number.isInteger(value) || value < min || value > max)
|
|
378
|
+
throw new CliError(`--${key} must be a whole number from ${min} to ${max}.`);
|
|
379
|
+
return value;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// src/catalog.ts
|
|
383
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
384
|
+
import { dirname, join } from "node:path";
|
|
385
|
+
|
|
386
|
+
// src/openapi.ts
|
|
387
|
+
import { readFile, stat } from "node:fs/promises";
|
|
388
|
+
import { parse as parseYaml } from "yaml";
|
|
389
|
+
function object(value, label) {
|
|
390
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
391
|
+
throw new CliError(`Invalid OpenAPI ${label}`, 2, "invalid_spec");
|
|
392
|
+
}
|
|
393
|
+
return value;
|
|
394
|
+
}
|
|
395
|
+
function resolve(doc, value, chain = []) {
|
|
396
|
+
if (Array.isArray(value))
|
|
397
|
+
return value.map((item) => resolve(doc, item, chain));
|
|
398
|
+
if (!value || typeof value !== "object")
|
|
399
|
+
return value;
|
|
400
|
+
const node = value;
|
|
401
|
+
if (typeof node.$ref === "string") {
|
|
402
|
+
const ref = node.$ref;
|
|
403
|
+
if (!ref.startsWith("#/"))
|
|
404
|
+
throw new CliError("External OpenAPI references are not supported", 2, "invalid_spec");
|
|
405
|
+
if (chain.includes(ref))
|
|
406
|
+
throw new CliError(`Cyclic OpenAPI reference: ${ref}`, 2, "invalid_spec");
|
|
407
|
+
let target = doc;
|
|
408
|
+
for (const part of ref.slice(2).split("/")) {
|
|
409
|
+
const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
410
|
+
const record = object(target, `reference ${ref}`);
|
|
411
|
+
if (!Object.hasOwn(record, key))
|
|
412
|
+
throw new CliError(`Unresolved OpenAPI reference: ${ref}`, 2, "invalid_spec");
|
|
413
|
+
target = record[key];
|
|
414
|
+
}
|
|
415
|
+
const { $ref: _ref, ...siblings } = node;
|
|
416
|
+
return resolve(doc, { ...object(target, `reference ${ref}`), ...siblings }, [...chain, ref]);
|
|
417
|
+
}
|
|
418
|
+
return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, resolve(doc, item, chain)]));
|
|
419
|
+
}
|
|
420
|
+
var APPROVALS = new Set(["none", "instruct", "confirm", "review", "forbidden_for_agents"]);
|
|
421
|
+
var METHODS = new Set(["get", "post", "put", "patch", "delete"]);
|
|
422
|
+
var PAGINATION = new Set(["limit", "offset", "cursor", "after", "page", "page_size", "pageSize", "per_page"]);
|
|
423
|
+
var WORD = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
|
|
424
|
+
var PARAM = /^\{[^}]+\}$/;
|
|
425
|
+
var RESERVED_FIRST = new Set(["auth", "help"]);
|
|
426
|
+
function serverBasePath(spec) {
|
|
427
|
+
const servers = spec?.servers;
|
|
428
|
+
const first = Array.isArray(servers) ? servers[0] : undefined;
|
|
429
|
+
if (!first || typeof first.url !== "string" || first.url.includes("{"))
|
|
430
|
+
return "";
|
|
431
|
+
try {
|
|
432
|
+
return new URL(first.url, "https://server.invalid").pathname.replace(/\/+$/, "");
|
|
433
|
+
} catch {
|
|
434
|
+
return "";
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function serverOrigin(spec) {
|
|
438
|
+
const servers = spec?.servers;
|
|
439
|
+
const first = Array.isArray(servers) ? servers[0] : undefined;
|
|
440
|
+
if (!first || typeof first.url !== "string" || !/^https?:\/\//i.test(first.url) || first.url.includes("{"))
|
|
441
|
+
return;
|
|
442
|
+
try {
|
|
443
|
+
return new URL(first.url).origin;
|
|
444
|
+
} catch {
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function annotatedWords(value, label) {
|
|
449
|
+
if (value === undefined)
|
|
450
|
+
return;
|
|
451
|
+
const command = typeof value === "string" ? value : value && typeof value === "object" && !Array.isArray(value) ? value.command : undefined;
|
|
452
|
+
const words = typeof command === "string" ? command.trim().split(/\s+/) : [];
|
|
453
|
+
if (!words.length || words.length > 3 || !words.every((word) => WORD.test(word)))
|
|
454
|
+
throw new CliError(`Invalid x-prudai-cli: ${label}`, 2, "invalid_spec");
|
|
455
|
+
return words;
|
|
456
|
+
}
|
|
457
|
+
function generateCommands(product, spec, options = {}) {
|
|
458
|
+
if (!/^[a-z][a-z0-9-]*$/.test(product))
|
|
459
|
+
throw new CliError("Invalid product name", 2, "invalid_spec");
|
|
460
|
+
const doc = object(spec, "document");
|
|
461
|
+
if (typeof doc.openapi !== "string" || !/^3\.1\./.test(doc.openapi)) {
|
|
462
|
+
throw new CliError("Expected an OpenAPI 3.1 specification", 2, "invalid_spec");
|
|
463
|
+
}
|
|
464
|
+
const base = serverBasePath(doc);
|
|
465
|
+
const items = new Map;
|
|
466
|
+
for (const [specPath, item] of Object.entries(object(doc.paths, "paths"))) {
|
|
467
|
+
const path = `${base}${specPath}`;
|
|
468
|
+
if (!path.startsWith("/v1/"))
|
|
469
|
+
continue;
|
|
470
|
+
items.set(path, object(resolve(doc, item), `path ${specPath}`));
|
|
471
|
+
}
|
|
472
|
+
const hasItemChild = (path) => [...items.keys()].some((other) => other.startsWith(`${path}/{`));
|
|
473
|
+
const itemHasPatch = (path) => [...items].some(([other, item]) => other.startsWith(`${path}/{`) && !other.slice(path.length + 1).includes("/") && ("patch" in item));
|
|
474
|
+
const drafts = [];
|
|
475
|
+
for (const [path, pathItem] of items) {
|
|
476
|
+
const segments = path.slice(4).split("/");
|
|
477
|
+
const statics = segments.filter((part) => !PARAM.test(part));
|
|
478
|
+
if (!statics.length || !statics.every((word) => WORD.test(word)))
|
|
479
|
+
throw new CliError(`Invalid resource path: ${path}`, 2, "invalid_spec");
|
|
480
|
+
if (RESERVED_FIRST.has(statics[0]))
|
|
481
|
+
continue;
|
|
482
|
+
const endsWithParam = PARAM.test(segments.at(-1));
|
|
483
|
+
const last = statics.at(-1);
|
|
484
|
+
for (const [method, rawOperation] of Object.entries(pathItem)) {
|
|
485
|
+
if (!METHODS.has(method))
|
|
486
|
+
continue;
|
|
487
|
+
const op = object(rawOperation, `operation ${method} ${path}`);
|
|
488
|
+
const write = method !== "get";
|
|
489
|
+
const approvalValue = op["x-prudai-approval"];
|
|
490
|
+
let approval = typeof approvalValue === "string" ? approvalValue : approvalValue && typeof approvalValue === "object" ? approvalValue.level : write ? undefined : "none";
|
|
491
|
+
let approvalSource = "spec";
|
|
492
|
+
if (approvalValue === undefined && write && options.lenientApproval) {
|
|
493
|
+
approval = method === "delete" ? "review" : "confirm";
|
|
494
|
+
approvalSource = "default";
|
|
495
|
+
}
|
|
496
|
+
if (typeof approval !== "string" || !APPROVALS.has(approval)) {
|
|
497
|
+
throw new CliError(`Missing or invalid x-prudai-approval: ${method.toUpperCase()} ${path}`, 2, "invalid_spec");
|
|
498
|
+
}
|
|
499
|
+
const parameters = new Map;
|
|
500
|
+
for (const candidate of [...Array.isArray(pathItem.parameters) ? pathItem.parameters : [], ...Array.isArray(op.parameters) ? op.parameters : []]) {
|
|
501
|
+
const parameter = object(candidate, "parameter");
|
|
502
|
+
if (typeof parameter.name !== "string" || typeof parameter.in !== "string")
|
|
503
|
+
throw new CliError("Invalid OpenAPI parameter", 2, "invalid_spec");
|
|
504
|
+
parameters.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
505
|
+
}
|
|
506
|
+
const params = [...parameters.values()];
|
|
507
|
+
const all = statics.join("-");
|
|
508
|
+
const hasParam = segments.some((part) => PARAM.test(part));
|
|
509
|
+
const firstLast = statics.length === 1 ? [statics[0]] : hasParam ? [statics.slice(0, -1).join("-"), last] : [statics[0], last];
|
|
510
|
+
const allButLast = statics.length === 1 ? [last] : [statics.slice(0, -1).join("-"), last];
|
|
511
|
+
let kind;
|
|
512
|
+
let preferred;
|
|
513
|
+
let fallback;
|
|
514
|
+
if (method === "get") {
|
|
515
|
+
const collection = hasItemChild(path) || "post" in pathItem || statics.length === 1 && params.some((p) => p.in === "query" && PAGINATION.has(p.name));
|
|
516
|
+
if (endsWithParam) {
|
|
517
|
+
kind = "get";
|
|
518
|
+
preferred = fallback = [all, "get"];
|
|
519
|
+
} else if (collection) {
|
|
520
|
+
kind = "list";
|
|
521
|
+
preferred = fallback = [all, "list"];
|
|
522
|
+
} else {
|
|
523
|
+
kind = "read";
|
|
524
|
+
preferred = firstLast;
|
|
525
|
+
fallback = allButLast;
|
|
526
|
+
}
|
|
527
|
+
} else if (method === "post") {
|
|
528
|
+
const collection = !endsWithParam && (statics.length === 1 || hasItemChild(path) || ("get" in pathItem));
|
|
529
|
+
if (collection) {
|
|
530
|
+
kind = "create";
|
|
531
|
+
preferred = fallback = [all, "create"];
|
|
532
|
+
} else if (endsWithParam) {
|
|
533
|
+
kind = "action";
|
|
534
|
+
preferred = fallback = [all, "post"];
|
|
535
|
+
} else {
|
|
536
|
+
kind = last === "restore" ? "restore" : "action";
|
|
537
|
+
preferred = firstLast;
|
|
538
|
+
fallback = allButLast;
|
|
539
|
+
}
|
|
540
|
+
} else if (method === "delete") {
|
|
541
|
+
kind = "delete";
|
|
542
|
+
preferred = fallback = [all, "delete"];
|
|
543
|
+
} else if (method === "put" && (("patch" in pathItem) || !endsWithParam && itemHasPatch(path))) {
|
|
544
|
+
kind = "replace";
|
|
545
|
+
preferred = fallback = [all, "replace"];
|
|
546
|
+
} else {
|
|
547
|
+
kind = "update";
|
|
548
|
+
preferred = fallback = [all, "update"];
|
|
549
|
+
}
|
|
550
|
+
const label = `${method.toUpperCase()} ${path}`;
|
|
551
|
+
const pinned = annotatedWords(op["x-prudai-cli"], label);
|
|
552
|
+
if (pinned)
|
|
553
|
+
preferred = fallback = pinned;
|
|
554
|
+
const operationId = typeof op.operationId === "string" ? op.operationId : `${method} ${path}`;
|
|
555
|
+
const body = op.requestBody ? object(op.requestBody, "request body") : undefined;
|
|
556
|
+
const content = body?.content ? object(body.content, "request content") : undefined;
|
|
557
|
+
const jsonBody = content?.["application/json"] ? object(content["application/json"], "JSON request content") : undefined;
|
|
558
|
+
const multipart = !jsonBody && !!content?.["multipart/form-data"];
|
|
559
|
+
const security = op.security ?? doc.security;
|
|
560
|
+
const securityScopes = Array.isArray(security) ? security.flatMap((requirement) => Object.values(object(requirement, "security")).flatMap((values) => Array.isArray(values) ? values.filter((v) => typeof v === "string") : [])) : [];
|
|
561
|
+
const explicitScopes = typeof op["x-prudai-scope"] === "string" ? [op["x-prudai-scope"]] : op["x-prudai-scopes"];
|
|
562
|
+
if (explicitScopes !== undefined && (!Array.isArray(explicitScopes) || !explicitScopes.every((value) => typeof value === "string"))) {
|
|
563
|
+
throw new CliError(`Invalid x-prudai-scopes: ${label}`, 2, "invalid_spec");
|
|
564
|
+
}
|
|
565
|
+
const scopes = [...new Set([...securityScopes, ...explicitScopes ?? []])];
|
|
566
|
+
const placeholders = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
567
|
+
const requiredQuery = params.filter((p) => p.in === "query" && p.required === true).map((p) => p.name);
|
|
568
|
+
const declaresKey = params.some((p) => p.in === "header" && p.name.toLowerCase() === "idempotency-key");
|
|
569
|
+
const declaresDryRun = params.some((p) => p.in === "query" && p.name === "dryRun") || op["x-prudai-dry-run"] === true || doc["x-prudai-dry-run"] === true && op["x-prudai-dry-run"] !== false;
|
|
570
|
+
drafts.push({ preferred, fallback, pinned: !!pinned, command: {
|
|
571
|
+
product,
|
|
572
|
+
kind,
|
|
573
|
+
method: method.toUpperCase(),
|
|
574
|
+
path,
|
|
575
|
+
operationId,
|
|
576
|
+
summary: typeof op.summary === "string" ? op.summary : operationId,
|
|
577
|
+
approval,
|
|
578
|
+
parameters: params,
|
|
579
|
+
positionals: [...placeholders, ...requiredQuery],
|
|
580
|
+
idempotencyKey: write,
|
|
581
|
+
idempotencyDeclared: write && declaresKey,
|
|
582
|
+
dryRun: write && declaresDryRun,
|
|
583
|
+
...jsonBody?.schema !== undefined ? { inputSchema: jsonBody.schema } : {},
|
|
584
|
+
...body?.required === true && !multipart ? { bodyRequired: true } : {},
|
|
585
|
+
...multipart ? { multipart: true } : {},
|
|
586
|
+
...scopes.length ? { scopes } : {},
|
|
587
|
+
...approvalSource === "default" ? { approvalSource } : {},
|
|
588
|
+
...describeOperation(doc, op, scopes)
|
|
589
|
+
} });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
const count = new Map;
|
|
593
|
+
for (const draft of drafts)
|
|
594
|
+
count.set(draft.preferred.join(" "), (count.get(draft.preferred.join(" ")) ?? 0) + 1);
|
|
595
|
+
const named = drafts.map((draft) => {
|
|
596
|
+
const words = !draft.pinned && count.get(draft.preferred.join(" ")) > 1 ? draft.fallback : draft.preferred;
|
|
597
|
+
return { draft, words, name: words.join(" ") };
|
|
598
|
+
});
|
|
599
|
+
const byName = new Map;
|
|
600
|
+
for (const entry of named)
|
|
601
|
+
byName.set(entry.name, [...byName.get(entry.name) ?? [], entry]);
|
|
602
|
+
const commands = [];
|
|
603
|
+
for (const [name, entries] of byName) {
|
|
604
|
+
if (entries.length > 1) {
|
|
605
|
+
if (!options.onAmbiguous)
|
|
606
|
+
throw new CliError(`Ambiguous generated command: ${product} ${name}. Pin names with x-prudai-cli.`, 2, "invalid_spec");
|
|
607
|
+
options.onAmbiguous(name, entries.map(({ draft: draft2 }) => `${draft2.command.method} ${draft2.command.path}`));
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
const { draft, words } = entries[0];
|
|
611
|
+
commands.push({ ...draft.command, name, words, resource: words.length === 1 ? words[0] : words.slice(0, -1).join(" "), action: words.length === 1 ? "" : words.at(-1) });
|
|
612
|
+
}
|
|
613
|
+
return commands;
|
|
614
|
+
}
|
|
615
|
+
function describeOperation(doc, op, scopes) {
|
|
616
|
+
const out = {};
|
|
617
|
+
if (typeof op.description === "string" && op.description.trim())
|
|
618
|
+
out.description = op.description.trim();
|
|
619
|
+
if (Array.isArray(op.tags)) {
|
|
620
|
+
const tags = op.tags.filter((tag) => typeof tag === "string");
|
|
621
|
+
if (tags.length)
|
|
622
|
+
out.tags = tags;
|
|
623
|
+
}
|
|
624
|
+
if (typeof op["x-prudai-status"] === "string")
|
|
625
|
+
out.status = op["x-prudai-status"];
|
|
626
|
+
if (op.deprecated === true)
|
|
627
|
+
out.deprecated = true;
|
|
628
|
+
const explicit = op["x-prudai-cost"] ?? op["x-prudai-credits"];
|
|
629
|
+
if (typeof explicit === "string" || typeof explicit === "number")
|
|
630
|
+
out.cost = String(explicit);
|
|
631
|
+
else if (explicit && typeof explicit === "object")
|
|
632
|
+
out.cost = JSON.stringify(explicit);
|
|
633
|
+
else {
|
|
634
|
+
const objects = doc["x-prudai-scope-objects"] && typeof doc["x-prudai-scope-objects"] === "object" ? doc["x-prudai-scope-objects"] : {};
|
|
635
|
+
const spends = scopes.some((scope) => {
|
|
636
|
+
const entry = objects[scope.split(":").slice(0, 2).join(":")];
|
|
637
|
+
return typeof entry?.description === "string" && /spends credits/i.test(entry.description);
|
|
638
|
+
});
|
|
639
|
+
if (spends)
|
|
640
|
+
out.cost = "credits (metered)";
|
|
641
|
+
}
|
|
642
|
+
if (op.responses && typeof op.responses === "object") {
|
|
643
|
+
out.responses = Object.entries(op.responses).map(([status, response]) => ({
|
|
644
|
+
status,
|
|
645
|
+
description: response && typeof response === "object" && typeof response.description === "string" ? response.description.trim().split(`
|
|
646
|
+
`)[0] : ""
|
|
647
|
+
}));
|
|
648
|
+
}
|
|
649
|
+
return out;
|
|
650
|
+
}
|
|
651
|
+
var MAX_SPEC_BYTES = 32 * 1024 * 1024;
|
|
652
|
+
var specTooLarge = () => new CliError(`Specification is larger than ${MAX_SPEC_BYTES / 1024 / 1024} MB`, 2, "invalid_spec");
|
|
653
|
+
async function loadSpec(source, fetchImpl = fetch) {
|
|
654
|
+
let text;
|
|
655
|
+
if (/^https?:\/\//i.test(source)) {
|
|
656
|
+
const url = secureUrl(source);
|
|
657
|
+
try {
|
|
658
|
+
const response = await fetchImpl(url, { redirect: "error", signal: AbortSignal.timeout(15000) });
|
|
659
|
+
if (!response.ok)
|
|
660
|
+
throw new CliError(`Could not load specification (HTTP ${response.status})`, response.status >= 400 && response.status < 500 ? 2 : 1, "spec_fetch_failed");
|
|
661
|
+
if (Number(response.headers.get("content-length")) > MAX_SPEC_BYTES)
|
|
662
|
+
throw specTooLarge();
|
|
663
|
+
text = await response.text();
|
|
664
|
+
if (text.length > MAX_SPEC_BYTES)
|
|
665
|
+
throw specTooLarge();
|
|
666
|
+
} catch (error) {
|
|
667
|
+
if (error instanceof CliError)
|
|
668
|
+
throw error;
|
|
669
|
+
throw new CliError("Could not fetch specification", 1, "spec_fetch_failed");
|
|
670
|
+
}
|
|
671
|
+
} else {
|
|
672
|
+
try {
|
|
673
|
+
if ((await stat(source)).size > MAX_SPEC_BYTES)
|
|
674
|
+
throw specTooLarge();
|
|
675
|
+
text = await readFile(source, "utf8");
|
|
676
|
+
} catch (error) {
|
|
677
|
+
if (error instanceof CliError)
|
|
678
|
+
throw error;
|
|
679
|
+
throw new CliError("Could not read specification file", 2, "invalid_spec");
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (text.charCodeAt(0) === 65279)
|
|
683
|
+
text = text.slice(1);
|
|
684
|
+
try {
|
|
685
|
+
const parsed = text.trimStart().startsWith("{") ? JSON.parse(text) : parseYaml(text, { logLevel: "error", merge: true, uniqueKeys: false });
|
|
686
|
+
return object(parsed, "document");
|
|
687
|
+
} catch (error) {
|
|
688
|
+
if (error instanceof CliError)
|
|
689
|
+
throw error;
|
|
690
|
+
throw new CliError("Specification must contain valid JSON or YAML", 2, "invalid_spec");
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
function isSafeHeaderName(name) {
|
|
694
|
+
return /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) && !/(auth|token|api[-_]?key|secret|cookie)/i.test(name) && !/^(host|connection|content-length|content-type|transfer-encoding|upgrade|te|trailer|proxy-.*|x-prudai-agent)$/i.test(name);
|
|
695
|
+
}
|
|
696
|
+
function validateInput(value, schema, label) {
|
|
697
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema))
|
|
698
|
+
return;
|
|
699
|
+
const node = schema;
|
|
700
|
+
const invalid = (detail) => {
|
|
701
|
+
throw new CliError(`Invalid ${label}: ${detail}`, 2, "invalid_parameter");
|
|
702
|
+
};
|
|
703
|
+
const types = Array.isArray(node.type) ? node.type : node.type ? [node.type] : [];
|
|
704
|
+
if (types.length && !types.some((type) => {
|
|
705
|
+
if (type === "null")
|
|
706
|
+
return value === null;
|
|
707
|
+
if (type === "array")
|
|
708
|
+
return Array.isArray(value);
|
|
709
|
+
if (type === "object")
|
|
710
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
711
|
+
if (type === "integer")
|
|
712
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
713
|
+
if (type === "number")
|
|
714
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
715
|
+
return typeof value === type;
|
|
716
|
+
}))
|
|
717
|
+
invalid(`expected ${types.join(" or ")}`);
|
|
718
|
+
if (Array.isArray(node.enum) && !node.enum.some((candidate) => JSON.stringify(candidate) === JSON.stringify(value)))
|
|
719
|
+
invalid("value is outside enum");
|
|
720
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
721
|
+
const record = value;
|
|
722
|
+
if (Array.isArray(node.required)) {
|
|
723
|
+
for (const key of node.required)
|
|
724
|
+
if (typeof key === "string" && !Object.hasOwn(record, key))
|
|
725
|
+
invalid(`missing required field ${key}`);
|
|
726
|
+
}
|
|
727
|
+
if (node.properties && typeof node.properties === "object" && !Array.isArray(node.properties)) {
|
|
728
|
+
for (const [key, child] of Object.entries(node.properties))
|
|
729
|
+
if (Object.hasOwn(record, key))
|
|
730
|
+
validateInput(record[key], child, `${label}.${key}`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
if (Array.isArray(value) && node.items)
|
|
734
|
+
value.forEach((item, index) => validateInput(item, node.items, `${label}[${index}]`));
|
|
735
|
+
}
|
|
736
|
+
function buildOperationRequest(command, args = {}) {
|
|
737
|
+
if (command.approval === "forbidden_for_agents")
|
|
738
|
+
throw new CliError("This operation is forbidden for agents; use the app", 2, "forbidden_for_agents");
|
|
739
|
+
if (command.bodyRequired && args.body === undefined)
|
|
740
|
+
throw new CliError("Missing required request body; use --data", 2, "missing_parameter");
|
|
741
|
+
if (args.body !== undefined)
|
|
742
|
+
validateInput(args.body, command.inputSchema, "request body");
|
|
743
|
+
const placeholders = [...command.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
744
|
+
const path = command.path.replace(/\{([^}]+)\}/g, (_match, name) => {
|
|
745
|
+
const value = args.params?.[name] ?? (name === "id" || placeholders.length === 1 ? args.id : undefined);
|
|
746
|
+
if (!value)
|
|
747
|
+
throw new CliError(`Missing path parameter: ${name}`, 2, "missing_parameter");
|
|
748
|
+
if (value === "." || value === "..")
|
|
749
|
+
throw new CliError(`Invalid path parameter: ${name}`, 2, "invalid_parameter");
|
|
750
|
+
return encodeURIComponent(value);
|
|
751
|
+
});
|
|
752
|
+
const query = new URLSearchParams;
|
|
753
|
+
for (const [name, value] of Object.entries(args.query ?? {})) {
|
|
754
|
+
if (value === undefined || value === null)
|
|
755
|
+
continue;
|
|
756
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
757
|
+
if (!["string", "number", "boolean"].includes(typeof item))
|
|
758
|
+
throw new CliError(`Invalid query parameter: ${name}`, 2, "invalid_parameter");
|
|
759
|
+
query.append(name, String(item));
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (command.method !== "GET" && !command.readsViaPost) {
|
|
763
|
+
query.delete("dryRun");
|
|
764
|
+
if (command.dryRun)
|
|
765
|
+
query.set("dryRun", String(args.dryRun !== false));
|
|
766
|
+
else if (args.dryRun !== false)
|
|
767
|
+
throw new CliError(`${command.method} ${command.path} declares no dry run, so nothing was sent. Check the request, then use --no-dry-run --yes to execute it.`, 2, "dry_run_unsupported");
|
|
768
|
+
}
|
|
769
|
+
for (const parameter of command.parameters) {
|
|
770
|
+
if (parameter.required === true && parameter.in === "query" && !query.has(String(parameter.name)))
|
|
771
|
+
throw new CliError(`Missing query parameter: ${parameter.name}`, 2, "missing_parameter");
|
|
772
|
+
if (parameter.in !== "query" || !query.has(parameter.name))
|
|
773
|
+
continue;
|
|
774
|
+
const schema = parameter.schema;
|
|
775
|
+
const values = query.getAll(parameter.name);
|
|
776
|
+
for (const value of values) {
|
|
777
|
+
const valueSchema = schema?.type === "array" ? schema.items : schema;
|
|
778
|
+
let parsed = value;
|
|
779
|
+
if (valueSchema?.type === "integer" || valueSchema?.type === "number")
|
|
780
|
+
parsed = value.trim() === "" ? NaN : Number(value);
|
|
781
|
+
else if (valueSchema?.type === "boolean")
|
|
782
|
+
parsed = value === "true" ? true : value === "false" ? false : value;
|
|
783
|
+
validateInput(parsed, valueSchema, `query parameter ${parameter.name}`);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
const headers = {};
|
|
787
|
+
const declaredHeaders = new Map(command.parameters.filter((parameter) => parameter.in === "header").map((parameter) => [parameter.name.toLowerCase(), parameter]));
|
|
788
|
+
const suppliedHeaders = new Map;
|
|
789
|
+
for (const [name, value] of Object.entries(args.headers ?? {})) {
|
|
790
|
+
const normalized = name.toLowerCase();
|
|
791
|
+
if (!isSafeHeaderName(name))
|
|
792
|
+
throw new CliError(`Header cannot be supplied as input: ${name}`, 2, "invalid_parameter");
|
|
793
|
+
if (!declaredHeaders.has(normalized) && normalized !== "if-match" && normalized !== "idempotency-key")
|
|
794
|
+
throw new CliError(`Undeclared header parameter: ${name}`, 2, "invalid_parameter");
|
|
795
|
+
if (typeof value !== "string" || /[^\t\x20-\x7e\x80-\xff]/.test(value))
|
|
796
|
+
throw new CliError(`Invalid header parameter: ${name}`, 2, "invalid_parameter");
|
|
797
|
+
if (suppliedHeaders.has(normalized))
|
|
798
|
+
throw new CliError(`Duplicate header parameter: ${name}`, 2, "invalid_parameter");
|
|
799
|
+
suppliedHeaders.set(normalized, value);
|
|
800
|
+
}
|
|
801
|
+
if (command.idempotencyKey || args.idempotencyKey !== undefined || suppliedHeaders.has("idempotency-key")) {
|
|
802
|
+
const suppliedKey = suppliedHeaders.get("idempotency-key");
|
|
803
|
+
if (suppliedKey && args.idempotencyKey && suppliedKey !== args.idempotencyKey)
|
|
804
|
+
throw new CliError("Conflicting Idempotency-Key inputs", 2, "invalid_parameter");
|
|
805
|
+
suppliedHeaders.set("idempotency-key", args.idempotencyKey ?? suppliedKey ?? crypto.randomUUID());
|
|
806
|
+
}
|
|
807
|
+
for (const parameter of command.parameters) {
|
|
808
|
+
if (parameter.in === "cookie" && parameter.required)
|
|
809
|
+
throw new CliError("Required cookie parameters are unsupported; use token authentication", 2, "invalid_parameter");
|
|
810
|
+
if (parameter.in !== "header")
|
|
811
|
+
continue;
|
|
812
|
+
let value = suppliedHeaders.get(parameter.name.toLowerCase());
|
|
813
|
+
if (value === undefined && parameter.required && isSafeHeaderName(parameter.name)) {
|
|
814
|
+
const schema = parameter.schema;
|
|
815
|
+
const fixed = typeof schema?.const === "string" ? schema.const : Array.isArray(schema?.enum) && schema.enum.length === 1 && typeof schema.enum[0] === "string" ? schema.enum[0] : undefined;
|
|
816
|
+
if (fixed !== undefined && !/[^\t\x20-\x7e\x80-\xff]/.test(fixed)) {
|
|
817
|
+
value = fixed;
|
|
818
|
+
suppliedHeaders.set(parameter.name.toLowerCase(), fixed);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
if (parameter.required && value === undefined)
|
|
822
|
+
throw new CliError(`Missing header parameter: ${parameter.name}`, 2, "missing_parameter");
|
|
823
|
+
if (value !== undefined)
|
|
824
|
+
validateInput(value, parameter.schema, `header parameter ${parameter.name}`);
|
|
825
|
+
}
|
|
826
|
+
for (const [name, value] of suppliedHeaders)
|
|
827
|
+
headers[name === "idempotency-key" ? "Idempotency-Key" : name] = value;
|
|
828
|
+
if (headers["Idempotency-Key"] !== undefined) {
|
|
829
|
+
const key = headers["Idempotency-Key"];
|
|
830
|
+
if (!key.trim() || /[^\t\x20-\x7e\x80-\xff]/.test(key))
|
|
831
|
+
throw new CliError("Invalid Idempotency-Key", 2, "invalid_parameter");
|
|
832
|
+
}
|
|
833
|
+
if (args.body !== undefined)
|
|
834
|
+
headers["Content-Type"] = "application/json";
|
|
835
|
+
return { method: command.method, path: query.size ? `${path}?${query}` : path, ...args.body !== undefined ? { body: args.body } : {}, headers };
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// src/products.ts
|
|
839
|
+
var PRODUCTS = [
|
|
840
|
+
{
|
|
841
|
+
product: "leo",
|
|
842
|
+
aliases: [],
|
|
843
|
+
title: "LEO and the Prudai platform API (models, chat, sources, citations, account, usage, credits)",
|
|
844
|
+
scopeProducts: ["prudai", "account"],
|
|
845
|
+
origin: "https://api.prudai.com",
|
|
846
|
+
liveSpecPath: "/v1/openapi.json"
|
|
847
|
+
},
|
|
848
|
+
{
|
|
849
|
+
product: "irma",
|
|
850
|
+
aliases: [],
|
|
851
|
+
title: "IRMA — GRC/ISMS (risks, controls, incidents, audits, registers)",
|
|
852
|
+
scopeProducts: ["irma"],
|
|
853
|
+
origin: "https://api.irma.prudai.com",
|
|
854
|
+
liveSpecPath: "/v1/openapi.json",
|
|
855
|
+
bundled: "irma.json",
|
|
856
|
+
approvalsPath: "/approvals",
|
|
857
|
+
mcpUrl: "https://api.irma.prudai.com/mcp"
|
|
858
|
+
},
|
|
859
|
+
{
|
|
860
|
+
product: "ordo",
|
|
861
|
+
aliases: [],
|
|
862
|
+
title: "ORDO — legal practice management and DMS (matters, documents, time, deadlines)",
|
|
863
|
+
scopeProducts: ["ordo"],
|
|
864
|
+
origin: "https://api.ordo.prudai.com",
|
|
865
|
+
liveSpecPath: "/v1/openapi.json"
|
|
866
|
+
}
|
|
867
|
+
];
|
|
868
|
+
var PLATFORM_PRODUCT = "leo";
|
|
869
|
+
var MCP_GATEWAY = "https://mcp.prudai.com";
|
|
870
|
+
var CONSOLE_URL = "https://account.prudai.com";
|
|
871
|
+
function findProduct(word) {
|
|
872
|
+
return PRODUCTS.find((entry) => entry.product === word || entry.aliases.includes(word));
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// src/catalog.ts
|
|
876
|
+
var POSITIVE_TTL_MS = 24 * 3600000;
|
|
877
|
+
var NEGATIVE_TTL_MS = 3600000;
|
|
878
|
+
var LIVE_TIMEOUT_MS = 4000;
|
|
879
|
+
var manifestCache;
|
|
880
|
+
function bundledPath(name) {
|
|
881
|
+
for (const candidate of [new URL(`./specs/${name}`, import.meta.url), new URL(`../specs/${name}`, import.meta.url)]) {
|
|
882
|
+
if (existsSync(candidate))
|
|
883
|
+
return candidate.pathname;
|
|
884
|
+
}
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
function bundledManifest() {
|
|
888
|
+
if (!manifestCache) {
|
|
889
|
+
const path = bundledPath("manifest.json");
|
|
890
|
+
manifestCache = path ? JSON.parse(readFileSync(path, "utf8")) : { products: {} };
|
|
891
|
+
}
|
|
892
|
+
return manifestCache;
|
|
893
|
+
}
|
|
894
|
+
function readBundledJson(name) {
|
|
895
|
+
const path = bundledPath(name);
|
|
896
|
+
return path ? JSON.parse(readFileSync(path, "utf8")) : undefined;
|
|
897
|
+
}
|
|
898
|
+
function cacheDir(env) {
|
|
899
|
+
if (env.PRUDAI_CACHE_DIR)
|
|
900
|
+
return env.PRUDAI_CACHE_DIR;
|
|
901
|
+
if (env.XDG_CACHE_HOME)
|
|
902
|
+
return join(env.XDG_CACHE_HOME, "prudai");
|
|
903
|
+
return env.HOME ? join(env.HOME, ".cache", "prudai") : undefined;
|
|
904
|
+
}
|
|
905
|
+
function readCache(env, product) {
|
|
906
|
+
const dir = cacheDir(env);
|
|
907
|
+
if (!dir)
|
|
908
|
+
return;
|
|
909
|
+
try {
|
|
910
|
+
return JSON.parse(readFileSync(join(dir, "specs", `${product}.json`), "utf8"));
|
|
911
|
+
} catch {
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
function writeCache(env, product, entry) {
|
|
916
|
+
const dir = cacheDir(env);
|
|
917
|
+
if (!dir)
|
|
918
|
+
return;
|
|
919
|
+
try {
|
|
920
|
+
const path = join(dir, "specs", `${product}.json`);
|
|
921
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
922
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
923
|
+
writeFileSync(temporary, JSON.stringify(entry), { mode: 384 });
|
|
924
|
+
renameSync(temporary, path);
|
|
925
|
+
} catch {}
|
|
926
|
+
}
|
|
927
|
+
function isSpec(value) {
|
|
928
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && typeof value.openapi === "string" && !!value.paths && typeof value.paths === "object";
|
|
929
|
+
}
|
|
930
|
+
var hasLogin = (ctx) => ctx.hasLogin ? ctx.hasLogin() : true;
|
|
931
|
+
var notLoggedInMessage = (product) => `${product} shows its commands to a logged-in person only. Not logged in. Run \`prudai login\`.`;
|
|
932
|
+
async function liveSpec(info, ctx) {
|
|
933
|
+
if (!info.liveSpecPath)
|
|
934
|
+
return {};
|
|
935
|
+
const origin = ctx.originFor?.(info.product) ?? info.origin;
|
|
936
|
+
const url = `${origin.replace(/\/+$/, "")}${info.liveSpecPath}`;
|
|
937
|
+
const cached = readCache(ctx.env, info.product);
|
|
938
|
+
const age = cached ? ctx.now() - Date.parse(cached.fetchedAt) : Infinity;
|
|
939
|
+
if (cached && cached.url === url && !ctx.refresh) {
|
|
940
|
+
if (cached.ok && cached.spec && age < POSITIVE_TTL_MS)
|
|
941
|
+
return { spec: cached.spec, source: { kind: "cache", location: url, fetchedAt: cached.fetchedAt } };
|
|
942
|
+
const refusedAnonymous = !cached.ok && !cached.authed && (cached.status === 401 || cached.status === 403);
|
|
943
|
+
const retryWithLogin = refusedAnonymous && !!ctx.credentialFor && hasLogin(ctx);
|
|
944
|
+
if (refusedAnonymous && ctx.credentialFor && !retryWithLogin && age < NEGATIVE_TTL_MS)
|
|
945
|
+
return { note: `live spec refused without a login at ${url} (HTTP ${cached.status}, checked ${cached.fetchedAt})`, loginNeeded: notLoggedInMessage(info.product) };
|
|
946
|
+
if (!cached.ok && age < NEGATIVE_TTL_MS && !retryWithLogin)
|
|
947
|
+
return { note: `live spec unavailable at ${url} (HTTP ${cached.status ?? "error"}, checked ${cached.fetchedAt})` };
|
|
948
|
+
}
|
|
949
|
+
if (ctx.offline) {
|
|
950
|
+
return cached?.ok && cached.spec && cached.url === url ? { spec: cached.spec, source: { kind: "cache", location: url, fetchedAt: cached.fetchedAt, note: "stale cache (offline)" } } : {};
|
|
951
|
+
}
|
|
952
|
+
if (!isTrustedOrigin(url, ctx.env))
|
|
953
|
+
return { note: `live spec skipped: ${origin} is not a trusted origin` };
|
|
954
|
+
let status;
|
|
955
|
+
let authed = false;
|
|
956
|
+
let loginNeeded;
|
|
957
|
+
let credentialFailure;
|
|
958
|
+
const attempt = async (token) => {
|
|
959
|
+
const response = await ctx.fetch(secureUrl(url).href, { headers: { accept: "application/json", ...token ? { authorization: `Bearer ${token}` } : {} }, redirect: "error", signal: AbortSignal.timeout(LIVE_TIMEOUT_MS) });
|
|
960
|
+
status = response.status;
|
|
961
|
+
if (!response.ok)
|
|
962
|
+
return;
|
|
963
|
+
const parsed = JSON.parse(await response.text());
|
|
964
|
+
return isSpec(parsed) ? parsed : undefined;
|
|
965
|
+
};
|
|
966
|
+
try {
|
|
967
|
+
let parsed = await attempt();
|
|
968
|
+
if (!parsed && (status === 401 || status === 403) && ctx.credentialFor) {
|
|
969
|
+
if (!hasLogin(ctx))
|
|
970
|
+
loginNeeded = notLoggedInMessage(info.product);
|
|
971
|
+
else {
|
|
972
|
+
const token = await ctx.credentialFor(info.product).catch((error) => {
|
|
973
|
+
if (error instanceof CliError && error.code === "not_authenticated")
|
|
974
|
+
return;
|
|
975
|
+
credentialFailure = error instanceof CliError ? error : new CliError("The token broker could not be reached; try again in a moment.", 1, "exchange_unavailable");
|
|
976
|
+
return;
|
|
977
|
+
});
|
|
978
|
+
if (!token && !credentialFailure)
|
|
979
|
+
loginNeeded = notLoggedInMessage(info.product);
|
|
980
|
+
if (token) {
|
|
981
|
+
authed = true;
|
|
982
|
+
parsed = await attempt(token);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
if (parsed) {
|
|
987
|
+
const fetchedAt = new Date(ctx.now()).toISOString();
|
|
988
|
+
writeCache(ctx.env, info.product, { url, fetchedAt, ok: true, spec: parsed });
|
|
989
|
+
return { spec: parsed, source: { kind: "live", location: url, fetchedAt, ...authed ? { note: "served to a logged-in person only" } : {} } };
|
|
990
|
+
}
|
|
991
|
+
} catch {}
|
|
992
|
+
if (!credentialFailure)
|
|
993
|
+
writeCache(ctx.env, info.product, { url, fetchedAt: new Date(ctx.now()).toISOString(), ok: false, ...status ? { status } : {}, ...authed ? { authed } : {} });
|
|
994
|
+
if (cached?.ok && cached.spec && cached.url === url)
|
|
995
|
+
return { spec: cached.spec, source: { kind: "cache", location: url, fetchedAt: cached.fetchedAt, note: "stale cache; the live spec could not be fetched" } };
|
|
996
|
+
return { note: `live spec unavailable at ${url}${status ? ` (HTTP ${status})` : ""}`, ...loginNeeded ? { loginNeeded } : {}, ...credentialFailure ? { credentialFailure } : {} };
|
|
997
|
+
}
|
|
998
|
+
async function loadProductCatalog(word, ctx) {
|
|
999
|
+
const info = findProduct(word);
|
|
1000
|
+
const product = info?.product ?? word;
|
|
1001
|
+
const plugin = ctx.plugins?.find((entry) => entry.product === product);
|
|
1002
|
+
const base = {
|
|
1003
|
+
product,
|
|
1004
|
+
title: info?.title ?? product,
|
|
1005
|
+
origin: ctx.originFor?.(product) ?? plugin?.apiUrl ?? info?.origin ?? "",
|
|
1006
|
+
commands: [],
|
|
1007
|
+
warnings: [],
|
|
1008
|
+
scopeProducts: info?.scopeProducts ?? [product],
|
|
1009
|
+
...info?.approvalsPath ? { approvalsPath: info.approvalsPath } : {},
|
|
1010
|
+
...info?.mcpUrl ? { mcpUrl: info.mcpUrl } : {}
|
|
1011
|
+
};
|
|
1012
|
+
let spec;
|
|
1013
|
+
let source;
|
|
1014
|
+
let refusal = {};
|
|
1015
|
+
const explicit = ctx.explicitSpec?.(product);
|
|
1016
|
+
if (explicit) {
|
|
1017
|
+
spec = await loadSpec(explicit, ctx.fetch);
|
|
1018
|
+
source = { kind: "explicit", location: explicit };
|
|
1019
|
+
} else if (plugin) {
|
|
1020
|
+
spec = plugin.spec;
|
|
1021
|
+
source = { kind: "plugin", location: `plugin:${product}` };
|
|
1022
|
+
} else if (info) {
|
|
1023
|
+
const live = await liveSpec(info, ctx);
|
|
1024
|
+
if (live.note)
|
|
1025
|
+
base.liveNote = live.note;
|
|
1026
|
+
refusal = live;
|
|
1027
|
+
if (live.spec) {
|
|
1028
|
+
spec = live.spec;
|
|
1029
|
+
source = live.source;
|
|
1030
|
+
} else if (info.bundled) {
|
|
1031
|
+
const bundled = readBundledJson(info.bundled);
|
|
1032
|
+
const meta = bundledManifest().products[info.product];
|
|
1033
|
+
if (bundled) {
|
|
1034
|
+
spec = bundled;
|
|
1035
|
+
source = { kind: "bundled", location: `specs/${info.bundled}`, ref: meta?.ref, status: meta?.status, note: meta?.note };
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
if (!spec) {
|
|
1040
|
+
if (!info)
|
|
1041
|
+
return { ...base, error: `Unknown product "${word}". Run prudai products to list them, or pass --spec <path-or-url>.` };
|
|
1042
|
+
if (refusal.loginNeeded)
|
|
1043
|
+
return { ...base, loginNeeded: true, error: refusal.loginNeeded };
|
|
1044
|
+
if (refusal.credentialFailure)
|
|
1045
|
+
return { ...base, credentialFailure: { code: refusal.credentialFailure.code, exitCode: refusal.credentialFailure.exitCode }, error: refusal.credentialFailure.message };
|
|
1046
|
+
return { ...base, notAvailable: true, error: `${product} is not available yet: its /v1 spec is not served publicly (${base.liveNote ?? (ctx.offline ? "offline: the live spec was not fetched" : "the live spec was not fetched")}), and this CLI bundles only APIs that are live. Commands appear here once ${(base.origin || info.origin).replace(/\/+$/, "")}${info.liveSpecPath ?? "/v1/openapi.json"} is served; or pass --spec <path-or-url> for a contract you have.` };
|
|
1047
|
+
}
|
|
1048
|
+
try {
|
|
1049
|
+
const lenient = source?.kind !== "explicit" && source?.kind !== "plugin";
|
|
1050
|
+
const commands = generateCommands(product, spec, {
|
|
1051
|
+
lenientApproval: lenient,
|
|
1052
|
+
...lenient ? { onAmbiguous: (name, operations) => base.warnings.push(`${operations.length} operations share the generated name "${product} ${name}" (${operations.join(", ")}) and are left out; reach them with prudai api <METHOD> <path>, or the product pins names with x-prudai-cli.`) } : {}
|
|
1053
|
+
});
|
|
1054
|
+
const defaulted = commands.filter((command) => command.approvalSource === "default").length;
|
|
1055
|
+
if (defaulted)
|
|
1056
|
+
base.warnings.push(`${defaulted} write operation(s) declare no x-prudai-approval; the CLI assumes the default level (confirm, delete: review).`);
|
|
1057
|
+
if (!commands.length)
|
|
1058
|
+
base.warnings.push("The spec yielded 0 commands: no operations under /v1, directly (/v1/...) or through a servers base path (servers: https://api.prudai.com/v1).");
|
|
1059
|
+
return { ...base, source, commands, spec };
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
if (source?.kind === "explicit" || source?.kind === "plugin")
|
|
1062
|
+
throw error;
|
|
1063
|
+
return { ...base, source, error: error instanceof CliError ? error.message : "The spec could not be read." };
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
async function loadCatalog(ctx, only) {
|
|
1067
|
+
const words = only?.length ? only : [...PRODUCTS.map((entry) => entry.product), ...(ctx.plugins ?? []).map((entry) => entry.product).filter((name) => !findProduct(name))];
|
|
1068
|
+
return Promise.all(words.map((word) => loadProductCatalog(word, ctx)));
|
|
1069
|
+
}
|
|
1070
|
+
function commandLine(command) {
|
|
1071
|
+
return [command.commandLine ?? `prudai ${command.product} ${command.name}`, ...command.positionals.map((name) => `<${name}>`)].join(" ");
|
|
1072
|
+
}
|
|
1073
|
+
var tokens = (text) => text.toLowerCase().split(/[^a-z0-9à-ÿ]+/i).filter((token) => token.length > 1 || /\d/.test(token));
|
|
1074
|
+
function searchOperations(catalogs, query, filters = {}) {
|
|
1075
|
+
const terms = tokens(query);
|
|
1076
|
+
const hits = [];
|
|
1077
|
+
for (const catalog of catalogs) {
|
|
1078
|
+
if (filters.product && catalog.product !== (findProduct(filters.product)?.product ?? filters.product))
|
|
1079
|
+
continue;
|
|
1080
|
+
for (const command of catalog.commands) {
|
|
1081
|
+
if (filters.approval && command.approval !== filters.approval)
|
|
1082
|
+
continue;
|
|
1083
|
+
if (filters.method && command.method !== filters.method.toUpperCase())
|
|
1084
|
+
continue;
|
|
1085
|
+
const fields = [
|
|
1086
|
+
[`${command.commandLine ?? `${command.product} ${command.name}`}`, 5],
|
|
1087
|
+
[command.path, 3],
|
|
1088
|
+
[command.summary, 3],
|
|
1089
|
+
[command.operationId, 2],
|
|
1090
|
+
[(command.tags ?? []).join(" "), 2],
|
|
1091
|
+
[(command.scopes ?? []).join(" "), 2],
|
|
1092
|
+
[(command.description ?? "").replace(/idempotency-key/gi, ""), 1]
|
|
1093
|
+
];
|
|
1094
|
+
let score = 0;
|
|
1095
|
+
let matched = 0;
|
|
1096
|
+
for (const term of terms) {
|
|
1097
|
+
let best = 0;
|
|
1098
|
+
for (const [text, weight] of fields)
|
|
1099
|
+
if (text.toLowerCase().includes(term))
|
|
1100
|
+
best = Math.max(best, weight);
|
|
1101
|
+
if (best) {
|
|
1102
|
+
matched++;
|
|
1103
|
+
score += best;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
if (terms.length && !matched)
|
|
1107
|
+
continue;
|
|
1108
|
+
score += matched * 10;
|
|
1109
|
+
hits.push({
|
|
1110
|
+
command: commandLine(command),
|
|
1111
|
+
product: command.product,
|
|
1112
|
+
method: command.method,
|
|
1113
|
+
path: command.path,
|
|
1114
|
+
operationId: command.operationId,
|
|
1115
|
+
summary: command.summary,
|
|
1116
|
+
approval: command.approval,
|
|
1117
|
+
scopes: command.scopes ?? [],
|
|
1118
|
+
cost: command.cost ?? "not stated",
|
|
1119
|
+
dryRun: command.dryRun,
|
|
1120
|
+
...command.status ? { status: command.status } : {},
|
|
1121
|
+
...command.available === false ? { available: false } : {},
|
|
1122
|
+
score
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
return hits.sort((a, b) => b.score - a.score || a.command.localeCompare(b.command));
|
|
1127
|
+
}
|
|
1128
|
+
function findOperation(catalogs, ref) {
|
|
1129
|
+
const words = ref.flatMap((part) => part.split(/\s+/)).filter(Boolean);
|
|
1130
|
+
if (words[0] === "prudai")
|
|
1131
|
+
words.shift();
|
|
1132
|
+
const productFirst = words[0] ? findProduct(words[0])?.product ?? (catalogs.some((c) => c.product === words[0]) ? words[0] : undefined) : undefined;
|
|
1133
|
+
const scoped = productFirst ? catalogs.filter((catalog) => catalog.product === productFirst) : catalogs;
|
|
1134
|
+
const rest = productFirst ? words.slice(1) : words;
|
|
1135
|
+
const found = [];
|
|
1136
|
+
if (rest.length === 2 && /^(get|post|put|patch|delete)$/i.test(rest[0])) {
|
|
1137
|
+
const [method, path] = [rest[0].toUpperCase(), rest[1].split("?")[0]];
|
|
1138
|
+
for (const catalog of scoped)
|
|
1139
|
+
for (const command of catalog.commands)
|
|
1140
|
+
if (command.method === method && (command.path === path || templateMatches(command.path, path)))
|
|
1141
|
+
found.push({ catalog, command });
|
|
1142
|
+
} else if (rest.length === 1 && rest[0].includes(":") && !productFirst) {
|
|
1143
|
+
const [product, operationId] = rest[0].split(/:(.*)/s);
|
|
1144
|
+
for (const catalog of catalogs.filter((c) => c.product === (findProduct(product)?.product ?? product)))
|
|
1145
|
+
for (const command of catalog.commands)
|
|
1146
|
+
if (command.operationId === operationId)
|
|
1147
|
+
found.push({ catalog, command });
|
|
1148
|
+
} else {
|
|
1149
|
+
for (const catalog of scoped) {
|
|
1150
|
+
for (const command of catalog.commands) {
|
|
1151
|
+
if (productFirst && rest.slice(0, command.words.length).join(" ") === command.name && rest.length <= command.words.length + command.positionals.length)
|
|
1152
|
+
found.push({ catalog, command });
|
|
1153
|
+
else if (rest.length === 1 && command.operationId === rest[0])
|
|
1154
|
+
found.push({ catalog, command });
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
const longest = Math.max(0, ...found.map((entry) => entry.command.words.length));
|
|
1158
|
+
found.splice(0, found.length, ...found.filter((entry) => entry.command.words.length === longest || !productFirst));
|
|
1159
|
+
}
|
|
1160
|
+
const unique = [...new Map(found.map((entry) => [`${entry.catalog.product} ${entry.command.method} ${entry.command.path}`, entry])).values()];
|
|
1161
|
+
if (unique.length === 1)
|
|
1162
|
+
return unique[0];
|
|
1163
|
+
return { candidates: unique.map((entry) => commandLine(entry.command)) };
|
|
1164
|
+
}
|
|
1165
|
+
function templateMatches(template, path) {
|
|
1166
|
+
const a = template.split("/");
|
|
1167
|
+
const b = path.split("/");
|
|
1168
|
+
return a.length === b.length && a.every((part, index) => /^\{[^}]+\}$/.test(part) ? !!b[index] : part === b[index]);
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
// src/execute.ts
|
|
1172
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
1173
|
+
|
|
1174
|
+
// src/output.ts
|
|
1175
|
+
function localEnvelope(data, parts = {}) {
|
|
1176
|
+
const count = Array.isArray(data) ? data.length : undefined;
|
|
1177
|
+
return {
|
|
1178
|
+
data,
|
|
1179
|
+
context: parts.context ?? {},
|
|
1180
|
+
completeness: parts.completeness ?? (count !== undefined ? { returned: count, total: count, truncated: false } : { complete: true }),
|
|
1181
|
+
notIncluded: parts.notIncluded ?? [],
|
|
1182
|
+
provenance: parts.provenance ?? { kind: "cli" },
|
|
1183
|
+
next: parts.next ?? []
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
class DetailedCliError extends CliError {
|
|
1188
|
+
details;
|
|
1189
|
+
constructor(message, code, details, exitCode = 2) {
|
|
1190
|
+
super(message, exitCode, code);
|
|
1191
|
+
this.details = details;
|
|
1192
|
+
this.name = "DetailedCliError";
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
class NotAvailableError extends DetailedCliError {
|
|
1197
|
+
constructor(message, details) {
|
|
1198
|
+
super(message, "not_available", details);
|
|
1199
|
+
this.name = "NotAvailableError";
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
function throwIfUnusable(catalog) {
|
|
1203
|
+
if (catalog.notAvailable)
|
|
1204
|
+
throw productNotAvailable(catalog);
|
|
1205
|
+
if (catalog.loginNeeded)
|
|
1206
|
+
throw new CliError(catalog.error, 2, "not_authenticated");
|
|
1207
|
+
if (catalog.credentialFailure)
|
|
1208
|
+
throw new CliError(catalog.error, catalog.credentialFailure.exitCode, catalog.credentialFailure.code);
|
|
1209
|
+
}
|
|
1210
|
+
function productNotAvailable(catalog) {
|
|
1211
|
+
return new NotAvailableError(catalog.error, {
|
|
1212
|
+
product: catalog.product,
|
|
1213
|
+
...catalog.liveNote ? { liveSpec: catalog.liveNote } : {},
|
|
1214
|
+
next: ["prudai products shows which catalogues are available.", `Retry later with --refresh once the ${catalog.product} /v1 spec is served.`]
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
function errorDocument(error) {
|
|
1218
|
+
return { error: error.code, message: error.message, exitCode: error.exitCode, ...error instanceof DetailedCliError ? error.details : {} };
|
|
1219
|
+
}
|
|
1220
|
+
function isEnvelopeLike(body) {
|
|
1221
|
+
return isRecord(body) && "data" in body && "context" in body;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// src/approvals.ts
|
|
1225
|
+
var APPROVAL_POLL_MS = 5000;
|
|
1226
|
+
var TERMINAL = new Set(["rejected", "expired", "cancelled", "canceled", "executed", "failed"]);
|
|
1227
|
+
function target(ctx) {
|
|
1228
|
+
const word = str(ctx.flags, "product");
|
|
1229
|
+
const candidates = PRODUCTS.filter((entry) => entry.approvalsPath);
|
|
1230
|
+
const info = word ? findProduct(word) : candidates.length === 1 ? candidates[0] : undefined;
|
|
1231
|
+
if (!info)
|
|
1232
|
+
throw new CliError(`Name the product: --product ${candidates.map((entry) => entry.product).join("|")}.`);
|
|
1233
|
+
if (!info.approvalsPath) {
|
|
1234
|
+
throw new NotAvailableError(`${info.product} has no approvals API yet. Approve the request in the ${info.product} app.`, {
|
|
1235
|
+
planned: "GET /v1/approvals/{id} (central approvals on the developer platform)",
|
|
1236
|
+
next: [`Find the request in the ${info.product} app.`]
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
const origin = resolveOrigin(info.product, ctx);
|
|
1240
|
+
if (!origin)
|
|
1241
|
+
throw new CliError(`Configure the ${info.product} API origin.`);
|
|
1242
|
+
return { product: info.product, origin: safeApiOrigin(origin), approvalsPath: info.approvalsPath };
|
|
1243
|
+
}
|
|
1244
|
+
async function requireToken(ctx, product) {
|
|
1245
|
+
const token = await credentialFor(product, ctx);
|
|
1246
|
+
if (!token)
|
|
1247
|
+
throw missingCredential(product);
|
|
1248
|
+
return token;
|
|
1249
|
+
}
|
|
1250
|
+
async function call(ctx, t, method, suffix, body) {
|
|
1251
|
+
requireTrustedOrigin(t.origin, ctx.env);
|
|
1252
|
+
return requestJson(ctx.fetch, `${t.origin}${t.approvalsPath}${suffix}`, { method, token: await requireToken(ctx, t.product), env: ctx.env, ...body !== undefined ? { body } : {} });
|
|
1253
|
+
}
|
|
1254
|
+
function fail(status, body, what) {
|
|
1255
|
+
const error = httpError(status, body);
|
|
1256
|
+
throw new CliError(`${what}: ${error.message}`, error.exitCode, error.code);
|
|
1257
|
+
}
|
|
1258
|
+
var idOf = (value) => {
|
|
1259
|
+
if (!value || !/^[A-Za-z0-9_-]{1,100}$/.test(value))
|
|
1260
|
+
throw new CliError("Give the approval request id (from the 202 answer).");
|
|
1261
|
+
return value;
|
|
1262
|
+
};
|
|
1263
|
+
async function waitForApproval(ctx, opts) {
|
|
1264
|
+
const t = { product: opts.product, origin: opts.origin, approvalsPath: opts.approvalsPath };
|
|
1265
|
+
const deadline = ctx.now() + (opts.timeoutSeconds ?? 600) * 1000;
|
|
1266
|
+
let status = "pending";
|
|
1267
|
+
let last = {};
|
|
1268
|
+
for (;; ) {
|
|
1269
|
+
const response = await call(ctx, t, "GET", `/${encodeURIComponent(opts.id)}/status`);
|
|
1270
|
+
if (response.status !== 200 || !isRecord(response.body))
|
|
1271
|
+
fail(response.status, response.body, "Approval status");
|
|
1272
|
+
last = response.body;
|
|
1273
|
+
status = String(last.status ?? "unknown");
|
|
1274
|
+
if (status !== "pending")
|
|
1275
|
+
break;
|
|
1276
|
+
if (ctx.now() >= deadline) {
|
|
1277
|
+
throw new CliError(`Still pending after ${opts.timeoutSeconds ?? 600}s; nothing was executed. Run prudai approvals wait ${opts.id} --product ${opts.product} again later.`, 2, "approval_timeout");
|
|
1278
|
+
}
|
|
1279
|
+
await ctx.sleep(Math.min(APPROVAL_POLL_MS, Math.max(0, deadline - ctx.now())));
|
|
1280
|
+
}
|
|
1281
|
+
const summary = { id: opts.id, product: opts.product, status, level: last.level, operation: last.operation, executeUntil: last.executeUntil ?? null };
|
|
1282
|
+
if (status === "approved") {
|
|
1283
|
+
if (!opts.execute) {
|
|
1284
|
+
const next = `prudai approvals execute ${opts.id} --product ${opts.product}`;
|
|
1285
|
+
ctx.emit(localEnvelope(summary, { provenance: { kind: "product", product: opts.product }, next: [{ action: next, why: "The server runs exactly the approved call." }] }), `Approved. Run: ${next}`);
|
|
1286
|
+
return 0;
|
|
1287
|
+
}
|
|
1288
|
+
return executeApproved(ctx, t, opts.id);
|
|
1289
|
+
}
|
|
1290
|
+
if (TERMINAL.has(status)) {
|
|
1291
|
+
if (status === "executed") {
|
|
1292
|
+
ctx.emit(localEnvelope(summary, { provenance: { kind: "product", product: opts.product }, notIncluded: ["The result was returned to whoever executed it."] }), "Already executed.");
|
|
1293
|
+
return 0;
|
|
1294
|
+
}
|
|
1295
|
+
throw new CliError(`Approval request ${opts.id} is ${status}; nothing was executed.`, 2, `approval_${status}`);
|
|
1296
|
+
}
|
|
1297
|
+
throw new CliError(`Unexpected approval status "${status}".`, 1, "invalid_response");
|
|
1298
|
+
}
|
|
1299
|
+
async function executeApproved(ctx, t, id) {
|
|
1300
|
+
const response = await call(ctx, t, "POST", `/${encodeURIComponent(id)}/execute`);
|
|
1301
|
+
if (response.status !== 200 || !isRecord(response.body))
|
|
1302
|
+
fail(response.status, response.body, "Execute approved request");
|
|
1303
|
+
const executed = response.body;
|
|
1304
|
+
if (executed.status !== "executed" || typeof executed.resultStatus !== "number")
|
|
1305
|
+
throw new CliError("Unexpected execute response.", 1, "invalid_response");
|
|
1306
|
+
const result = executed.result;
|
|
1307
|
+
if (executed.resultStatus >= 400)
|
|
1308
|
+
throw new CliError(`The approved call ran and returned HTTP ${executed.resultStatus}.`, executed.resultStatus >= 500 ? 1 : 2, `http_${executed.resultStatus}`);
|
|
1309
|
+
const envelope = isEnvelopeLike(result) ? parseEnvelope(result) : localEnvelope(result ?? null, { provenance: { kind: "product", product: t.product }, context: { approvalRequestId: id, resultStatus: executed.resultStatus } });
|
|
1310
|
+
ctx.emit(envelope, renderEnvelope(envelope));
|
|
1311
|
+
return 0;
|
|
1312
|
+
}
|
|
1313
|
+
async function approvalsCommand(words, ctx) {
|
|
1314
|
+
validateFlags(ctx.flags, ["json", "profile", "product", "api-url", "timeout", "execute", "status", "scope", "limit", "help"]);
|
|
1315
|
+
const [action, id, ...extra] = words;
|
|
1316
|
+
if (extra.length)
|
|
1317
|
+
throw new CliError("Too many arguments.");
|
|
1318
|
+
if (action === "approve" || action === "reject" || action === "decide") {
|
|
1319
|
+
throw new CliError("Approving or rejecting is a human decision in the product app; the CLI never approves (forbidden_for_agents).", 2, "forbidden_for_agents");
|
|
1320
|
+
}
|
|
1321
|
+
const t = target(ctx);
|
|
1322
|
+
if (action === "list") {
|
|
1323
|
+
const status = str(ctx.flags, "status") ?? "pending";
|
|
1324
|
+
if (!["pending", "approved", "all"].includes(status))
|
|
1325
|
+
throw new CliError("--status is pending, approved or all.");
|
|
1326
|
+
const scope = str(ctx.flags, "scope") ?? "mine";
|
|
1327
|
+
if (!["mine", "to-review", "all"].includes(scope))
|
|
1328
|
+
throw new CliError("--scope is mine, to-review or all.");
|
|
1329
|
+
const limit = intFlag(ctx.flags, "limit", 50, 1, 200);
|
|
1330
|
+
const response = await call(ctx, t, "GET", `?scope=${scope}&status=${status}&limit=${limit}`);
|
|
1331
|
+
if (response.status !== 200 || !isRecord(response.body) || !Array.isArray(response.body.items))
|
|
1332
|
+
fail(response.status, response.body, "List approvals");
|
|
1333
|
+
const items = response.body.items;
|
|
1334
|
+
ctx.emit(localEnvelope(items, {
|
|
1335
|
+
provenance: { kind: "product", product: t.product },
|
|
1336
|
+
completeness: { returned: items.length, truncated: items.length >= limit },
|
|
1337
|
+
next: [{ action: `prudai approvals wait <id> --product ${t.product}`, why: "Wait for a decision." }]
|
|
1338
|
+
}));
|
|
1339
|
+
return 0;
|
|
1340
|
+
}
|
|
1341
|
+
if (action === "get" || action === "status") {
|
|
1342
|
+
const response = await call(ctx, t, "GET", `/${encodeURIComponent(idOf(id))}${action === "status" ? "/status" : ""}`);
|
|
1343
|
+
if (response.status !== 200)
|
|
1344
|
+
fail(response.status, response.body, "Approval lookup");
|
|
1345
|
+
ctx.emit(localEnvelope(response.body, { provenance: { kind: "product", product: t.product } }));
|
|
1346
|
+
return 0;
|
|
1347
|
+
}
|
|
1348
|
+
if (action === "wait") {
|
|
1349
|
+
return waitForApproval(ctx, { ...t, id: idOf(id), execute: !!ctx.flags.execute, timeoutSeconds: intFlag(ctx.flags, "timeout", 600, 5, 3600) });
|
|
1350
|
+
}
|
|
1351
|
+
if (action === "execute")
|
|
1352
|
+
return executeApproved(ctx, t, idOf(id));
|
|
1353
|
+
if (action === "cancel") {
|
|
1354
|
+
const response = await call(ctx, t, "POST", `/${encodeURIComponent(idOf(id))}/cancel`);
|
|
1355
|
+
if (response.status !== 200)
|
|
1356
|
+
fail(response.status, response.body, "Cancel approval");
|
|
1357
|
+
ctx.emit(localEnvelope(response.body, { provenance: { kind: "product", product: t.product } }));
|
|
1358
|
+
return 0;
|
|
1359
|
+
}
|
|
1360
|
+
throw new CliError("Usage: prudai approvals list|get <id>|status <id>|wait <id> [--execute] [--timeout s]|execute <id>|cancel <id> --product <product> (list: --status pending|approved|all --scope mine|to-review|all)");
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
// src/transfer.ts
|
|
1364
|
+
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
1365
|
+
import { accessSync, closeSync, constants, existsSync as existsSync2, fchmodSync, fstatSync, linkSync, lstatSync, openSync, renameSync as renameSync2, statSync, unlinkSync, writeSync } from "node:fs";
|
|
1366
|
+
import { open } from "node:fs/promises";
|
|
1367
|
+
import { basename, dirname as dirname2, extname, join as join2, resolve as resolve2 } from "node:path";
|
|
1368
|
+
var PRIVATE_MODE = 384;
|
|
1369
|
+
var CHUNK = 256 * 1024;
|
|
1370
|
+
var TEMPORARY_OVERHEAD = 1 + 1 + 8 + 5;
|
|
1371
|
+
var CONTENT_TYPES = {
|
|
1372
|
+
".m4a": "audio/mp4",
|
|
1373
|
+
".mp4": "audio/mp4",
|
|
1374
|
+
".webm": "audio/webm",
|
|
1375
|
+
".mp3": "audio/mpeg",
|
|
1376
|
+
".wav": "audio/wav",
|
|
1377
|
+
".ogg": "audio/ogg",
|
|
1378
|
+
".opus": "audio/opus",
|
|
1379
|
+
".aac": "audio/aac",
|
|
1380
|
+
".flac": "audio/flac",
|
|
1381
|
+
".vtt": "text/vtt",
|
|
1382
|
+
".srt": "application/x-subrip",
|
|
1383
|
+
".txt": "text/plain",
|
|
1384
|
+
".md": "text/markdown",
|
|
1385
|
+
".pdf": "application/pdf",
|
|
1386
|
+
".csv": "text/csv",
|
|
1387
|
+
".json": "application/json",
|
|
1388
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
1389
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
1390
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
|
1391
|
+
};
|
|
1392
|
+
var fileError = (message, code = "invalid_file") => new CliError(message, 2, code);
|
|
1393
|
+
function inspectUploadFile(raw, field = "file") {
|
|
1394
|
+
if (!raw.trim())
|
|
1395
|
+
throw fileError("Give the path of the file to upload.");
|
|
1396
|
+
const path = resolve2(raw);
|
|
1397
|
+
try {
|
|
1398
|
+
const seen = lstatSync(path);
|
|
1399
|
+
if (seen.isSymbolicLink())
|
|
1400
|
+
throw fileError(`${raw} is a symbolic link; pass the path of the real file. Nothing was sent.`);
|
|
1401
|
+
if (!seen.isFile())
|
|
1402
|
+
throw fileError(`${raw} is not a regular file. Nothing was sent.`);
|
|
1403
|
+
} catch (error) {
|
|
1404
|
+
if (error instanceof CliError)
|
|
1405
|
+
throw error;
|
|
1406
|
+
if (error.code === "ENOENT")
|
|
1407
|
+
throw fileError(`File not found: ${raw}`);
|
|
1408
|
+
}
|
|
1409
|
+
let fd;
|
|
1410
|
+
try {
|
|
1411
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
1412
|
+
} catch (error) {
|
|
1413
|
+
const code = error.code;
|
|
1414
|
+
if (code === "ENOENT")
|
|
1415
|
+
throw fileError(`File not found: ${raw}`);
|
|
1416
|
+
if (code === "ELOOP" || code === "EMLINK")
|
|
1417
|
+
throw fileError(`${raw} is a symbolic link; pass the path of the real file. Nothing was sent.`);
|
|
1418
|
+
if (code === "EACCES" || code === "EPERM")
|
|
1419
|
+
throw fileError(`No permission to read ${raw}.`);
|
|
1420
|
+
throw fileError(`Could not open ${raw}.`);
|
|
1421
|
+
}
|
|
1422
|
+
try {
|
|
1423
|
+
const stat2 = fstatSync(fd);
|
|
1424
|
+
if (!stat2.isFile())
|
|
1425
|
+
throw fileError(`${raw} is not a regular file. Nothing was sent.`);
|
|
1426
|
+
if (stat2.size === 0)
|
|
1427
|
+
throw fileError(`${raw} is empty. Nothing was sent.`);
|
|
1428
|
+
const filename = basename(path);
|
|
1429
|
+
const file = {
|
|
1430
|
+
path,
|
|
1431
|
+
field,
|
|
1432
|
+
filename,
|
|
1433
|
+
size: stat2.size,
|
|
1434
|
+
dev: stat2.dev,
|
|
1435
|
+
ino: stat2.ino,
|
|
1436
|
+
contentType: CONTENT_TYPES[extname(filename).toLowerCase()] ?? "application/octet-stream",
|
|
1437
|
+
open: () => readFile2(file)
|
|
1438
|
+
};
|
|
1439
|
+
return file;
|
|
1440
|
+
} finally {
|
|
1441
|
+
closeSync(fd);
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
async function* readFile2(file) {
|
|
1445
|
+
let handle;
|
|
1446
|
+
try {
|
|
1447
|
+
handle = await open(file.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
1448
|
+
} catch {
|
|
1449
|
+
throw new CliError("The file could not be opened for uploading; check the state before retrying.", 1, "file_unreadable");
|
|
1450
|
+
}
|
|
1451
|
+
try {
|
|
1452
|
+
const stat2 = await handle.stat();
|
|
1453
|
+
if (!stat2.isFile() || stat2.dev !== file.dev || stat2.ino !== file.ino || stat2.size !== file.size) {
|
|
1454
|
+
throw new CliError("The file changed after it was checked; nothing was sent from it.", 1, "file_changed");
|
|
1455
|
+
}
|
|
1456
|
+
for (;; ) {
|
|
1457
|
+
const buffer = Buffer.allocUnsafe(CHUNK);
|
|
1458
|
+
const { bytesRead } = await handle.read(buffer, 0, CHUNK, null);
|
|
1459
|
+
if (bytesRead === 0)
|
|
1460
|
+
return;
|
|
1461
|
+
yield buffer.subarray(0, bytesRead);
|
|
1462
|
+
}
|
|
1463
|
+
} finally {
|
|
1464
|
+
await handle.close();
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
async function sha256File(file) {
|
|
1468
|
+
const hash = createHash2("sha256");
|
|
1469
|
+
let bytes = 0;
|
|
1470
|
+
for await (const chunk of file.open()) {
|
|
1471
|
+
hash.update(chunk);
|
|
1472
|
+
bytes += chunk.length;
|
|
1473
|
+
}
|
|
1474
|
+
if (bytes !== file.size)
|
|
1475
|
+
throw new CliError("The file changed while it was being read.", 1, "file_changed");
|
|
1476
|
+
return hash.digest("hex");
|
|
1477
|
+
}
|
|
1478
|
+
function checkOutTarget(raw, force) {
|
|
1479
|
+
if (!raw.trim() || raw === "-")
|
|
1480
|
+
throw fileError("--out takes a file path. Bytes and long text are never written to stdout.", "invalid_out");
|
|
1481
|
+
const path = resolve2(raw);
|
|
1482
|
+
let parentOk = false;
|
|
1483
|
+
try {
|
|
1484
|
+
parentOk = statSync(dirname2(path)).isDirectory();
|
|
1485
|
+
} catch {}
|
|
1486
|
+
if (!parentOk)
|
|
1487
|
+
throw fileError(`The directory of --out does not exist: ${dirname2(raw)}`, "invalid_out");
|
|
1488
|
+
try {
|
|
1489
|
+
accessSync(dirname2(path), constants.W_OK);
|
|
1490
|
+
} catch {
|
|
1491
|
+
throw fileError(`The directory of --out is not writable: ${dirname2(raw)}`, "invalid_out");
|
|
1492
|
+
}
|
|
1493
|
+
if (Buffer.byteLength(basename(path)) + TEMPORARY_OVERHEAD > 255)
|
|
1494
|
+
throw fileError("The file name of --out is too long.", "invalid_out");
|
|
1495
|
+
let existing;
|
|
1496
|
+
try {
|
|
1497
|
+
existing = lstatSync(path);
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
if (error.code !== "ENOENT")
|
|
1500
|
+
throw fileError(`Could not check ${raw}.`, "invalid_out");
|
|
1501
|
+
}
|
|
1502
|
+
if (existing?.isDirectory())
|
|
1503
|
+
throw fileError(`${raw} is a directory; give a file path.`, "invalid_out");
|
|
1504
|
+
if (existing && !force)
|
|
1505
|
+
throw fileError(`${raw} already exists. Nothing was overwritten; use --force to replace it, or pick another path.`, "file_exists");
|
|
1506
|
+
return path;
|
|
1507
|
+
}
|
|
1508
|
+
function moveIntoPlace(temporary, target2, raw, force) {
|
|
1509
|
+
const exists = () => fileError(`${raw} appeared while writing; nothing was overwritten. Use --force to replace it.`, "file_exists");
|
|
1510
|
+
if (force) {
|
|
1511
|
+
renameSync2(temporary, target2);
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
try {
|
|
1515
|
+
linkSync(temporary, target2);
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
if (error.code === "EEXIST")
|
|
1518
|
+
throw exists();
|
|
1519
|
+
if (existsSync2(target2))
|
|
1520
|
+
throw exists();
|
|
1521
|
+
renameSync2(temporary, target2);
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
unlinkSync(temporary);
|
|
1525
|
+
}
|
|
1526
|
+
async function writeChunks(rawOut, chunks, options) {
|
|
1527
|
+
const target2 = checkOutTarget(rawOut, options.force);
|
|
1528
|
+
const temporary = join2(dirname2(target2), `.${basename(target2)}.${randomUUID().slice(0, 8)}.part`);
|
|
1529
|
+
let fd;
|
|
1530
|
+
try {
|
|
1531
|
+
fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, PRIVATE_MODE);
|
|
1532
|
+
} catch {
|
|
1533
|
+
throw fileError(`Cannot create a file next to ${rawOut}; nothing was written.`, "invalid_out");
|
|
1534
|
+
}
|
|
1535
|
+
let closed = false;
|
|
1536
|
+
const onSignal = (signal) => {
|
|
1537
|
+
try {
|
|
1538
|
+
closeSync(fd);
|
|
1539
|
+
} catch {}
|
|
1540
|
+
try {
|
|
1541
|
+
unlinkSync(temporary);
|
|
1542
|
+
} catch {}
|
|
1543
|
+
process.exit(signal === "SIGINT" ? 130 : 143);
|
|
1544
|
+
};
|
|
1545
|
+
process.once("SIGINT", onSignal);
|
|
1546
|
+
process.once("SIGTERM", onSignal);
|
|
1547
|
+
try {
|
|
1548
|
+
fchmodSync(fd, PRIVATE_MODE);
|
|
1549
|
+
const hash = createHash2("sha256");
|
|
1550
|
+
let bytes = 0;
|
|
1551
|
+
for await (const chunk of chunks) {
|
|
1552
|
+
let offset = 0;
|
|
1553
|
+
while (offset < chunk.length)
|
|
1554
|
+
offset += writeSync(fd, chunk, offset, chunk.length - offset);
|
|
1555
|
+
hash.update(chunk);
|
|
1556
|
+
bytes += chunk.length;
|
|
1557
|
+
}
|
|
1558
|
+
if (options.expectedBytes !== undefined && bytes !== options.expectedBytes) {
|
|
1559
|
+
throw new CliError(`The download ended after ${bytes} of ${options.expectedBytes} bytes; nothing was kept.`, 1, "incomplete_download");
|
|
1560
|
+
}
|
|
1561
|
+
closeSync(fd);
|
|
1562
|
+
closed = true;
|
|
1563
|
+
moveIntoPlace(temporary, target2, rawOut, options.force);
|
|
1564
|
+
return { path: target2, bytes, sha256: hash.digest("hex") };
|
|
1565
|
+
} catch (error) {
|
|
1566
|
+
if (!closed)
|
|
1567
|
+
try {
|
|
1568
|
+
closeSync(fd);
|
|
1569
|
+
} catch {}
|
|
1570
|
+
try {
|
|
1571
|
+
unlinkSync(temporary);
|
|
1572
|
+
} catch {}
|
|
1573
|
+
if (error instanceof CliError)
|
|
1574
|
+
throw error;
|
|
1575
|
+
throw new CliError("The file could not be written; nothing was kept.", 1, "write_failed");
|
|
1576
|
+
} finally {
|
|
1577
|
+
process.off("SIGINT", onSignal);
|
|
1578
|
+
process.off("SIGTERM", onSignal);
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
async function* interruptible(source) {
|
|
1582
|
+
try {
|
|
1583
|
+
for await (const chunk of source)
|
|
1584
|
+
yield chunk;
|
|
1585
|
+
} catch {
|
|
1586
|
+
throw new CliError("The download was interrupted; nothing was kept. The file can be downloaded again.", 1, "network_error");
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
async function writeStreamToFile(out, stream, options) {
|
|
1590
|
+
return writeChunks(out, interruptible(stream), options);
|
|
1591
|
+
}
|
|
1592
|
+
async function writeTextToFile(out, text, force) {
|
|
1593
|
+
return writeChunks(out, async function* () {
|
|
1594
|
+
yield new TextEncoder().encode(text);
|
|
1595
|
+
}(), { force });
|
|
1596
|
+
}
|
|
1597
|
+
function terminalSafe(text) {
|
|
1598
|
+
return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "?");
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
// src/execute.ts
|
|
1602
|
+
function resolveOrigin(product, ctx, spec, useFlag = true) {
|
|
1603
|
+
const profile = ctx.file.profiles[ctx.config.profile];
|
|
1604
|
+
const plugin = ctx.options.plugins?.find((entry) => entry.product === product);
|
|
1605
|
+
const info = findProduct(product);
|
|
1606
|
+
const specOrigin = spec ? serverOrigin(spec) : undefined;
|
|
1607
|
+
return (useFlag ? str(ctx.flags, "api-url") : undefined) ?? ctx.env[`PRUDAI_${product.toUpperCase().replaceAll("-", "_")}_API_URL`] ?? profile?.productApiUrls?.[product] ?? (plugin?.apiUrl || undefined) ?? (info?.product === PLATFORM_PRODUCT ? ctx.config.apiUrl : undefined) ?? info?.origin ?? (specOrigin && isTrustedOrigin(specOrigin) && !/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|$)/.test(specOrigin) ? specOrigin : undefined);
|
|
1608
|
+
}
|
|
1609
|
+
async function credentialFor(product, ctx) {
|
|
1610
|
+
if (!ctx.session.hasLogin)
|
|
1611
|
+
return;
|
|
1612
|
+
return ctx.session.productToken(product);
|
|
1613
|
+
}
|
|
1614
|
+
function missingCredential(_product) {
|
|
1615
|
+
return new CliError("Not logged in. Run `prudai login` (device login with your Prudai account).", 2, "not_authenticated");
|
|
1616
|
+
}
|
|
1617
|
+
async function readData(flags) {
|
|
1618
|
+
const data = str(flags, "data");
|
|
1619
|
+
if (data === undefined)
|
|
1620
|
+
return;
|
|
1621
|
+
let text = data;
|
|
1622
|
+
if (data.startsWith("@")) {
|
|
1623
|
+
try {
|
|
1624
|
+
text = await readFile3(data.slice(1), "utf8");
|
|
1625
|
+
} catch {
|
|
1626
|
+
throw new CliError("Could not read --data file.");
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
try {
|
|
1630
|
+
return JSON.parse(text);
|
|
1631
|
+
} catch {
|
|
1632
|
+
throw new CliError("--data must contain valid JSON.");
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
var IRREVERSIBLE = "This is the final removal: the document, its text and its original are removed for good and cannot be restored. To get it back, upload the original again.";
|
|
1636
|
+
async function executeOperation(operation, positionals, origin, ctx, extras = {}) {
|
|
1637
|
+
const { flags, env, emit, stderr } = ctx;
|
|
1638
|
+
const allowed = new Set([...GLOBAL_FLAGS, ...extras.consumed ?? []]);
|
|
1639
|
+
for (const parameter of operation.parameters) {
|
|
1640
|
+
if (parameter.in === "header") {
|
|
1641
|
+
if (isSafeHeaderName(parameter.name))
|
|
1642
|
+
allowed.add(parameter.name.toLowerCase());
|
|
1643
|
+
} else if (parameter.in === "path" || parameter.in === "query")
|
|
1644
|
+
allowed.add(parameter.name);
|
|
1645
|
+
}
|
|
1646
|
+
validateFlags(flags, allowed);
|
|
1647
|
+
if (operation.approval === "forbidden_for_agents")
|
|
1648
|
+
throw new CliError("This operation is forbidden for agents; a human does it in the product app.", 2, "forbidden_for_agents");
|
|
1649
|
+
if (operation.multipart && !extras.upload) {
|
|
1650
|
+
throw new CliError(`${operation.method} ${operation.path} takes a file (multipart/form-data), which this generic command cannot send. Use prudai projects upload, prudai memos upload or prudai kb upload. Nothing was sent.`, 2, "validation_error");
|
|
1651
|
+
}
|
|
1652
|
+
if (!origin)
|
|
1653
|
+
throw new CliError(`Configure the ${operation.product} API origin: prudai profile set productApiUrls.${operation.product} <origin>, or --api-url <origin>.`);
|
|
1654
|
+
const apiUrl = safeApiOrigin(origin);
|
|
1655
|
+
requireTrustedOrigin(apiUrl, env);
|
|
1656
|
+
const token = await credentialFor(operation.product, ctx);
|
|
1657
|
+
if (!token)
|
|
1658
|
+
throw missingCredential(operation.product);
|
|
1659
|
+
const isGet = operation.method.toUpperCase() === "GET";
|
|
1660
|
+
const writing = !isGet && !operation.readsViaPost;
|
|
1661
|
+
const approvalsPath = extras.approvalsPath ?? findProduct(operation.product)?.approvalsPath;
|
|
1662
|
+
if (flags.wait && writing && !approvalsPath)
|
|
1663
|
+
throw new CliError(`--wait needs an approvals API, and ${operation.product} has none yet; use the product's own approval screen instead.`, 2, "not_available");
|
|
1664
|
+
if (operation.status === "planned") {
|
|
1665
|
+
stderr(`Note: ${operation.method} ${operation.path} comes from a spec that marks it planned; it may not be served yet.`);
|
|
1666
|
+
}
|
|
1667
|
+
if (operation.cost?.startsWith("credits") && writing && flags["no-dry-run"])
|
|
1668
|
+
stderr("Note: this operation spends credits.");
|
|
1669
|
+
if (isGet && (flags.data !== undefined || extras.body))
|
|
1670
|
+
throw new CliError("Read commands do not accept --data.");
|
|
1671
|
+
if (writing && flags["no-dry-run"] && !flags.yes)
|
|
1672
|
+
throw new CliError("Real writes require --no-dry-run --yes.");
|
|
1673
|
+
if (flags.wait && !writing)
|
|
1674
|
+
throw new CliError("--wait belongs to writes that may need approval.");
|
|
1675
|
+
const params = {};
|
|
1676
|
+
const query = {};
|
|
1677
|
+
const headers = {};
|
|
1678
|
+
for (const parameter of operation.parameters) {
|
|
1679
|
+
const value = str(flags, parameter.in === "header" ? parameter.name.toLowerCase() : parameter.name);
|
|
1680
|
+
if (value !== undefined) {
|
|
1681
|
+
if (parameter.in === "path")
|
|
1682
|
+
params[parameter.name] = value;
|
|
1683
|
+
else if (parameter.in === "query")
|
|
1684
|
+
query[parameter.name] = value;
|
|
1685
|
+
else if (parameter.in === "header")
|
|
1686
|
+
headers[parameter.name.toLowerCase()] = value;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
const open2 = operation.positionals.filter((name) => params[name] === undefined && query[name] === undefined);
|
|
1690
|
+
if (positionals.length > open2.length) {
|
|
1691
|
+
throw new CliError(open2.length ? `Too many arguments; ${operation.name} takes ${open2.map((name) => `<${name}>`).join(" ")}.` : `${operation.name} takes no positional arguments.`);
|
|
1692
|
+
}
|
|
1693
|
+
const pathNames = new Set([...operation.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]));
|
|
1694
|
+
positionals.forEach((value, index) => {
|
|
1695
|
+
const name = open2[index];
|
|
1696
|
+
if (pathNames.has(name))
|
|
1697
|
+
params[name] = value;
|
|
1698
|
+
else
|
|
1699
|
+
query[name] = value;
|
|
1700
|
+
});
|
|
1701
|
+
const data = await readData(flags);
|
|
1702
|
+
if (extras.upload && data !== undefined)
|
|
1703
|
+
throw new CliError("--data does not apply to a file upload: the request body is the file.", 2, "validation_error");
|
|
1704
|
+
let body = data;
|
|
1705
|
+
if (extras.body) {
|
|
1706
|
+
if (data !== undefined && !isRecord(data))
|
|
1707
|
+
throw new CliError("--data must be a JSON object here.");
|
|
1708
|
+
body = { ...data, ...extras.body };
|
|
1709
|
+
}
|
|
1710
|
+
extras.checkBody?.(body);
|
|
1711
|
+
const etag = str(flags, "if-match");
|
|
1712
|
+
if (etag)
|
|
1713
|
+
headers["if-match"] = etag;
|
|
1714
|
+
const dryRun = writing && !flags["no-dry-run"];
|
|
1715
|
+
const request = buildOperationRequest(extras.upload && dryRun ? { ...operation, dryRun: true } : operation, { params, query, body, headers, dryRun: !flags["no-dry-run"], idempotencyKey: str(flags, "idempotency-key") });
|
|
1716
|
+
if (extras.upload && dryRun) {
|
|
1717
|
+
const { file } = extras.upload;
|
|
1718
|
+
const shown2 = new URL(request.path, "https://request.invalid");
|
|
1719
|
+
shown2.searchParams.delete("dryRun");
|
|
1720
|
+
const upload = { field: file.field, filename: file.filename, bytes: file.size, sha256: await sha256File(file), contentType: file.contentType };
|
|
1721
|
+
emit({
|
|
1722
|
+
dryRun: true,
|
|
1723
|
+
serverConfirmed: false,
|
|
1724
|
+
request: { method: request.method, path: `${shown2.pathname}${shown2.search}`, upload },
|
|
1725
|
+
...extras.upload.target ? { target: extras.upload.target } : {},
|
|
1726
|
+
approval: operation.approval,
|
|
1727
|
+
next: "Nothing was sent. Repeat with --no-dry-run --yes to upload this file."
|
|
1728
|
+
}, [
|
|
1729
|
+
`DRY RUN — nothing was sent. Would upload ${file.filename} (${file.size} bytes, sha256 ${upload.sha256}) with ${request.method} ${shown2.pathname}${shown2.search}`,
|
|
1730
|
+
...extras.upload.target ? [`target: ${JSON.stringify(extras.upload.target)}`] : [],
|
|
1731
|
+
`approval: ${operation.approval}`,
|
|
1732
|
+
"Repeat with --no-dry-run --yes to upload this file."
|
|
1733
|
+
].join(`
|
|
1734
|
+
`));
|
|
1735
|
+
return 0;
|
|
1736
|
+
}
|
|
1737
|
+
const idempotencyKey = request.headers["Idempotency-Key"];
|
|
1738
|
+
if (writing && idempotencyKey && !dryRun)
|
|
1739
|
+
stderr(`Idempotency-Key: ${idempotencyKey} (reuse it with --idempotency-key after an uncertain delivery${operation.idempotencyDeclared ? "" : "; this operation does not declare replay protection"})`);
|
|
1740
|
+
if (extras.irreversible && !dryRun)
|
|
1741
|
+
stderr(`Warning: ${IRREVERSIBLE}`);
|
|
1742
|
+
const target2 = `${apiUrl}${request.path}`;
|
|
1743
|
+
let result;
|
|
1744
|
+
if (extras.upload) {
|
|
1745
|
+
const sent = await requestMultipart(ctx.fetch, target2, { method: request.method, headers: request.headers, token, env, file: extras.upload.file });
|
|
1746
|
+
if (sent.status >= 200 && sent.status < 300 && sent.status !== 202)
|
|
1747
|
+
stderr(`Uploaded ${sent.sent.bytes} bytes (sha256 ${sent.sent.sha256}).`);
|
|
1748
|
+
result = sent;
|
|
1749
|
+
} else if (extras.download) {
|
|
1750
|
+
const answer = await requestBytes(ctx.fetch, target2, { headers: request.headers, token, env });
|
|
1751
|
+
if (answer.kind === "bytes")
|
|
1752
|
+
return emitDownload(answer, extras.download, operation, ctx);
|
|
1753
|
+
result = answer;
|
|
1754
|
+
} else
|
|
1755
|
+
result = await requestJson(ctx.fetch, target2, { ...request, token, env });
|
|
1756
|
+
const accepted = result.status === 202 && extras.queued === true && isEnvelopeLike(result.body) && isRecord(result.body) && result.body.status !== "approval_required" && result.body.approvalRequest === undefined && isRecord(result.body.data) && result.body.data.id === params.document_id && result.body.data.deleted_at === null && result.body.data.approvalRequest === undefined;
|
|
1757
|
+
if (accepted)
|
|
1758
|
+
stderr("Note: accepted. The document is processed again in the background (status pending); read its status with the matching get command.");
|
|
1759
|
+
if (result.status === 202 && !accepted) {
|
|
1760
|
+
const pending = approvalResult(result.body, env);
|
|
1761
|
+
if (pending.warning)
|
|
1762
|
+
stderr(`Warning: ${pending.warning}`);
|
|
1763
|
+
const request202 = pending.approvalRequest;
|
|
1764
|
+
const id = typeof request202.approvalRequestId === "string" ? request202.approvalRequestId : typeof request202.id === "string" ? request202.id : undefined;
|
|
1765
|
+
const follow = id && approvalsPath ? `prudai approvals wait ${id} --product ${operation.product} --execute` : undefined;
|
|
1766
|
+
if (flags.wait && id && approvalsPath) {
|
|
1767
|
+
stderr(`APPROVAL REQUIRED. ${pending.next} Waiting (prudai approvals wait ${id}).`);
|
|
1768
|
+
return waitForApproval(ctx, { product: operation.product, origin: apiUrl, approvalsPath, id, execute: true, timeoutSeconds: intFlag(flags, "timeout", 600, 5, 3600) });
|
|
1769
|
+
}
|
|
1770
|
+
const out = { ...pending, ...follow ? { follow, next: `${pending.next} Then run: ${follow}` } : {} };
|
|
1771
|
+
emit(out, `APPROVAL REQUIRED. ${out.next}
|
|
1772
|
+
${JSON.stringify(pending.approvalRequest, null, 2)}`);
|
|
1773
|
+
return 2;
|
|
1774
|
+
}
|
|
1775
|
+
if (result.status >= 400) {
|
|
1776
|
+
if (operation.status === "planned" && [400, 404, 405, 501].includes(result.status) && !isEnvelopeLike(result.body)) {
|
|
1777
|
+
throw new NotAvailableError(`${operation.method} ${operation.path} is not served by ${apiUrl} yet (HTTP ${result.status}): it comes from a spec that marks it planned.`, { planned: `${operation.method} ${operation.path}`, ...operation.scopes?.length ? { scope: operation.scopes.join(" ") } : {}, approval: operation.approval, next: ["Nothing was executed. Try again when the product announces the API as live."] });
|
|
1778
|
+
}
|
|
1779
|
+
throw httpError(result.status, result.body, operation.product);
|
|
1780
|
+
}
|
|
1781
|
+
requireSuccess(accepted ? 200 : result.status);
|
|
1782
|
+
const envelope = result.status === 204 ? null : isEnvelopeLike(result.body) ? parseEnvelope(result.body) : localEnvelope(result.body, { provenance: { kind: "raw", product: operation.product }, completeness: {}, notIncluded: ["The server answered without the /v1 envelope; data is its raw body."] });
|
|
1783
|
+
if (extras.text && envelope)
|
|
1784
|
+
return emitText(envelope, extras.text, ctx);
|
|
1785
|
+
if (dryRun) {
|
|
1786
|
+
const shown2 = new URL(request.path, "https://request.invalid");
|
|
1787
|
+
shown2.searchParams.delete("dryRun");
|
|
1788
|
+
const next = `Nothing was executed. Repeat with --no-dry-run --yes to execute this request.${extras.after ? ` Afterwards: ${extras.after.action} (${extras.after.why})` : ""}`;
|
|
1789
|
+
const would = { method: request.method, path: `${shown2.pathname}${shown2.search}`, ...request.body !== undefined ? { body: request.body } : {} };
|
|
1790
|
+
const serverConfirmed = result.headers.get("x-prudai-dry-run") === "true" || envelope?.context.dry_run === true;
|
|
1791
|
+
if (extras.irreversible && !serverConfirmed) {
|
|
1792
|
+
throw new CliError(`The server did not confirm a dry run for an irreversible delete (no x-prudai-dry-run header, no context.dry_run), so the document may already be gone. Check it with the matching get command before doing anything else. ${IRREVERSIBLE}`, 1, "dry_run_unconfirmed");
|
|
1793
|
+
}
|
|
1794
|
+
emit({ dryRun: true, serverConfirmed, request: would, approval: operation.approval, ...extras.irreversible ? { irreversible: true, warning: IRREVERSIBLE } : {}, preview: envelope, next }, [
|
|
1795
|
+
`DRY RUN — nothing was executed. Would send: ${would.method} ${would.path}${request.body !== undefined ? ` ${JSON.stringify(request.body)}` : ""}`,
|
|
1796
|
+
`approval: ${operation.approval}`,
|
|
1797
|
+
...extras.irreversible ? [`IRREVERSIBLE: ${IRREVERSIBLE}`] : [],
|
|
1798
|
+
...envelope ? [renderEnvelope(envelope)] : [],
|
|
1799
|
+
"Repeat with --no-dry-run --yes to execute this request.",
|
|
1800
|
+
...extras.after ? [`Afterwards: ${extras.after.action} (${extras.after.why})`] : []
|
|
1801
|
+
].join(`
|
|
1802
|
+
`));
|
|
1803
|
+
return 0;
|
|
1804
|
+
}
|
|
1805
|
+
if (!envelope) {
|
|
1806
|
+
emit(localEnvelope(null, { context: { status: 204 }, provenance: { kind: "product", product: operation.product } }), "Done (no content).");
|
|
1807
|
+
return 0;
|
|
1808
|
+
}
|
|
1809
|
+
const shown = extras.after ? { ...envelope, next: [...envelope.next, extras.after] } : envelope;
|
|
1810
|
+
emit(shown, renderEnvelope(shown));
|
|
1811
|
+
return 0;
|
|
1812
|
+
}
|
|
1813
|
+
async function emitDownload(answer, options, operation, ctx) {
|
|
1814
|
+
const length = Number(answer.headers.get("content-length"));
|
|
1815
|
+
const encoded = /\S/.test(answer.headers.get("content-encoding") ?? "") && answer.headers.get("content-encoding").trim().toLowerCase() !== "identity";
|
|
1816
|
+
let written;
|
|
1817
|
+
try {
|
|
1818
|
+
written = await writeStreamToFile(options.out, answer.stream, { force: options.force, ...!encoded && answer.headers.has("content-length") && Number.isSafeInteger(length) && length >= 0 ? { expectedBytes: length } : {} });
|
|
1819
|
+
} finally {
|
|
1820
|
+
await answer.stream.cancel().catch(() => {
|
|
1821
|
+
return;
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
const contentType = answer.headers.get("content-type")?.split(";")[0]?.trim() || null;
|
|
1825
|
+
const summary = { path: written.path, bytes: written.bytes, sha256: written.sha256, content_type: contentType };
|
|
1826
|
+
ctx.emit(localEnvelope(summary, {
|
|
1827
|
+
provenance: { kind: "product", product: operation.product },
|
|
1828
|
+
notIncluded: ["The file content: it was written to the path above (mode 0600), never to stdout."],
|
|
1829
|
+
next: [{ action: `sha256sum ${written.path}`, why: "Compare with the sha256 above to verify the file." }]
|
|
1830
|
+
}), JSON.stringify(summary, null, 2));
|
|
1831
|
+
return 0;
|
|
1832
|
+
}
|
|
1833
|
+
async function emitText(envelope, options, ctx) {
|
|
1834
|
+
const data = envelope.data;
|
|
1835
|
+
if (!isRecord(data) || typeof data.text !== "string")
|
|
1836
|
+
throw new CliError("The server answered without the text of the document.", 1, "invalid_response");
|
|
1837
|
+
const truncated = envelope.completeness.truncated === true;
|
|
1838
|
+
if (truncated)
|
|
1839
|
+
ctx.stderr(`Note: the text is truncated (${JSON.stringify(envelope.completeness)}). The text below is not the whole document.`);
|
|
1840
|
+
if (options.out !== undefined) {
|
|
1841
|
+
const written = await writeTextToFile(options.out, data.text, options.force);
|
|
1842
|
+
const summary = { path: written.path, bytes: written.bytes, sha256: written.sha256, characters: data.text.length, truncated };
|
|
1843
|
+
ctx.emit(localEnvelope(summary, {
|
|
1844
|
+
provenance: { kind: "product" },
|
|
1845
|
+
completeness: { truncated },
|
|
1846
|
+
notIncluded: ["The text itself: it was written to the path above (mode 0600), never to stdout."]
|
|
1847
|
+
}), JSON.stringify(summary, null, 2));
|
|
1848
|
+
return 0;
|
|
1849
|
+
}
|
|
1850
|
+
const plain = data.text.endsWith(`
|
|
1851
|
+
`) ? data.text.slice(0, -1) : data.text;
|
|
1852
|
+
ctx.emit(envelope, process.stdout.isTTY ? terminalSafe(plain) : plain);
|
|
1853
|
+
return 0;
|
|
1854
|
+
}
|
|
1855
|
+
var STATUS_HINT = {
|
|
1856
|
+
400: "the request was refused as invalid (or this route is not served here yet)",
|
|
1857
|
+
401: "the credential was rejected: expired, revoked or not valid for this product (check it with prudai auth token; a new one via prudai login or the product app)",
|
|
1858
|
+
402: "a credit or spend limit was reached (prudai credits)",
|
|
1859
|
+
403: "not allowed: a missing scope, role or product access, or an approval is required",
|
|
1860
|
+
404: "not found, or not served by this API yet",
|
|
1861
|
+
409: "conflict with the current state (check it and use --if-match)",
|
|
1862
|
+
412: "the ETag no longer matches; read the record again",
|
|
1863
|
+
422: "validation failed",
|
|
1864
|
+
429: "rate limited; wait and retry reads (never blindly retry a write)"
|
|
1865
|
+
};
|
|
1866
|
+
function httpError(status, body, product) {
|
|
1867
|
+
const code = errorCodeOf(body);
|
|
1868
|
+
const hint = status === 401 && product ? "The product rejected the token for your login; run `prudai whoami --online`, and `prudai login` if the session is gone." : undefined;
|
|
1869
|
+
const message = errorMessageOf(body) ?? STATUS_HINT[status] ?? (status >= 500 ? "server error; check state before retrying a write" : "request failed");
|
|
1870
|
+
return new CliError(`API returned HTTP ${status}${code ? ` (${code})` : ""}: ${message}.${hint ? ` ${hint}` : ""}`, status >= 500 ? 1 : 2, code ?? `http_${status}`);
|
|
1871
|
+
}
|
|
1872
|
+
function errorCodeOf(body) {
|
|
1873
|
+
if (!isRecord(body))
|
|
1874
|
+
return;
|
|
1875
|
+
const context = isRecord(body.context) && isRecord(body.context.error) ? body.context.error.code : undefined;
|
|
1876
|
+
const nested = isRecord(body.error) ? body.error.code : undefined;
|
|
1877
|
+
return [context, nested, body.error, body.code].find((value) => typeof value === "string" && /^[a-z][a-z0-9]*(?:[_.][a-z0-9]+)+$/.test(value) && value.length <= 80);
|
|
1878
|
+
}
|
|
1879
|
+
function errorMessageOf(body) {
|
|
1880
|
+
if (!isRecord(body))
|
|
1881
|
+
return;
|
|
1882
|
+
const error = isRecord(body.context) && isRecord(body.context.error) ? body.context.error : isRecord(body.error) ? body.error : typeof body.message === "string" ? body : undefined;
|
|
1883
|
+
if (!error)
|
|
1884
|
+
return;
|
|
1885
|
+
const details = isRecord(error.details) ? error.details : isRecord(body.details) ? body.details : {};
|
|
1886
|
+
const extra = ["required_scope", "currentVersion", "current_version", "param"].filter((key) => typeof details[key] === "string" || typeof details[key] === "number").map((key) => `${key.replace(/_/g, " ")}: ${details[key]}`);
|
|
1887
|
+
const parts = [typeof error.message === "string" ? error.message : undefined, ...extra].filter(Boolean);
|
|
1888
|
+
return parts.length ? parts.join("; ").replace(/prudai_(?:pat|sk_(?:live|test))_[A-Za-z0-9_-]+/g, "[redacted]").slice(0, 400) : undefined;
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
// src/api.ts
|
|
1892
|
+
var METHODS2 = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
|
|
1893
|
+
var CLI_FLAG_NAMES = new Set([...BOOLEAN_FLAGS, ...GLOBAL_FLAGS, "product", "org", "registry", "spec"]);
|
|
1894
|
+
var HUMAN_ONLY_PATH = /\/approvals\/[^/]+\/(?:decision|approve|reject)\/?$/i;
|
|
1895
|
+
async function apiCommand(words, ctx) {
|
|
1896
|
+
const [rawMethod, rawPath, ...extra] = words;
|
|
1897
|
+
const method = rawMethod?.toUpperCase();
|
|
1898
|
+
if (!method || !METHODS2.has(method) || !rawPath || extra.length)
|
|
1899
|
+
throw new CliError("Usage: prudai api <GET|POST|PUT|PATCH|DELETE> </v1/path?query> [--product p] [--data json|@file]");
|
|
1900
|
+
if (!rawPath.startsWith("/") || rawPath.startsWith("//") || /(^|\/)\.\.?(\/|$|\?)/.test(rawPath) || /[\s#]/.test(rawPath))
|
|
1901
|
+
throw new CliError("The path must start with / and contain no '..', spaces or fragments.");
|
|
1902
|
+
const parsed = new URL(rawPath, "https://path.invalid");
|
|
1903
|
+
const path = parsed.pathname;
|
|
1904
|
+
let decoded;
|
|
1905
|
+
try {
|
|
1906
|
+
decoded = decodeURIComponent(path);
|
|
1907
|
+
} catch {
|
|
1908
|
+
throw new CliError("The path contains an invalid percent-encoding.");
|
|
1909
|
+
}
|
|
1910
|
+
if (HUMAN_ONLY_PATH.test(path) || HUMAN_ONLY_PATH.test(decoded))
|
|
1911
|
+
throw new CliError("Approving or rejecting is a person's decision in the product app; the CLI never approves (forbidden_for_agents). Nothing was sent.", 2, "forbidden_for_agents");
|
|
1912
|
+
const wanted = str(ctx.flags, "product");
|
|
1913
|
+
if (wanted && !findProduct(wanted))
|
|
1914
|
+
throw new CliError(`Unknown product "${wanted}". Products: ${PRODUCTS.map((p) => p.product).join(", ")}.`);
|
|
1915
|
+
const catalogs = await loadCatalog(ctx.catalog, wanted ? [findProduct(wanted).product] : undefined);
|
|
1916
|
+
const matches = catalogs.flatMap((catalog2) => catalog2.commands.filter((command) => command.method === method && templateMatches(command.path, path)).map((command) => ({ catalog: catalog2, command })));
|
|
1917
|
+
const products = [...new Set(matches.map((entry) => entry.catalog.product))];
|
|
1918
|
+
if (!wanted && products.length > 1)
|
|
1919
|
+
throw new CliError(`${method} ${path} exists in ${products.join(" and ")}; add --product.`);
|
|
1920
|
+
const product = wanted ? findProduct(wanted).product : products[0] ?? PLATFORM_PRODUCT;
|
|
1921
|
+
const match = matches.filter((entry) => entry.catalog.product === product).sort((a, b) => (a.command.path.match(/\{/g)?.length ?? 0) - (b.command.path.match(/\{/g)?.length ?? 0))[0];
|
|
1922
|
+
const catalog = catalogs.find((entry) => entry.product === product);
|
|
1923
|
+
const origin = resolveOrigin(product, ctx, catalog?.spec);
|
|
1924
|
+
if (match) {
|
|
1925
|
+
const templateParts = match.command.path.split("/");
|
|
1926
|
+
const values = path.split("/");
|
|
1927
|
+
const pathValues = templateParts.flatMap((part, index) => /^\{[^}]+\}$/.test(part) ? [decodeURIComponent(values[index])] : []);
|
|
1928
|
+
const declared = new Set(match.command.parameters.filter((p) => p.in === "query").map((p) => p.name));
|
|
1929
|
+
const queryFlags = {};
|
|
1930
|
+
for (const [key, value] of parsed.searchParams) {
|
|
1931
|
+
if (key === "dryRun")
|
|
1932
|
+
throw new CliError("Do not put dryRun in the path; the CLI sets it (use --no-dry-run --yes to execute).");
|
|
1933
|
+
if (CLI_FLAG_NAMES.has(key) || !declared.has(key))
|
|
1934
|
+
throw new CliError(`Query parameter "${key}" is not a query parameter of ${match.command.method} ${match.command.path}; it was not sent. Run prudai describe ${match.command.method} ${match.command.path}.`);
|
|
1935
|
+
if (Object.hasOwn(ctx.flags, key) || Object.hasOwn(queryFlags, key))
|
|
1936
|
+
throw new CliError(`Query parameter ${key} given twice.`);
|
|
1937
|
+
queryFlags[key] = value;
|
|
1938
|
+
}
|
|
1939
|
+
const placeholders = [...match.command.path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
|
|
1940
|
+
const ordered = match.command.positionals.filter((name) => placeholders.includes(name));
|
|
1941
|
+
const positionals = ordered.map((name) => pathValues[placeholders.indexOf(name)]);
|
|
1942
|
+
const flags = { ...ctx.flags, ...queryFlags };
|
|
1943
|
+
delete flags.product;
|
|
1944
|
+
return executeOperation(match.command, positionals, origin, { ...ctx, flags });
|
|
1945
|
+
}
|
|
1946
|
+
validateFlags(ctx.flags, ["json", "help", "yes", "no-dry-run", "dry-run", "profile", "product", "api-url", "data", "idempotency-key", "refresh", "offline"]);
|
|
1947
|
+
if (!origin)
|
|
1948
|
+
throw new CliError(`Configure the ${product} API origin (--api-url).`);
|
|
1949
|
+
if (catalog?.notAvailable)
|
|
1950
|
+
ctx.stderr(`Note: ${product} has no live /v1 spec yet, so this path is not a known operation; the raw call is sent as you wrote it (same credential, trust and dry-run rules).`);
|
|
1951
|
+
const apiUrl = safeApiOrigin(origin);
|
|
1952
|
+
requireTrustedOrigin(apiUrl, ctx.env);
|
|
1953
|
+
const token = await credentialFor(product, ctx);
|
|
1954
|
+
if (!token)
|
|
1955
|
+
throw missingCredential(product);
|
|
1956
|
+
const writing = method !== "GET";
|
|
1957
|
+
const body = await readData(ctx.flags);
|
|
1958
|
+
if (!writing && body !== undefined)
|
|
1959
|
+
throw new CliError("GET does not take --data.");
|
|
1960
|
+
if (writing && !(ctx.flags["no-dry-run"] && ctx.flags.yes)) {
|
|
1961
|
+
throw new CliError(`${method} ${path} is not in the ${product} catalogue, so no dry run is known and nothing was sent. Check the request, then repeat with --no-dry-run --yes.`, 2, "dry_run_unsupported");
|
|
1962
|
+
}
|
|
1963
|
+
const headers = {};
|
|
1964
|
+
if (writing) {
|
|
1965
|
+
const key = str(ctx.flags, "idempotency-key") ?? crypto.randomUUID();
|
|
1966
|
+
if (!key.trim() || /[^\t\x20-\x7e]/.test(key))
|
|
1967
|
+
throw new CliError("Invalid Idempotency-Key.");
|
|
1968
|
+
headers["Idempotency-Key"] = key;
|
|
1969
|
+
ctx.stderr(`Idempotency-Key: ${key} (reuse it with --idempotency-key after an uncertain delivery)`);
|
|
1970
|
+
}
|
|
1971
|
+
ctx.stderr(`Note: ${method} ${path} is not in the ${product} catalogue; sent as-is to ${apiUrl}.`);
|
|
1972
|
+
const result = await requestJson(ctx.fetch, `${apiUrl}${parsed.pathname}${parsed.search}`, { method, token, env: ctx.env, headers, ...body !== undefined ? { body } : {} });
|
|
1973
|
+
if (result.status === 202) {
|
|
1974
|
+
const pending = approvalResult(result.body, ctx.env);
|
|
1975
|
+
if (pending.warning)
|
|
1976
|
+
ctx.stderr(`Warning: ${pending.warning}`);
|
|
1977
|
+
ctx.emit(pending, `APPROVAL REQUIRED. ${pending.next}`);
|
|
1978
|
+
return 2;
|
|
1979
|
+
}
|
|
1980
|
+
if (result.status >= 400)
|
|
1981
|
+
throw httpError(result.status, result.body, product);
|
|
1982
|
+
const envelope = isEnvelopeLike(result.body) ? parseEnvelope(result.body) : localEnvelope(result.body, { context: { status: result.status }, completeness: {}, provenance: { kind: "raw", product, path }, notIncluded: ["Raw answer: the server did not use the /v1 envelope."] });
|
|
1983
|
+
ctx.emit(envelope, renderEnvelope(envelope));
|
|
1984
|
+
return 0;
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
// src/auth.ts
|
|
1988
|
+
import { hostname } from "node:os";
|
|
1989
|
+
|
|
1990
|
+
// src/keycloak.ts
|
|
1991
|
+
var CLIENT_ID = "prudai-cli";
|
|
1992
|
+
var DEVICE_SCOPE = "offline_access";
|
|
1993
|
+
var FORM = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
|
|
1994
|
+
var record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
1995
|
+
var positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
1996
|
+
var USER_CODE = /^[A-Za-z0-9][A-Za-z0-9-]{2,30}[A-Za-z0-9]$/;
|
|
1997
|
+
var JWT = /^[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}$/;
|
|
1998
|
+
var TOKEN_SHAPE = /^[A-Za-z0-9._~+/=-]{20,8192}$/;
|
|
1999
|
+
function endpoints(issuer, env) {
|
|
2000
|
+
let url;
|
|
2001
|
+
try {
|
|
2002
|
+
url = secureUrl(issuer);
|
|
2003
|
+
} catch {
|
|
2004
|
+
throw new CliError("The Keycloak issuer must be an https URL (or localhost), without credentials.", 2, "invalid_issuer");
|
|
2005
|
+
}
|
|
2006
|
+
if (url.search || url.hash)
|
|
2007
|
+
throw new CliError("The Keycloak issuer must be a plain realm URL.", 2, "invalid_issuer");
|
|
2008
|
+
requireTrustedOrigin(url.href, env);
|
|
2009
|
+
const base = `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
2010
|
+
return { issuer: base, device: `${base}/protocol/openid-connect/auth/device`, token: `${base}/protocol/openid-connect/token`, revoke: `${base}/protocol/openid-connect/revoke` };
|
|
2011
|
+
}
|
|
2012
|
+
async function postForm(fetchImpl, url, form) {
|
|
2013
|
+
let response;
|
|
2014
|
+
try {
|
|
2015
|
+
response = await fetchImpl(url, { method: "POST", headers: FORM, body: new URLSearchParams(form).toString(), redirect: "error", signal: AbortSignal.timeout(15000) });
|
|
2016
|
+
} catch {
|
|
2017
|
+
throw new CliError("Could not reach the login service; check the network and try again.", 1, "network_error");
|
|
2018
|
+
}
|
|
2019
|
+
const text = await response.text();
|
|
2020
|
+
let body = {};
|
|
2021
|
+
try {
|
|
2022
|
+
body = record(text ? JSON.parse(text) : {});
|
|
2023
|
+
} catch {}
|
|
2024
|
+
return { status: response.status, body, headers: response.headers };
|
|
2025
|
+
}
|
|
2026
|
+
function retryAfter(headers, now) {
|
|
2027
|
+
const raw = headers.get("retry-after");
|
|
2028
|
+
if (!raw)
|
|
2029
|
+
return 0;
|
|
2030
|
+
const seconds = /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : (Date.parse(raw) - now) / 1000;
|
|
2031
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.ceil(seconds), 60) : 0;
|
|
2032
|
+
}
|
|
2033
|
+
function readClaims(token) {
|
|
2034
|
+
if (!JWT.test(token))
|
|
2035
|
+
return;
|
|
2036
|
+
let payload;
|
|
2037
|
+
try {
|
|
2038
|
+
payload = record(JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8")));
|
|
2039
|
+
} catch {
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
const str2 = (v) => typeof v === "string" && v.length <= 320 ? v : undefined;
|
|
2043
|
+
const aud = typeof payload.aud === "string" ? [payload.aud] : Array.isArray(payload.aud) ? payload.aud.filter((v) => typeof v === "string") : undefined;
|
|
2044
|
+
return {
|
|
2045
|
+
sub: str2(payload.sub),
|
|
2046
|
+
exp: typeof payload.exp === "number" ? payload.exp : undefined,
|
|
2047
|
+
iat: typeof payload.iat === "number" ? payload.iat : undefined,
|
|
2048
|
+
aud,
|
|
2049
|
+
azp: str2(payload.azp),
|
|
2050
|
+
scope: str2(payload.scope),
|
|
2051
|
+
name: str2(payload.name),
|
|
2052
|
+
email: str2(payload.email),
|
|
2053
|
+
username: str2(payload.preferred_username),
|
|
2054
|
+
organizationId: str2(payload.organization_id),
|
|
2055
|
+
organizationName: str2(payload.organization_name)
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
function tokensFrom(body, now, previousRefresh) {
|
|
2059
|
+
const access = body.access_token;
|
|
2060
|
+
const refresh = typeof body.refresh_token === "string" ? body.refresh_token : previousRefresh;
|
|
2061
|
+
if (typeof access !== "string" || !TOKEN_SHAPE.test(access) || typeof refresh !== "string" || !TOKEN_SHAPE.test(refresh) || body.token_type !== undefined && String(body.token_type).toLowerCase() !== "bearer") {
|
|
2062
|
+
throw new CliError("Invalid token response from the login service. Nothing was stored.", 1, "invalid_token_response");
|
|
2063
|
+
}
|
|
2064
|
+
const claims = readClaims(access) ?? {};
|
|
2065
|
+
const lifetime = positive(body.expires_in) ? body.expires_in * 1000 : undefined;
|
|
2066
|
+
const expiry = claims.exp ? claims.exp * 1000 : lifetime ? now + lifetime : NaN;
|
|
2067
|
+
if (!Number.isFinite(expiry) || expiry <= now)
|
|
2068
|
+
throw new CliError("Invalid token response from the login service. Nothing was stored.", 1, "invalid_token_response");
|
|
2069
|
+
return { accessToken: access, refreshToken: refresh, accessExpiresAt: expiry, claims };
|
|
2070
|
+
}
|
|
2071
|
+
async function deviceLogin(issuer, options) {
|
|
2072
|
+
const ep = endpoints(issuer, options.env);
|
|
2073
|
+
const start = await postForm(options.fetch, ep.device, { client_id: CLIENT_ID, scope: DEVICE_SCOPE });
|
|
2074
|
+
if (start.status !== 200) {
|
|
2075
|
+
throw new CliError(`Login could not start (HTTP ${start.status}). ${start.status >= 500 ? "Try again in a moment." : "The login service does not know this client; ask support."}`, start.status >= 500 ? 1 : 2, "login_unavailable");
|
|
2076
|
+
}
|
|
2077
|
+
const d = start.body;
|
|
2078
|
+
if (typeof d.device_code !== "string" || !TOKEN_SHAPE.test(d.device_code) || typeof d.user_code !== "string" || !USER_CODE.test(d.user_code) || !positive(d.expires_in) || d.interval !== undefined && !positive(d.interval))
|
|
2079
|
+
throw new CliError("Invalid device-login response.", 1, "invalid_device_response");
|
|
2080
|
+
const pairing = (raw) => {
|
|
2081
|
+
let u;
|
|
2082
|
+
try {
|
|
2083
|
+
u = new URL(String(raw));
|
|
2084
|
+
} catch {
|
|
2085
|
+
throw new CliError("Invalid pairing URL.", 1, "invalid_device_response");
|
|
2086
|
+
}
|
|
2087
|
+
if (u.origin !== new URL(ep.issuer).origin || u.username || u.password || u.hash)
|
|
2088
|
+
throw new CliError("The pairing URL does not match the login service.", 1, "invalid_device_response");
|
|
2089
|
+
return u.href;
|
|
2090
|
+
};
|
|
2091
|
+
const verificationUri = pairing(d.verification_uri);
|
|
2092
|
+
const openUri = d.verification_uri_complete !== undefined ? pairing(d.verification_uri_complete) : verificationUri;
|
|
2093
|
+
options.stderr(`Open ${verificationUri} and enter code ${d.user_code}. Waiting for approval.`);
|
|
2094
|
+
if (options.openBrowser) {
|
|
2095
|
+
try {
|
|
2096
|
+
options.openBrowser(openUri);
|
|
2097
|
+
} catch {}
|
|
2098
|
+
}
|
|
2099
|
+
const started = options.now();
|
|
2100
|
+
const deadline = started + Math.min(d.expires_in, 900) * 1000;
|
|
2101
|
+
let interval = Math.max(typeof d.interval === "number" ? d.interval : 5, 1) * 1000;
|
|
2102
|
+
let warned = false;
|
|
2103
|
+
while (options.now() < deadline) {
|
|
2104
|
+
await options.sleep(Math.min(interval, Math.max(deadline - options.now(), 0)));
|
|
2105
|
+
if (options.now() >= deadline)
|
|
2106
|
+
break;
|
|
2107
|
+
const poll = await postForm(options.fetch, ep.token, { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: d.device_code, client_id: CLIENT_ID }).catch((error2) => {
|
|
2108
|
+
if (error2 instanceof CliError && error2.exitCode === 1)
|
|
2109
|
+
return;
|
|
2110
|
+
throw error2;
|
|
2111
|
+
});
|
|
2112
|
+
if (!poll) {
|
|
2113
|
+
if (!warned)
|
|
2114
|
+
options.stderr("The login service could not be reached; still waiting.");
|
|
2115
|
+
warned = true;
|
|
2116
|
+
continue;
|
|
2117
|
+
}
|
|
2118
|
+
if (poll.status === 200)
|
|
2119
|
+
return tokensFrom(poll.body, options.now());
|
|
2120
|
+
const error = String(poll.body.error ?? "");
|
|
2121
|
+
if (error === "authorization_pending")
|
|
2122
|
+
continue;
|
|
2123
|
+
if (error === "slow_down" || poll.status === 429) {
|
|
2124
|
+
interval += 5000;
|
|
2125
|
+
interval = Math.max(interval, retryAfter(poll.headers, options.now()) * 1000);
|
|
2126
|
+
continue;
|
|
2127
|
+
}
|
|
2128
|
+
if (poll.status >= 500) {
|
|
2129
|
+
if (!warned)
|
|
2130
|
+
options.stderr("The login service is temporarily unavailable; still waiting.");
|
|
2131
|
+
warned = true;
|
|
2132
|
+
continue;
|
|
2133
|
+
}
|
|
2134
|
+
if (error === "access_denied")
|
|
2135
|
+
throw new CliError("Login was denied in the browser. Run `prudai login` again if that was a mistake.", 2, "access_denied");
|
|
2136
|
+
if (error === "expired_token")
|
|
2137
|
+
throw new CliError("The device code expired. Run `prudai login` again.", 2, "expired_token");
|
|
2138
|
+
throw new CliError("Login failed. Run `prudai login` again.", 2, "login_failed");
|
|
2139
|
+
}
|
|
2140
|
+
throw new CliError("The device code expired. Run `prudai login` again.", 2, "expired_token");
|
|
2141
|
+
}
|
|
2142
|
+
async function refreshLogin(issuer, refreshToken, options) {
|
|
2143
|
+
const ep = endpoints(issuer, options.env);
|
|
2144
|
+
const reply = await postForm(options.fetch, ep.token, { grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: refreshToken });
|
|
2145
|
+
if (reply.status === 200)
|
|
2146
|
+
return tokensFrom(reply.body, options.now(), refreshToken);
|
|
2147
|
+
if (reply.status === 400 || reply.status === 401) {
|
|
2148
|
+
throw new CliError("Your login is no longer valid (logged out, revoked or idle for too long). Run `prudai login`.", 2, "not_authenticated");
|
|
2149
|
+
}
|
|
2150
|
+
throw new CliError(`The login service answered HTTP ${reply.status}; try again in a moment.`, 1, "login_unavailable");
|
|
2151
|
+
}
|
|
2152
|
+
async function revokeLogin(issuer, refreshToken, options) {
|
|
2153
|
+
const ep = endpoints(issuer, options.env);
|
|
2154
|
+
const reply = await postForm(options.fetch, ep.revoke, { client_id: CLIENT_ID, token: refreshToken, token_type_hint: "refresh_token" });
|
|
2155
|
+
return reply.status;
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
// src/exchange.ts
|
|
2159
|
+
var TOKEN_PRODUCTS = ["prudai", "irma", "ordo"];
|
|
2160
|
+
function tokenProductFor(product) {
|
|
2161
|
+
return product === "irma" ? "irma" : product === "ordo" ? "ordo" : "prudai";
|
|
2162
|
+
}
|
|
2163
|
+
var PRODUCT_AUDIENCE = { prudai: "prudai-api", irma: "irma-backend", ordo: "ordo-backend" };
|
|
2164
|
+
var audienceAllowed = (product, aud) => aud.length === 1 && aud[0] === PRODUCT_AUDIENCE[product];
|
|
2165
|
+
var record2 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
2166
|
+
var message = (body) => typeof body.error_description === "string" ? body.error_description.slice(0, 200).replace(/[\u0000-\u001f\u007f]/g, " ") : "";
|
|
2167
|
+
function exchangeEndpoint(raw, env) {
|
|
2168
|
+
let url;
|
|
2169
|
+
try {
|
|
2170
|
+
url = secureUrl(raw);
|
|
2171
|
+
} catch {
|
|
2172
|
+
throw new CliError("The exchange URL must be an https URL (or localhost), without credentials.", 2, "invalid_exchange_url");
|
|
2173
|
+
}
|
|
2174
|
+
if (url.search)
|
|
2175
|
+
throw new CliError("The exchange URL must not carry a query string.", 2, "invalid_exchange_url");
|
|
2176
|
+
requireTrustedOrigin(url.href, env);
|
|
2177
|
+
return url.href;
|
|
2178
|
+
}
|
|
2179
|
+
async function exchangeToken(options) {
|
|
2180
|
+
const url = exchangeEndpoint(options.url, options.env);
|
|
2181
|
+
let response;
|
|
2182
|
+
try {
|
|
2183
|
+
response = await options.fetch(url, {
|
|
2184
|
+
method: "POST",
|
|
2185
|
+
redirect: "error",
|
|
2186
|
+
signal: AbortSignal.timeout(15000),
|
|
2187
|
+
headers: { authorization: `Bearer ${options.loginToken}`, "content-type": "application/x-www-form-urlencoded", accept: "application/json", "x-prudai-agent": "prudai-cli" },
|
|
2188
|
+
body: new URLSearchParams({ product: options.product }).toString()
|
|
2189
|
+
});
|
|
2190
|
+
} catch {
|
|
2191
|
+
throw new CliError("Could not reach the token broker; check the network and try again.", 1, "exchange_unavailable");
|
|
2192
|
+
}
|
|
2193
|
+
const text = await response.text();
|
|
2194
|
+
let body = {};
|
|
2195
|
+
try {
|
|
2196
|
+
body = record2(text ? JSON.parse(text) : {});
|
|
2197
|
+
} catch {}
|
|
2198
|
+
const status = response.status;
|
|
2199
|
+
if (status === 200) {
|
|
2200
|
+
const token = body.access_token;
|
|
2201
|
+
const claims = typeof token === "string" ? readClaims(token) : undefined;
|
|
2202
|
+
const lifetime = body.expires_in;
|
|
2203
|
+
if (typeof token !== "string" || !claims || String(body.token_type ?? "").toLowerCase() !== "bearer" || typeof lifetime !== "number" || !(lifetime > 0 && lifetime <= 900) || body.product !== options.product || !claims.aud?.length) {
|
|
2204
|
+
throw new CliError("Invalid answer from the token broker. Nothing was used.", 1, "invalid_exchange_response");
|
|
2205
|
+
}
|
|
2206
|
+
if (!audienceAllowed(options.product, claims.aud))
|
|
2207
|
+
throw new CliError("The token broker returned a token for another audience than this product. Nothing was used.", 1, "invalid_exchange_response");
|
|
2208
|
+
const expiry = Math.min(options.now() + lifetime * 1000, claims.exp ? claims.exp * 1000 : Infinity);
|
|
2209
|
+
return { token, expiresAt: expiry, audience: claims.aud[0] };
|
|
2210
|
+
}
|
|
2211
|
+
const code = String(body.error ?? "");
|
|
2212
|
+
if (status === 401)
|
|
2213
|
+
throw new CliError("invalid_token", 2, "invalid_token");
|
|
2214
|
+
if (status === 403)
|
|
2215
|
+
throw new CliError(`Access to ${options.product} is not allowed for this login${message(body) ? `: ${message(body)}` : ""}.`, 2, "access_denied");
|
|
2216
|
+
if (status === 400)
|
|
2217
|
+
throw new CliError(`The token broker refused the request${code ? ` (${code})` : ""}.`, 2, code === "unknown_product" ? "unknown_product" : "invalid_request");
|
|
2218
|
+
if (status === 429) {
|
|
2219
|
+
const wait = Number(response.headers.get("retry-after"));
|
|
2220
|
+
throw new CliError(`The token broker is rate limiting this login${Number.isFinite(wait) && wait > 0 ? `; retry in ${Math.min(Math.ceil(wait), 3600)} s` : ""}.`, 1, "rate_limited");
|
|
2221
|
+
}
|
|
2222
|
+
throw new CliError(`The token broker is unavailable (HTTP ${status}); try again in a moment.`, 1, "exchange_unavailable");
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
// src/session.ts
|
|
2226
|
+
var SKEW_MS = 30000;
|
|
2227
|
+
|
|
2228
|
+
class Session {
|
|
2229
|
+
o;
|
|
2230
|
+
login;
|
|
2231
|
+
products = new Map;
|
|
2232
|
+
pending = new Map;
|
|
2233
|
+
constructor(o) {
|
|
2234
|
+
this.o = o;
|
|
2235
|
+
const stored = o.file.profiles[o.config.profile]?.login;
|
|
2236
|
+
this.login = { refreshToken: o.config.refreshToken };
|
|
2237
|
+
if (o.config.refreshSource === "file" && stored) {
|
|
2238
|
+
this.login.accessToken = stored.accessToken;
|
|
2239
|
+
this.login.accessExpiresAt = stored.accessExpiresAt;
|
|
2240
|
+
}
|
|
2241
|
+
for (const secret of [o.config.refreshToken, this.login.accessToken])
|
|
2242
|
+
if (secret)
|
|
2243
|
+
o.onSecret?.(secret);
|
|
2244
|
+
}
|
|
2245
|
+
get hasLogin() {
|
|
2246
|
+
return !!this.login.refreshToken || !!this.o.override;
|
|
2247
|
+
}
|
|
2248
|
+
get cachedLoginToken() {
|
|
2249
|
+
return this.login.accessToken;
|
|
2250
|
+
}
|
|
2251
|
+
get refreshTokenValue() {
|
|
2252
|
+
return this.login.refreshToken;
|
|
2253
|
+
}
|
|
2254
|
+
once(key, work) {
|
|
2255
|
+
const running = this.pending.get(key);
|
|
2256
|
+
if (running)
|
|
2257
|
+
return running;
|
|
2258
|
+
const promise = work().finally(() => this.pending.delete(key));
|
|
2259
|
+
this.pending.set(key, promise);
|
|
2260
|
+
return promise;
|
|
2261
|
+
}
|
|
2262
|
+
async loginToken(force = false) {
|
|
2263
|
+
const { accessToken, accessExpiresAt, refreshToken } = this.login;
|
|
2264
|
+
if (!refreshToken)
|
|
2265
|
+
throw notAuthenticated();
|
|
2266
|
+
if (!force && accessToken && accessExpiresAt && accessExpiresAt - SKEW_MS > this.o.now())
|
|
2267
|
+
return accessToken;
|
|
2268
|
+
return this.once("login", async () => {
|
|
2269
|
+
const tokens2 = await refreshLogin(this.o.config.issuer, refreshToken, { fetch: this.o.fetch, env: this.o.env, now: this.o.now });
|
|
2270
|
+
this.adopt(tokens2);
|
|
2271
|
+
return tokens2.accessToken;
|
|
2272
|
+
});
|
|
2273
|
+
}
|
|
2274
|
+
adopt(tokens2) {
|
|
2275
|
+
const startedFrom = this.login?.refreshToken ?? this.o.config.refreshToken;
|
|
2276
|
+
this.login = { accessToken: tokens2.accessToken, accessExpiresAt: tokens2.accessExpiresAt, refreshToken: tokens2.refreshToken };
|
|
2277
|
+
this.o.onSecret?.(tokens2.accessToken);
|
|
2278
|
+
this.o.onSecret?.(tokens2.refreshToken);
|
|
2279
|
+
if (this.o.config.refreshSource !== "file")
|
|
2280
|
+
return;
|
|
2281
|
+
try {
|
|
2282
|
+
const latest = this.o.load ? this.o.load() : this.o.file;
|
|
2283
|
+
const profile = latest.profiles[this.o.config.profile];
|
|
2284
|
+
if (!profile?.login || profile.login.refreshToken !== startedFrom)
|
|
2285
|
+
return;
|
|
2286
|
+
const login = { ...profile.login, refreshToken: tokens2.refreshToken, accessToken: tokens2.accessToken, accessExpiresAt: tokens2.accessExpiresAt };
|
|
2287
|
+
this.o.save({ ...latest, profiles: { ...latest.profiles, [this.o.config.profile]: { ...profile, login } } });
|
|
2288
|
+
} catch {}
|
|
2289
|
+
}
|
|
2290
|
+
async productToken(product) {
|
|
2291
|
+
if (this.o.override) {
|
|
2292
|
+
const token = await this.o.override.productToken(product);
|
|
2293
|
+
if (!token)
|
|
2294
|
+
throw notAuthenticated();
|
|
2295
|
+
this.o.onSecret?.(token);
|
|
2296
|
+
return token;
|
|
2297
|
+
}
|
|
2298
|
+
const wanted = tokenProductFor(product);
|
|
2299
|
+
const cached = this.products.get(wanted);
|
|
2300
|
+
if (cached && cached.expiresAt - SKEW_MS > this.o.now())
|
|
2301
|
+
return cached.token;
|
|
2302
|
+
return this.once(`product:${wanted}`, async () => {
|
|
2303
|
+
let login = await this.loginToken();
|
|
2304
|
+
const ask = () => exchangeToken({ fetch: this.o.fetch, env: this.o.env, now: this.o.now, url: this.o.config.exchangeUrl, loginToken: login, product: wanted });
|
|
2305
|
+
let result;
|
|
2306
|
+
try {
|
|
2307
|
+
result = await ask();
|
|
2308
|
+
} catch (error) {
|
|
2309
|
+
if (!(error instanceof CliError && error.code === "invalid_token"))
|
|
2310
|
+
throw error;
|
|
2311
|
+
login = await this.loginToken(true);
|
|
2312
|
+
try {
|
|
2313
|
+
result = await ask();
|
|
2314
|
+
} catch (again) {
|
|
2315
|
+
if (again instanceof CliError && again.code === "invalid_token")
|
|
2316
|
+
throw notAuthenticated("The login was rejected by the token broker.");
|
|
2317
|
+
throw again;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
this.products.set(wanted, { token: result.token, expiresAt: result.expiresAt });
|
|
2321
|
+
this.o.onSecret?.(result.token);
|
|
2322
|
+
return result.token;
|
|
2323
|
+
});
|
|
2324
|
+
}
|
|
2325
|
+
forget(product) {
|
|
2326
|
+
this.products.delete(tokenProductFor(product));
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
function notAuthenticated(why) {
|
|
2330
|
+
return new CliError(`${why ? `${why} ` : ""}Not logged in. Run \`prudai login\`.`, 2, "not_authenticated");
|
|
2331
|
+
}
|
|
2332
|
+
function loginClaims(session) {
|
|
2333
|
+
const token = session.cachedLoginToken;
|
|
2334
|
+
return token ? readClaims(token) : undefined;
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
// src/auth.ts
|
|
2338
|
+
var clock = (o) => o.now ?? Date.now;
|
|
2339
|
+
var wait = (o) => o.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
2340
|
+
var env = (o) => o.env ?? {};
|
|
2341
|
+
function identityOf(claims) {
|
|
2342
|
+
const name = claims.name ?? claims.username ?? null;
|
|
2343
|
+
return {
|
|
2344
|
+
user: { id: claims.sub ?? null, name, email: claims.email ?? null },
|
|
2345
|
+
organization: { id: claims.organizationId ?? null, name: claims.organizationName ?? null }
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
function accessMap(config) {
|
|
2349
|
+
return { platform: `prudai (via ${new URL(config.exchangeUrl).host})`, irma: "irma", ordo: "ordo" };
|
|
2350
|
+
}
|
|
2351
|
+
function storeLogin(options, tokens2, before) {
|
|
2352
|
+
const latest = options.load ? options.load() : options.file;
|
|
2353
|
+
const name = options.config.profile;
|
|
2354
|
+
const current = latest.profiles[name]?.login;
|
|
2355
|
+
if (current?.refreshToken !== before?.refreshToken)
|
|
2356
|
+
throw new CliError("The login changed while this command ran; nothing was stored.", 2, "config_changed");
|
|
2357
|
+
const identity = identityOf(tokens2.claims);
|
|
2358
|
+
const { token: _t, tokenApiUrl: _a, tokenKind: _k, expiresAt: _e, products: _p, ...profile } = latest.profiles[name] ?? {};
|
|
2359
|
+
const login = { issuer: options.config.issuer, refreshToken: tokens2.refreshToken, accessToken: tokens2.accessToken, accessExpiresAt: tokens2.accessExpiresAt };
|
|
2360
|
+
try {
|
|
2361
|
+
options.save({ ...latest, profiles: { ...latest.profiles, [name]: { ...profile, ...identity, login } } });
|
|
2362
|
+
} catch {
|
|
2363
|
+
throw new CliError("Could not store the login safely. Nothing was kept.", 1, "config_write_failed");
|
|
2364
|
+
}
|
|
2365
|
+
return identity;
|
|
2366
|
+
}
|
|
2367
|
+
async function sessionAlive(options, refreshToken) {
|
|
2368
|
+
try {
|
|
2369
|
+
await refreshLogin(options.config.issuer, refreshToken, { fetch: options.fetch, env: env(options), now: clock(options) });
|
|
2370
|
+
return true;
|
|
2371
|
+
} catch (error) {
|
|
2372
|
+
if (error instanceof CliError && error.code === "not_authenticated")
|
|
2373
|
+
return false;
|
|
2374
|
+
throw error;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
async function authLogin(options) {
|
|
2378
|
+
const { config, file } = options;
|
|
2379
|
+
if (config.refreshSource === "env")
|
|
2380
|
+
throw new CliError("PRUDAI_REFRESH_TOKEN is set, so this shell is already logged in. Unset it to log in interactively.", 2, "already_authenticated");
|
|
2381
|
+
const before = file.profiles[config.profile]?.login;
|
|
2382
|
+
if (before && await sessionAlive(options, before.refreshToken)) {
|
|
2383
|
+
throw new CliError("A login already exists for this profile. Run `prudai auth logout` first (or use another profile).", 2, "already_authenticated");
|
|
2384
|
+
}
|
|
2385
|
+
endpoints(config.issuer, env(options));
|
|
2386
|
+
exchangeEndpoint(config.exchangeUrl, env(options));
|
|
2387
|
+
const tokens2 = await deviceLogin(config.issuer, { fetch: options.fetch, env: env(options), stderr: options.stderr, now: clock(options), sleep: wait(options), openBrowser: options.openBrowser });
|
|
2388
|
+
const identity = storeLogin(options, tokens2, before);
|
|
2389
|
+
return {
|
|
2390
|
+
status: "linked",
|
|
2391
|
+
profile: config.profile,
|
|
2392
|
+
issuer: config.issuer,
|
|
2393
|
+
...identity,
|
|
2394
|
+
device: hostname().slice(0, 60),
|
|
2395
|
+
loginValidUntil: new Date(tokens2.accessExpiresAt).toISOString(),
|
|
2396
|
+
next: "Run `prudai whoami`, then `prudai guide`."
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
2399
|
+
async function authStatus(options, online = false) {
|
|
2400
|
+
const { config, session } = options;
|
|
2401
|
+
if (!session.hasLogin) {
|
|
2402
|
+
if (config.legacyLogin)
|
|
2403
|
+
throw new CliError("This profile holds a removed personal token (prudai_pat_…). It no longer works: run `prudai login` (Keycloak device login).", 2, "legacy_login");
|
|
2404
|
+
throw notAuthenticated();
|
|
2405
|
+
}
|
|
2406
|
+
let claims = loginClaims(session);
|
|
2407
|
+
if (online || !claims) {
|
|
2408
|
+
await session.loginToken(online);
|
|
2409
|
+
claims = loginClaims(session);
|
|
2410
|
+
}
|
|
2411
|
+
const stored = options.file.profiles[config.profile];
|
|
2412
|
+
const identity = claims ? identityOf(claims) : { user: stored?.user, organization: stored?.organization };
|
|
2413
|
+
return {
|
|
2414
|
+
status: "authenticated",
|
|
2415
|
+
profile: config.profile,
|
|
2416
|
+
...identity,
|
|
2417
|
+
login: { issuer: config.issuer, source: config.refreshSource === "env" ? "PRUDAI_REFRESH_TOKEN" : "config file", accessValidUntil: claims?.exp ? new Date(claims.exp * 1000).toISOString() : null, checkedOnline: online || !loginClaims(session) },
|
|
2418
|
+
access: { kind: "user_rights", note: "You act with your own role and rights in each product; there is no key or scope list. Writes that need approval wait for a person." },
|
|
2419
|
+
products: accessMap(config),
|
|
2420
|
+
broker: config.exchangeUrl
|
|
2421
|
+
};
|
|
2422
|
+
}
|
|
2423
|
+
async function authLogout(options) {
|
|
2424
|
+
const { config } = options;
|
|
2425
|
+
const refresh = config.refreshToken;
|
|
2426
|
+
if (!refresh) {
|
|
2427
|
+
if (config.legacyLogin) {
|
|
2428
|
+
removeLogin(options, undefined);
|
|
2429
|
+
return { status: "removed_legacy", profile: config.profile, removedLocally: true };
|
|
2430
|
+
}
|
|
2431
|
+
throw notAuthenticated();
|
|
2432
|
+
}
|
|
2433
|
+
let status;
|
|
2434
|
+
try {
|
|
2435
|
+
status = await revokeLogin(config.issuer, refresh, { fetch: options.fetch, env: env(options) });
|
|
2436
|
+
} catch (error) {
|
|
2437
|
+
if (error instanceof CliError && error.exitCode === 1)
|
|
2438
|
+
throw new CliError("Logout could not reach the login service; the local login was kept. Try again.", 1, "network_error");
|
|
2439
|
+
throw error;
|
|
2440
|
+
}
|
|
2441
|
+
if (status >= 500 || status === 429)
|
|
2442
|
+
throw new CliError(`Logout failed (HTTP ${status}); the local login was kept. Try again.`, 1, "logout_failed");
|
|
2443
|
+
const revoked = status === 200 ? "revoked" : "already_rejected";
|
|
2444
|
+
if (config.refreshSource === "env") {
|
|
2445
|
+
options.stderr("The session of PRUDAI_REFRESH_TOKEN was ended. Unset the variable in your shell; stored profile credentials were kept.");
|
|
2446
|
+
return { status: revoked, profile: config.profile, removedLocally: false, unsetEnvironment: true };
|
|
2447
|
+
}
|
|
2448
|
+
removeLogin(options, refresh);
|
|
2449
|
+
return { status: revoked, profile: config.profile, removedLocally: true };
|
|
2450
|
+
}
|
|
2451
|
+
function removeLogin(options, refresh) {
|
|
2452
|
+
const latest = options.load ? options.load() : options.file;
|
|
2453
|
+
const current = latest.profiles[options.config.profile];
|
|
2454
|
+
if (refresh && current?.login?.refreshToken !== refresh)
|
|
2455
|
+
throw new CliError("The session was ended, but the local login changed meanwhile and was kept.", 2, "config_changed");
|
|
2456
|
+
const { login: _l, token: _t, tokenApiUrl: _a, tokenKind: _k, expiresAt: _e, products: _p, user: _u, organization: _o, ...profile } = current ?? {};
|
|
2457
|
+
try {
|
|
2458
|
+
options.save({ ...latest, profiles: { ...latest.profiles, [options.config.profile]: profile } });
|
|
2459
|
+
} catch {
|
|
2460
|
+
throw new CliError("The session was ended, but the local credentials could not be removed.", 1, "config_write_failed");
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
function authToken(options) {
|
|
2464
|
+
const { config, session } = options;
|
|
2465
|
+
if (!session.hasLogin)
|
|
2466
|
+
throw notAuthenticated();
|
|
2467
|
+
const claims = loginClaims(session);
|
|
2468
|
+
return {
|
|
2469
|
+
profile: config.profile,
|
|
2470
|
+
kind: "keycloak_login",
|
|
2471
|
+
source: config.refreshSource === "env" ? "environment (PRUDAI_REFRESH_TOKEN)" : "config file",
|
|
2472
|
+
issuer: config.issuer,
|
|
2473
|
+
...claims?.exp ? { loginValidUntil: new Date(claims.exp * 1000).toISOString() } : {},
|
|
2474
|
+
productTokens: { lifetime: "5 minutes, one product each, kept in memory only", products: TOKEN_PRODUCTS },
|
|
2475
|
+
next: 'Use a product token without printing it: curl -H "Authorization: Bearer $(prudai auth token --reveal --product irma)" … , or let prudai api make the call.'
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
async function revealProductToken(options, product) {
|
|
2479
|
+
if (!options.session.hasLogin)
|
|
2480
|
+
throw notAuthenticated();
|
|
2481
|
+
if (!TOKEN_PRODUCTS.includes(product))
|
|
2482
|
+
throw new CliError(`Unknown product "${product}". Use ${TOKEN_PRODUCTS.join(", ")}.`, 2, "unknown_product");
|
|
2483
|
+
return options.session.productToken(tokenProductFor(product));
|
|
2484
|
+
}
|
|
2485
|
+
async function authSet(options) {
|
|
2486
|
+
const { config, file } = options;
|
|
2487
|
+
const before = file.profiles[config.profile]?.login;
|
|
2488
|
+
if (config.refreshSource === "env" || before)
|
|
2489
|
+
throw new CliError("A login already exists. Run `prudai auth logout` first and unset PRUDAI_REFRESH_TOKEN.", 2, "already_authenticated");
|
|
2490
|
+
if (!options.readStdin)
|
|
2491
|
+
throw new CliError('Pipe the refresh token on stdin: printf %s "$TOKEN" | prudai auth set --stdin', 2, "stdin_required");
|
|
2492
|
+
const refresh = (await options.readStdin()).trim();
|
|
2493
|
+
if (!refresh || refresh.length > 8192 || /\s/.test(refresh))
|
|
2494
|
+
throw new CliError("Expected one Keycloak refresh token on stdin (from `prudai auth export --reveal`).", 2, "invalid_refresh_token");
|
|
2495
|
+
const tokens2 = await refreshLogin(config.issuer, refresh, { fetch: options.fetch, env: env(options), now: clock(options) });
|
|
2496
|
+
const identity = storeLogin(options, tokens2, before);
|
|
2497
|
+
return { status: "stored", profile: config.profile, ...identity, next: "Run `prudai whoami` to check the login." };
|
|
2498
|
+
}
|
|
2499
|
+
function authExport(options) {
|
|
2500
|
+
const refresh = options.session.refreshTokenValue;
|
|
2501
|
+
if (!refresh)
|
|
2502
|
+
throw notAuthenticated();
|
|
2503
|
+
return refresh;
|
|
2504
|
+
}
|
|
2505
|
+
|
|
2506
|
+
// src/config.ts
|
|
2507
|
+
import { closeSync as closeSync2, constants as constants2, existsSync as existsSync3, fchmodSync as fchmodSync2, fsyncSync, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
2508
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
2509
|
+
import { homedir } from "node:os";
|
|
2510
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
2511
|
+
var DEFAULT_API_URL = "https://api.prudai.com";
|
|
2512
|
+
var DEFAULT_ISSUER = "https://login.prudai.com/realms/prudai";
|
|
2513
|
+
var DEFAULT_EXCHANGE_URL = "https://mcp.prudai.com/oauth/exchange";
|
|
2514
|
+
var object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
2515
|
+
var names = (name) => /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(name);
|
|
2516
|
+
var identityPart = (v, keys) => v === undefined || object2(v) && Object.entries(v).every(([k, x]) => keys.includes(k) && (x === null || typeof x === "string"));
|
|
2517
|
+
function configPath(env2) {
|
|
2518
|
+
return env2.PRUDAI_CONFIG_FILE || join3(env2.XDG_CONFIG_HOME || join3(env2.HOME || homedir(), ".config"), "prudai", "config.json");
|
|
2519
|
+
}
|
|
2520
|
+
function validate(raw) {
|
|
2521
|
+
if (!object2(raw) || !object2(raw.profiles) || raw.defaultProfile !== undefined && (typeof raw.defaultProfile !== "string" || !names(raw.defaultProfile))) {
|
|
2522
|
+
throw new CliError("Invalid Prudai configuration.", 2, "invalid_config");
|
|
2523
|
+
}
|
|
2524
|
+
for (const [name, p] of Object.entries(raw.profiles)) {
|
|
2525
|
+
if (!names(name) || !object2(p))
|
|
2526
|
+
throw new CliError("Invalid Prudai profile.", 2, "invalid_config");
|
|
2527
|
+
for (const key of ["apiUrl", "token", "tokenApiUrl", "expiresAt", "registryUrl", "exchangeUrl"]) {
|
|
2528
|
+
if (p[key] !== undefined && typeof p[key] !== "string")
|
|
2529
|
+
throw new CliError("Invalid Prudai profile value.", 2, "invalid_config");
|
|
2530
|
+
}
|
|
2531
|
+
if (p.tokenKind !== undefined && typeof p.tokenKind !== "string")
|
|
2532
|
+
throw new CliError("Invalid Prudai profile value.", 2, "invalid_config");
|
|
2533
|
+
if (p.login !== undefined) {
|
|
2534
|
+
const l = p.login;
|
|
2535
|
+
if (!object2(l) || typeof l.issuer !== "string" || typeof l.refreshToken !== "string" || !l.refreshToken || l.accessToken !== undefined && typeof l.accessToken !== "string" || l.accessExpiresAt !== undefined && (typeof l.accessExpiresAt !== "number" || !Number.isFinite(l.accessExpiresAt))) {
|
|
2536
|
+
throw new CliError("Invalid login in configuration.", 2, "invalid_config");
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
if (!identityPart(p.user, ["id", "name", "email"]) || !identityPart(p.organization, ["id", "name"]))
|
|
2540
|
+
throw new CliError("Invalid identity in configuration.", 2, "invalid_config");
|
|
2541
|
+
if (p.products !== undefined && (!Array.isArray(p.products) || p.products.some((v) => typeof v !== "string")))
|
|
2542
|
+
throw new CliError("Invalid products in configuration.", 2, "invalid_config");
|
|
2543
|
+
for (const key of ["productApiUrls", "specs"]) {
|
|
2544
|
+
if (p[key] !== undefined && (!object2(p[key]) || Object.values(p[key]).some((v) => typeof v !== "string")))
|
|
2545
|
+
throw new CliError("Invalid product configuration.", 2, "invalid_config");
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
return raw;
|
|
2549
|
+
}
|
|
2550
|
+
function readConfig(path) {
|
|
2551
|
+
try {
|
|
2552
|
+
const stat2 = lstatSync2(path);
|
|
2553
|
+
if (stat2.isSymbolicLink())
|
|
2554
|
+
throw new CliError("Refusing a symlinked credential file.", 2, "unsafe_config");
|
|
2555
|
+
const config = validate(JSON.parse(readFileSync2(path, "utf8")));
|
|
2556
|
+
if (Object.values(config.profiles).some((profile) => profile.token || profile.login) && (stat2.mode & 63) !== 0) {
|
|
2557
|
+
throw new CliError("Credential file is accessible to other users. Set permissions to 0600.", 2, "unsafe_config");
|
|
2558
|
+
}
|
|
2559
|
+
return config;
|
|
2560
|
+
} catch (e) {
|
|
2561
|
+
if (e.code === "ENOENT")
|
|
2562
|
+
return { profiles: {} };
|
|
2563
|
+
if (e instanceof CliError)
|
|
2564
|
+
throw e;
|
|
2565
|
+
throw new CliError("Could not read Prudai configuration.", 2, "invalid_config");
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
function writeConfig(path, cfg) {
|
|
2569
|
+
validate(cfg);
|
|
2570
|
+
const dir = dirname3(path);
|
|
2571
|
+
mkdirSync2(dir, { recursive: true, mode: 448 });
|
|
2572
|
+
try {
|
|
2573
|
+
if (lstatSync2(path).isSymbolicLink())
|
|
2574
|
+
throw new CliError("Refusing a symlinked credential file.", 2, "unsafe_config");
|
|
2575
|
+
} catch (e) {
|
|
2576
|
+
if (e.code !== "ENOENT")
|
|
2577
|
+
throw e;
|
|
2578
|
+
}
|
|
2579
|
+
const temporary = join3(dir, `.config-${randomUUID2()}.tmp`);
|
|
2580
|
+
const fd = openSync2(temporary, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
|
|
2581
|
+
try {
|
|
2582
|
+
fchmodSync2(fd, 384);
|
|
2583
|
+
writeFileSync2(fd, `${JSON.stringify(cfg, null, 2)}
|
|
2584
|
+
`);
|
|
2585
|
+
fsyncSync(fd);
|
|
2586
|
+
renameSync3(temporary, path);
|
|
2587
|
+
} finally {
|
|
2588
|
+
closeSync2(fd);
|
|
2589
|
+
if (existsSync3(temporary))
|
|
2590
|
+
unlinkSync2(temporary);
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
function selectedProfile(env2, file, profileName) {
|
|
2594
|
+
const explicit = profileName || env2.PRUDAI_PROFILE || file.defaultProfile;
|
|
2595
|
+
const name = explicit || "default";
|
|
2596
|
+
if (!names(name))
|
|
2597
|
+
throw new CliError('Invalid profile name. Use 1–64 letters, digits, "_" or "-".', 2, "invalid_profile");
|
|
2598
|
+
return { name, explicit: !!explicit, exists: Object.hasOwn(file.profiles, name) };
|
|
2599
|
+
}
|
|
2600
|
+
function unknownProfile(name) {
|
|
2601
|
+
return new CliError(`Profile "${name}" does not exist. Create it with \`prudai profile create ${name}\`, or pick an existing one from \`prudai profile list\` (\`prudai profile use <name>\`).`, 2, "unknown_profile");
|
|
2602
|
+
}
|
|
2603
|
+
function resolveConfig(env2, file, profileName) {
|
|
2604
|
+
validate(file);
|
|
2605
|
+
const selection = selectedProfile(env2, file, profileName);
|
|
2606
|
+
const profile = selection.name;
|
|
2607
|
+
if (!selection.exists && selection.explicit)
|
|
2608
|
+
throw unknownProfile(profile);
|
|
2609
|
+
const p = selection.exists ? file.profiles[profile] : {};
|
|
2610
|
+
const { login, token, tokenApiUrl: _a, tokenKind: _k, expiresAt: _e, products: _p, ...rest } = p;
|
|
2611
|
+
const envRefresh = env2.PRUDAI_REFRESH_TOKEN?.trim();
|
|
2612
|
+
const refreshToken = envRefresh || login?.refreshToken;
|
|
2613
|
+
return {
|
|
2614
|
+
...rest,
|
|
2615
|
+
profile,
|
|
2616
|
+
apiUrl: (env2.PRUDAI_API_URL || p.apiUrl || DEFAULT_API_URL).replace(/\/+$/, ""),
|
|
2617
|
+
issuer: (env2.PRUDAI_ISSUER || (envRefresh ? undefined : login?.issuer) || DEFAULT_ISSUER).replace(/\/+$/, ""),
|
|
2618
|
+
exchangeUrl: env2.PRUDAI_EXCHANGE_URL || p.exchangeUrl || DEFAULT_EXCHANGE_URL,
|
|
2619
|
+
...refreshToken ? { refreshToken } : {},
|
|
2620
|
+
refreshSource: envRefresh ? "env" : login?.refreshToken ? "file" : "none",
|
|
2621
|
+
legacyLogin: !!token && !login
|
|
2622
|
+
};
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
// src/projects.ts
|
|
2626
|
+
var MEMOS_DEFAULT_PROJECT = "Transcribe";
|
|
2627
|
+
var MEMO_KINDS = new Set(["audio", "transcript"]);
|
|
2628
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2629
|
+
var PROJECT_PAGE = 100;
|
|
2630
|
+
var DOCUMENT_PAGE = 200;
|
|
2631
|
+
var NAME_PAGES = 5;
|
|
2632
|
+
var MEMO_PAGES = 25;
|
|
2633
|
+
async function apiAccess(ctx, product, origin) {
|
|
2634
|
+
if (!origin)
|
|
2635
|
+
throw new CliError(`Configure the ${product} API origin: prudai profile set productApiUrls.${product} <origin>, or --api-url <origin>.`);
|
|
2636
|
+
const apiUrl = safeApiOrigin(origin);
|
|
2637
|
+
requireTrustedOrigin(apiUrl, ctx.env);
|
|
2638
|
+
const token = await credentialFor(product, ctx);
|
|
2639
|
+
if (!token)
|
|
2640
|
+
throw missingCredential(product);
|
|
2641
|
+
return { ctx, apiUrl, token };
|
|
2642
|
+
}
|
|
2643
|
+
async function readEnvelope(access, command, input) {
|
|
2644
|
+
const request = buildOperationRequest(command, { ...input });
|
|
2645
|
+
const result = await requestJson(access.ctx.fetch, `${access.apiUrl}${request.path}`, { method: request.method, headers: request.headers, token: access.token, env: access.ctx.env });
|
|
2646
|
+
if (result.status >= 400)
|
|
2647
|
+
throw httpError(result.status, result.body, command.product);
|
|
2648
|
+
if (result.status !== 200 || !isEnvelopeLike(result.body))
|
|
2649
|
+
throw new CliError(`${command.method} ${command.path} did not answer with a /v1 envelope.`, 1, "invalid_envelope");
|
|
2650
|
+
return parseEnvelope(result.body);
|
|
2651
|
+
}
|
|
2652
|
+
function nextCursor(envelope) {
|
|
2653
|
+
for (const entry of envelope.next)
|
|
2654
|
+
if (isRecord(entry) && isRecord(entry.params) && typeof entry.params.cursor === "string")
|
|
2655
|
+
return entry.params.cursor;
|
|
2656
|
+
return;
|
|
2657
|
+
}
|
|
2658
|
+
var brief = (project) => ({ id: project.id, name: project.name, ...typeof project.archived === "boolean" ? { archived: project.archived } : {} });
|
|
2659
|
+
var sameName = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
2660
|
+
async function resolveProject(access, reference, commands, options = {}) {
|
|
2661
|
+
const wanted = reference.trim();
|
|
2662
|
+
if (!wanted || wanted.length > 255)
|
|
2663
|
+
throw new CliError("A project is a UUID or an exact project name (1 to 255 characters).", 2, "validation_error");
|
|
2664
|
+
if (UUID.test(wanted)) {
|
|
2665
|
+
const id = wanted.toLowerCase();
|
|
2666
|
+
if (!options.verify || !commands.get)
|
|
2667
|
+
return { id, name: null };
|
|
2668
|
+
const data = (await readEnvelope(access, commands.get, { params: { project_id: id } })).data;
|
|
2669
|
+
return { id, name: isRecord(data) && typeof data.name === "string" ? data.name : null };
|
|
2670
|
+
}
|
|
2671
|
+
const listProjects = commands.list;
|
|
2672
|
+
if (!listProjects) {
|
|
2673
|
+
throw new NotAvailableError("A project name can only be resolved through GET /v1/projects, which the platform does not serve yet. Pass the project id (a UUID). Nothing was sent.", { planned: "GET /v1/projects", next: ["Pass the project id instead of its name.", "Name resolution starts working without a CLI release once the platform spec lists the operation."] });
|
|
2674
|
+
}
|
|
2675
|
+
const found = [];
|
|
2676
|
+
let cursor;
|
|
2677
|
+
let pages = 0;
|
|
2678
|
+
do {
|
|
2679
|
+
const page = await readEnvelope(access, listProjects, { query: { q: wanted, limit: PROJECT_PAGE, ...cursor ? { cursor } : {} } });
|
|
2680
|
+
if (!Array.isArray(page.data))
|
|
2681
|
+
throw new CliError("The project list is not a list.", 1, "invalid_response");
|
|
2682
|
+
found.push(...page.data.filter((entry) => isRecord(entry) && typeof entry.id === "string" && typeof entry.name === "string" && entry.archived !== true));
|
|
2683
|
+
cursor = nextCursor(page);
|
|
2684
|
+
pages++;
|
|
2685
|
+
} while (cursor && pages < NAME_PAGES);
|
|
2686
|
+
const exact = found.filter((project) => sameName(project.name, wanted));
|
|
2687
|
+
if (cursor) {
|
|
2688
|
+
throw new DetailedCliError(`More than ${found.length} projects match "${wanted}", so the name cannot be resolved with certainty. Use the project id (prudai projects list --q "${wanted}"). Nothing was sent.`, "ambiguous_project", { candidates: exact.map(brief) });
|
|
2689
|
+
}
|
|
2690
|
+
if (exact.length === 1)
|
|
2691
|
+
return { id: exact[0].id, name: exact[0].name };
|
|
2692
|
+
if (exact.length > 1) {
|
|
2693
|
+
throw new DetailedCliError(`"${wanted}" is the name of ${exact.length} projects: ${exact.map((project) => project.id).join(", ")}. Pass the id of the one you mean. Nothing was sent.`, "ambiguous_project", { candidates: exact.map(brief) });
|
|
2694
|
+
}
|
|
2695
|
+
throw new DetailedCliError(`No project is named "${wanted}".${found.length ? ` Similar names are listed under candidates; pass the id of the one you mean.` : " prudai projects list shows your projects."} Nothing was sent.`, "project_not_found", { candidates: found.slice(0, 10).map(brief) });
|
|
2696
|
+
}
|
|
2697
|
+
function memoProjectReference(ctx) {
|
|
2698
|
+
return str(ctx.flags, "project") ?? (ctx.env.PRUDAI_MEMOS_PROJECT?.trim() || MEMOS_DEFAULT_PROJECT);
|
|
2699
|
+
}
|
|
2700
|
+
function memoRow(document) {
|
|
2701
|
+
const audio = isRecord(document.audio) ? document.audio : null;
|
|
2702
|
+
return {
|
|
2703
|
+
id: document.id,
|
|
2704
|
+
filename: document.filename,
|
|
2705
|
+
kind: document.kind,
|
|
2706
|
+
status: document.status,
|
|
2707
|
+
uploaded_by: document.uploaded_by ?? null,
|
|
2708
|
+
subtitles: document.subtitles ?? null,
|
|
2709
|
+
language: audio && typeof audio.language_code === "string" ? audio.language_code : null,
|
|
2710
|
+
created_at: document.created_at ?? null
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
var cell = (value, width) => terminalSafe(value === null || value === undefined || value === "" ? "-" : String(value)).slice(0, width).padEnd(width);
|
|
2714
|
+
var person = (value) => isRecord(value) ? String(value.name ?? value.email ?? "-") : "-";
|
|
2715
|
+
var subtitles = (value) => isRecord(value) ? String(value.format ?? "yes") : "-";
|
|
2716
|
+
async function listMemos(access, command, project, ctx) {
|
|
2717
|
+
const limit = intFlag(ctx.flags, "limit", 50, 1, 500);
|
|
2718
|
+
const status = str(ctx.flags, "status");
|
|
2719
|
+
const trash = ctx.flags.trash === true;
|
|
2720
|
+
const memos = [];
|
|
2721
|
+
let scanned = 0;
|
|
2722
|
+
let unreadable = false;
|
|
2723
|
+
let cursor;
|
|
2724
|
+
let pages = 0;
|
|
2725
|
+
do {
|
|
2726
|
+
const page = await readEnvelope(access, command, { params: { project_id: project.id }, query: { limit: DOCUMENT_PAGE, ...status ? { status } : {}, ...trash ? { deleted: "true" } : {}, ...cursor ? { cursor } : {} } });
|
|
2727
|
+
if (!Array.isArray(page.data))
|
|
2728
|
+
throw new CliError("The document list is not a list.", 1, "invalid_response");
|
|
2729
|
+
for (const entry of page.data) {
|
|
2730
|
+
scanned++;
|
|
2731
|
+
if (isRecord(entry) && typeof entry.kind === "string" && MEMO_KINDS.has(entry.kind))
|
|
2732
|
+
memos.push(entry);
|
|
2733
|
+
}
|
|
2734
|
+
cursor = nextCursor(page);
|
|
2735
|
+
if (!cursor && page.completeness.truncated === true)
|
|
2736
|
+
unreadable = true;
|
|
2737
|
+
pages++;
|
|
2738
|
+
} while (cursor && pages < MEMO_PAGES);
|
|
2739
|
+
const sawAll = !cursor && !unreadable;
|
|
2740
|
+
const rows = memos.slice(0, limit).map(memoRow);
|
|
2741
|
+
const truncated = rows.length < memos.length || !sawAll;
|
|
2742
|
+
const envelope = localEnvelope(rows, {
|
|
2743
|
+
context: { project: { id: project.id, name: project.name }, kinds: [...MEMO_KINDS], ...status ? { status } : {}, ...trash ? { deleted: true } : {} },
|
|
2744
|
+
completeness: { total: sawAll ? memos.length : null, returned: rows.length, truncated, documents_scanned: scanned, filter: "kind is audio or transcript (applied by the CLI)" },
|
|
2745
|
+
notIncluded: [
|
|
2746
|
+
"Other documents of the project (kind document) are not listed here; prudai projects docs <project> lists everything.",
|
|
2747
|
+
...rows.length < memos.length ? [`${memos.length - rows.length} more memos exist; raise --limit.`] : [],
|
|
2748
|
+
...!sawAll ? [`Only the first ${scanned} documents of the project were read, so more memos may exist.`] : []
|
|
2749
|
+
],
|
|
2750
|
+
provenance: { kind: "cli", derived_from: `${command.method} ${command.path}` },
|
|
2751
|
+
next: rows.length ? [
|
|
2752
|
+
{ action: "prudai memos transcript <document_id>", why: "Read the text of one memo." },
|
|
2753
|
+
{ action: "prudai memos download <document_id> --out <path>", why: "Save the original recording." }
|
|
2754
|
+
] : [{ action: "prudai memos upload <file>", why: "Add a recording or a transcript (.vtt, .srt)." }]
|
|
2755
|
+
});
|
|
2756
|
+
const header = `${"id".padEnd(36)} ${"filename".padEnd(40)} ${"kind".padEnd(10)} ${"status".padEnd(10)} ${"uploaded_by".padEnd(20)} ${"subtitles".padEnd(9)} language`;
|
|
2757
|
+
ctx.emit(envelope, rows.length ? [
|
|
2758
|
+
`Project ${project.name ?? ""} ${project.id}`.trim(),
|
|
2759
|
+
header,
|
|
2760
|
+
...rows.map((row) => `${cell(row.id, 36)} ${cell(row.filename, 40)} ${cell(row.kind, 10)} ${cell(row.status, 10)} ${cell(person(row.uploaded_by), 20)} ${cell(subtitles(row.subtitles), 9)} ${cell(row.language, 8)}`.trimEnd()),
|
|
2761
|
+
...truncated ? [`(not complete: ${JSON.stringify(envelope.completeness)})`] : []
|
|
2762
|
+
].join(`
|
|
2763
|
+
`) : "No recordings or transcripts in this project.");
|
|
2764
|
+
return 0;
|
|
2765
|
+
}
|
|
2766
|
+
|
|
2767
|
+
// src/scopes.ts
|
|
2768
|
+
var SHAPE = /^[a-z][a-z0-9-]*:([a-z][a-z0-9_]*|\*):(read|write|delete)$/;
|
|
2769
|
+
var KEY_WRITE_SCOPE = "account:api_keys:write";
|
|
2770
|
+
var RESERVED_PRODUCTS = ["irma", "ordo"];
|
|
2771
|
+
function shapeProblem(scope) {
|
|
2772
|
+
if (SHAPE.test(scope))
|
|
2773
|
+
return;
|
|
2774
|
+
if (scope === "*")
|
|
2775
|
+
return "A bare * is not a scope. Use <product>:*:<verb> for everything of one verb in one product.";
|
|
2776
|
+
const parts = scope.split(":");
|
|
2777
|
+
if (parts.length !== 3)
|
|
2778
|
+
return "A scope has three parts: <product>:<object>:<verb>, e.g. irma:risks:read.";
|
|
2779
|
+
const [product, object3, verb] = parts;
|
|
2780
|
+
if (product === "*")
|
|
2781
|
+
return "The product cannot be a wildcard (*:x:read is invalid). Name the product.";
|
|
2782
|
+
if (verb === "*")
|
|
2783
|
+
return object3 === "*" ? "<product>:*:* is invalid: pick a verb (read, write or delete) per wildcard." : "<product>:<object>:* is invalid: name each verb (read, write, delete) separately.";
|
|
2784
|
+
if (!["read", "write", "delete"].includes(verb))
|
|
2785
|
+
return `Unknown verb "${verb}". Verbs are read, write and delete.`;
|
|
2786
|
+
return "Product and object are lowercase words (a-z, 0-9, _ or -).";
|
|
2787
|
+
}
|
|
2788
|
+
function covers(held, wanted, catalog) {
|
|
2789
|
+
if (held.includes(wanted))
|
|
2790
|
+
return true;
|
|
2791
|
+
const [product, object3, verb] = wanted.split(":");
|
|
2792
|
+
if (object3 === "*")
|
|
2793
|
+
return false;
|
|
2794
|
+
if (!held.includes(`${product}:*:${verb}`))
|
|
2795
|
+
return false;
|
|
2796
|
+
return !explicitOnly(product, object3, catalog);
|
|
2797
|
+
}
|
|
2798
|
+
function explicitOnly(product, object3, catalog) {
|
|
2799
|
+
return !!catalog?.products.find((entry) => entry.product === product)?.objects.find((entry) => entry.object === object3)?.explicit_only;
|
|
2800
|
+
}
|
|
2801
|
+
function checkScopes(requested, catalog) {
|
|
2802
|
+
const problems = [];
|
|
2803
|
+
const warnings = [];
|
|
2804
|
+
if (!requested.length)
|
|
2805
|
+
problems.push({ scope: "", code: "validation_error", reason: "Name at least one scope (--scopes product:object:verb[,…]) or a bundle." });
|
|
2806
|
+
for (const scope of requested) {
|
|
2807
|
+
const shape = shapeProblem(scope);
|
|
2808
|
+
if (shape) {
|
|
2809
|
+
problems.push({ scope, code: "validation_error", reason: shape });
|
|
2810
|
+
continue;
|
|
2811
|
+
}
|
|
2812
|
+
if (!catalog)
|
|
2813
|
+
continue;
|
|
2814
|
+
const [product, object3, verb] = scope.split(":");
|
|
2815
|
+
const entry = catalog.products.find((candidate) => candidate.product === product);
|
|
2816
|
+
if (!entry && RESERVED_PRODUCTS.includes(product)) {
|
|
2817
|
+
problems.push({ scope, code: "scope_not_available", reason: `Product "${product}" is reserved: its scopes are not issuable on service keys yet. Use a personal token (prudai login) for ${product} today.` });
|
|
2818
|
+
continue;
|
|
2819
|
+
}
|
|
2820
|
+
if (!entry) {
|
|
2821
|
+
problems.push({ scope, code: "scope_not_available", reason: `Unknown product "${product}". Products: ${catalog.products.map((p) => p.product).join(", ")}.` });
|
|
2822
|
+
continue;
|
|
2823
|
+
}
|
|
2824
|
+
if (entry.status === "reserved") {
|
|
2825
|
+
problems.push({ scope, code: "scope_not_available", reason: `Product "${product}" is reserved: its scopes are not issuable yet.` });
|
|
2826
|
+
continue;
|
|
2827
|
+
}
|
|
2828
|
+
if (object3 === "*") {
|
|
2829
|
+
const issuable = entry.objects.filter((o) => !o.explicit_only && o.scopes.some((s) => s.verb === verb && s.issuable));
|
|
2830
|
+
if (!issuable.length)
|
|
2831
|
+
problems.push({ scope, code: "scope_not_available", reason: `No ${verb} scope in ${product} is issuable yet, so ${scope} grants nothing.` });
|
|
2832
|
+
const excluded = entry.objects.filter((o) => o.explicit_only && o.scopes.some((s) => s.verb === verb)).map((o) => `${product}:${o.object}:${verb}`);
|
|
2833
|
+
if (excluded.length)
|
|
2834
|
+
warnings.push(`${scope} never covers explicit-only scopes; request them by name if needed: ${excluded.join(", ")}.`);
|
|
2835
|
+
if (verb !== "read")
|
|
2836
|
+
warnings.push(`${scope} grants ${verb} rights: every ${verb} call waits for human approval (HITL).`);
|
|
2837
|
+
continue;
|
|
2838
|
+
}
|
|
2839
|
+
const obj = entry.objects.find((candidate) => candidate.object === object3);
|
|
2840
|
+
if (!obj) {
|
|
2841
|
+
problems.push({ scope, code: "scope_not_available", reason: `Unknown object "${object3}" in ${product}. Objects: ${entry.objects.map((o) => o.object).join(", ")}.` });
|
|
2842
|
+
continue;
|
|
2843
|
+
}
|
|
2844
|
+
const offered = obj.scopes.find((candidate) => candidate.verb === verb);
|
|
2845
|
+
if (!offered) {
|
|
2846
|
+
problems.push({ scope, code: "scope_not_available", reason: `${product}:${object3} offers ${obj.scopes.map((s) => s.verb).join("/") || "no verbs"}, not ${verb}.` });
|
|
2847
|
+
continue;
|
|
2848
|
+
}
|
|
2849
|
+
if (!offered.issuable) {
|
|
2850
|
+
problems.push({ scope, code: "scope_not_available", reason: `${scope} exists but is not issuable yet ("nog niet beschikbaar").` });
|
|
2851
|
+
continue;
|
|
2852
|
+
}
|
|
2853
|
+
if (verb !== "read")
|
|
2854
|
+
warnings.push(`${scope}: every ${verb} call waits for human approval (HITL).`);
|
|
2855
|
+
if (obj.explicit_only)
|
|
2856
|
+
warnings.push(`${scope} is explicit-only (${obj.description.replace(/\.$/, "")}).`);
|
|
2857
|
+
}
|
|
2858
|
+
return { problems, warnings };
|
|
2859
|
+
}
|
|
2860
|
+
function checkAttenuation(parent, child, catalog) {
|
|
2861
|
+
const problems = [];
|
|
2862
|
+
if (parent.scopes) {
|
|
2863
|
+
if (!parent.scopes.includes(KEY_WRITE_SCOPE)) {
|
|
2864
|
+
problems.push({ scope: KEY_WRITE_SCOPE, code: "insufficient_scope", reason: `This key lacks ${KEY_WRITE_SCOPE} (explicit-only; never granted by account:*:write), so it cannot create keys.` });
|
|
2865
|
+
}
|
|
2866
|
+
for (const scope of child.scopes) {
|
|
2867
|
+
if (!covers(parent.scopes, scope, catalog)) {
|
|
2868
|
+
problems.push({ scope, code: "attenuation_violation", reason: scope.split(":")[1] === "*" ? `${scope} is broader than any set of concrete scopes; only a key that holds ${scope} itself can pass it on.` : `This key does not hold ${scope} (or a wildcard that covers it), and a key can only pass on a subset of its own rights.` });
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
}
|
|
2872
|
+
if (parent.expiresAt) {
|
|
2873
|
+
const limit = Date.parse(parent.expiresAt);
|
|
2874
|
+
const wanted = child.expiresAt ? Date.parse(child.expiresAt) : Infinity;
|
|
2875
|
+
if (Number.isFinite(limit) && !(wanted <= limit)) {
|
|
2876
|
+
problems.push({ scope: "", code: "attenuation_violation", reason: `The new key must expire no later than this key (${parent.expiresAt}); pass --expires-at ${parent.expiresAt} or earlier.` });
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
if (typeof parent.monthlyCreditCap === "number") {
|
|
2880
|
+
const wanted = typeof child.monthlyCreditCap === "number" ? child.monthlyCreditCap : Infinity;
|
|
2881
|
+
if (!(wanted <= parent.monthlyCreditCap)) {
|
|
2882
|
+
problems.push({ scope: "", code: "attenuation_violation", reason: `The new key's monthly credit limit must be at most this key's (${parent.monthlyCreditCap}); set one that is lower or equal.` });
|
|
2883
|
+
}
|
|
2884
|
+
}
|
|
2885
|
+
return problems;
|
|
2886
|
+
}
|
|
2887
|
+
function isScopeCatalog(value) {
|
|
2888
|
+
return !!value && typeof value === "object" && value.schema === 1 && Array.isArray(value.products);
|
|
2889
|
+
}
|
|
2890
|
+
|
|
2891
|
+
// src/platform.ts
|
|
2892
|
+
function knowledgeBaseSelection(raw, flag = "kb") {
|
|
2893
|
+
const value = raw.trim();
|
|
2894
|
+
if (value === "all" || value === "none")
|
|
2895
|
+
return value;
|
|
2896
|
+
const ids = [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))];
|
|
2897
|
+
if (!ids.length || ids.length > 50 || ids.some((id) => !/^kb_[A-Za-z0-9]{20}$/.test(id))) {
|
|
2898
|
+
throw new CliError(`--${flag} must be "all", "none" or 1 to 50 comma-separated knowledge base ids (kb_…). Nothing was sent.`, 2, "validation_error");
|
|
2899
|
+
}
|
|
2900
|
+
return ids;
|
|
2901
|
+
}
|
|
2902
|
+
function checkKnowledgeBaseField(value) {
|
|
2903
|
+
if (typeof value === "string") {
|
|
2904
|
+
if (value !== "all" && value !== "none")
|
|
2905
|
+
throw new CliError(`--data knowledge_bases must be exactly "all", "none" or an array of 1 to 50 knowledge base ids (kb_…). Nothing was sent.`, 2, "validation_error");
|
|
2906
|
+
return;
|
|
2907
|
+
}
|
|
2908
|
+
const ok = Array.isArray(value) && value.length >= 1 && value.length <= 50 && value.every((id) => typeof id === "string" && /^kb_[A-Za-z0-9]{20}$/.test(id));
|
|
2909
|
+
if (!ok)
|
|
2910
|
+
throw new CliError(`--data knowledge_bases must be "all", "none" or 1 to 50 knowledge base ids (kb_…). Nothing was sent.`, 2, "validation_error");
|
|
2911
|
+
}
|
|
2912
|
+
var KEY_BODY = [
|
|
2913
|
+
{ flag: "name", field: "name", kind: "string" },
|
|
2914
|
+
{ flag: "scopes", field: "scopes", kind: "csv" },
|
|
2915
|
+
{ flag: "bundles", field: "bundles", kind: "csv" },
|
|
2916
|
+
{ flag: "expires-at", field: "expires_at", kind: "string" },
|
|
2917
|
+
{ flag: "ip-allowlist", field: "ip_allowlist", kind: "csv" },
|
|
2918
|
+
{ flag: "monthly-cap-credits", field: "monthly_spend_cap_mcr", kind: "credits-mcr" }
|
|
2919
|
+
];
|
|
2920
|
+
var ORG = "/v1/organizations/{id}";
|
|
2921
|
+
var PROJECT = "/v1/projects/{project_id}";
|
|
2922
|
+
var IN_LEO = "A person can do this in LEO (https://app.prudai.com) today: open the project and its documents.";
|
|
2923
|
+
var OUT_FLAGS = [{ flag: "out", note: "file to write (mode 0600); bytes are never written to stdout" }, { flag: "force", note: "replace an existing --out file" }];
|
|
2924
|
+
var DELETED_FLAG = { flag: "trash", note: "list the trash (documents that were deleted and can be restored) instead of the live documents", query: "deleted" };
|
|
2925
|
+
var MEMO_PROJECT_FLAG = { flag: "project", note: "project id or exact name; default PRUDAI_MEMOS_PROJECT, else Transcribe" };
|
|
2926
|
+
var PLATFORM_OPS = [
|
|
2927
|
+
{ capability: "account.show", words: ["account", "show"], method: "GET", path: "/v1/account", operationIds: ["getAccount"], scope: "account:organizations:read", approval: "none", summary: "The calling principal, organisation and limits", status: "contract" },
|
|
2928
|
+
{ capability: "orgs.list", words: ["account", "orgs", "list"], method: "GET", path: "/v1/organizations", operationIds: ["listOrganizations"], scope: "account:organizations:read", approval: "none", summary: "Organisations you can act for", status: "planned", consoleToday: true },
|
|
2929
|
+
{ capability: "orgs.create", words: ["account", "orgs", "create"], method: "POST", path: "/v1/organizations", operationIds: ["createOrganization"], scope: "account:organizations:write", approval: "confirm", summary: "Create an organisation and start its trial (idempotent on Idempotency-Key and on KvK + admin mail domain)", status: "planned", body: [{ flag: "name", field: "name", kind: "string" }, { flag: "kvk", field: "kvk", kind: "string" }, { flag: "admin-email", field: "admin_email", kind: "string" }] },
|
|
2930
|
+
{ capability: "orgs.update", words: ["account", "orgs", "update"], method: "PATCH", path: ORG, operationIds: ["updateOrganization"], scope: "account:organizations:write", approval: "confirm", summary: "Change the organisation", status: "planned", consoleToday: true, orgScoped: true, body: [{ flag: "name", field: "name", kind: "string" }] },
|
|
2931
|
+
{ capability: "orgs.delete", words: ["account", "orgs", "delete"], method: "DELETE", path: ORG, operationIds: ["deleteOrganization"], scope: "account:organizations:delete", approval: "forbidden_for_agents", summary: "Delete the organisation: only a person, in the account dashboard", status: "planned", consoleToday: true, orgScoped: true },
|
|
2932
|
+
{ capability: "orgs.products", words: ["account", "products", "list"], method: "GET", path: `${ORG}/product-access`, operationIds: ["getProductAccess"], scope: "account:organizations:read", approval: "none", summary: "Product access of the organisation", status: "planned", consoleToday: true, orgScoped: true },
|
|
2933
|
+
{ capability: "orgs.products.update", words: ["account", "products", "update"], method: "PATCH", path: `${ORG}/product-access`, operationIds: ["updateProductAccess"], scope: "account:organizations:write", approval: "confirm", summary: "Change product access (within the subscription)", status: "planned", consoleToday: true, orgScoped: true },
|
|
2934
|
+
{ capability: "members.list", words: ["account", "members", "list"], method: "GET", path: `${ORG}/members`, operationIds: ["listMembers"], scope: "account:members:read", approval: "none", summary: "Members of the organisation", status: "planned", consoleToday: true, orgScoped: true },
|
|
2935
|
+
{ capability: "members.invite", words: ["account", "members", "invite"], method: "POST", path: `${ORG}/members`, operationIds: ["inviteMember", "createMember"], scope: "account:members:write", approval: "confirm", summary: "Invite a member (an extra seat goes through the subscription: a person approves)", status: "planned", consoleToday: true, orgScoped: true, body: [{ flag: "email", field: "email", kind: "string" }, { flag: "role", field: "role", kind: "string" }] },
|
|
2936
|
+
{ capability: "members.update", words: ["account", "members", "update"], method: "PATCH", path: `${ORG}/members/{userId}`, operationIds: ["updateMember"], scope: "account:members:write", approval: "confirm", summary: "Change a member's role", status: "planned", consoleToday: true, orgScoped: true, positionals: ["userId"], body: [{ flag: "role", field: "role", kind: "string" }] },
|
|
2937
|
+
{ capability: "members.remove", words: ["account", "members", "remove"], method: "DELETE", path: `${ORG}/members/{userId}`, operationIds: ["removeMember", "deleteMember"], scope: "account:members:delete", approval: "review", summary: "Remove a member", status: "planned", consoleToday: true, orgScoped: true, positionals: ["userId"] },
|
|
2938
|
+
{ capability: "subscription.show", words: ["account", "subscription", "show"], method: "GET", path: `${ORG}/subscription`, operationIds: ["getSubscription"], scope: "account:subscriptions:read", approval: "none", summary: "Subscription and seats", status: "planned", consoleToday: true, orgScoped: true },
|
|
2939
|
+
{ capability: "subscription.change", words: ["account", "subscription", "change"], method: "PUT", path: `${ORG}/subscription`, operationIds: ["updateSubscription", "replaceSubscription"], scope: "account:subscriptions:write", approval: "confirm", summary: "Change the plan: returns a payment link; a person approves and pays, never the agent", status: "planned", consoleToday: true, orgScoped: true, costsMoney: true, body: [{ flag: "plan", field: "plan", kind: "string" }] },
|
|
2940
|
+
{ capability: "seats.change", words: ["account", "seats", "change"], method: "PUT", path: `${ORG}/subscription`, operationIds: ["updateSubscription", "replaceSubscription"], scope: "account:subscriptions:write", approval: "confirm", summary: "Change the number of seats: a person approves and pays", status: "planned", consoleToday: true, orgScoped: true, costsMoney: true, body: [{ flag: "seats", field: "seats", kind: "number" }] },
|
|
2941
|
+
{ capability: "billing.show", words: ["account", "billing", "show"], method: "GET", path: `${ORG}/billing`, operationIds: ["getBillingDetails"], scope: "account:subscriptions:read", approval: "none", summary: "Billing details (invoice address, VAT number, invoice e-mail)", status: "proposed", consoleToday: true, orgScoped: true },
|
|
2942
|
+
{ capability: "billing.update", words: ["account", "billing", "update"], method: "PATCH", path: `${ORG}/billing`, operationIds: ["updateBillingDetails"], scope: "account:subscriptions:write", approval: "confirm", summary: "Change billing details", status: "proposed", consoleToday: true, orgScoped: true },
|
|
2943
|
+
{ capability: "settings.agent-keys", words: ["settings", "agent-keys"], method: "PATCH", path: `${ORG}/settings/agent-keys`, operationIds: ["updateAgentKeySettings"], scope: "account:organizations:write", approval: "forbidden_for_agents", summary: "Allow agents to create keys (and the approval level for it): only a person", status: "planned", orgScoped: true },
|
|
2944
|
+
{ capability: "keys.list", words: ["keys", "list"], method: "GET", path: "/v1/api-keys", operationIds: ["listApiKeys"], scope: "account:api_keys:read", approval: "none", summary: "Service keys of the organisation (never the secret)", status: "contract" },
|
|
2945
|
+
{ capability: "keys.get", words: ["keys", "get"], method: "GET", path: "/v1/api-keys/{id}", operationIds: ["getApiKey", "retrieveApiKey"], scope: "account:api_keys:read", approval: "none", summary: "One service key", status: "planned", positionals: ["id"] },
|
|
2946
|
+
{ capability: "keys.create", words: ["keys", "create"], method: "POST", path: "/v1/api-keys", operationIds: ["createApiKey"], scope: "account:api_keys:write", approval: "confirm", summary: "Create a service key (the secret is shown once)", status: "contract", body: KEY_BODY, check: "scopes" },
|
|
2947
|
+
{ capability: "keys.update", words: ["keys", "update"], method: "PATCH", path: "/v1/api-keys/{id}", operationIds: ["updateApiKey"], scope: "account:api_keys:write", approval: "confirm", summary: "Change name, scopes, expiry, allowlist or monthly limit", status: "planned", positionals: ["id"], body: KEY_BODY.filter((entry) => entry.flag !== "bundles"), check: "scopes" },
|
|
2948
|
+
{ capability: "keys.rotate", words: ["keys", "rotate"], method: "POST", path: "/v1/api-keys/{id}/rotate", operationIds: ["rotateApiKey"], scope: "account:api_keys:write", approval: "confirm", summary: "Rotate: new secret once, same rights", status: "contract", positionals: ["id"], body: [{ flag: "grace-seconds", field: "grace_seconds", kind: "number" }, { flag: "expires-at", field: "expires_at", kind: "string" }] },
|
|
2949
|
+
{ capability: "keys.revoke", words: ["keys", "revoke"], method: "POST", path: "/v1/api-keys/{id}/revoke", operationIds: ["revokeApiKey"], scope: "account:api_keys:delete", approval: "review", summary: "Revoke a key and every key it created", status: "contract", positionals: ["id"], body: [{ flag: "reason", field: "reason", kind: "string" }] },
|
|
2950
|
+
{ capability: "tokens.list", words: ["tokens", "list"], method: "GET", path: "/v1/personal-tokens", operationIds: ["listPersonalTokens"], scope: "account:personal_tokens:read", approval: "none", summary: "Your personal tokens (device logins)", status: "proposed" },
|
|
2951
|
+
{ capability: "tokens.revoke", words: ["tokens", "revoke"], method: "POST", path: "/v1/personal-tokens/{id}/revoke", operationIds: ["revokePersonalToken"], scope: "account:personal_tokens:delete", approval: "review", summary: "Revoke a personal token", status: "proposed", positionals: ["id"] },
|
|
2952
|
+
{ capability: "apps.list", words: ["apps", "list"], method: "GET", path: "/v1/apps", operationIds: ["listApps"], scope: "account:apps:read", approval: "none", summary: "OAuth apps", status: "proposed" },
|
|
2953
|
+
{ capability: "apps.create", words: ["apps", "create"], method: "POST", path: "/v1/apps", operationIds: ["createApp"], scope: "account:apps:write", approval: "confirm", summary: "Register an OAuth app (PKCE, https only)", status: "proposed", body: [{ flag: "name", field: "name", kind: "string" }, { flag: "redirect-uris", field: "redirect_uris", kind: "csv" }] },
|
|
2954
|
+
{ capability: "apps.rotate-secret", words: ["apps", "rotate-secret"], method: "POST", path: "/v1/apps/{id}/rotate-secret", operationIds: ["rotateAppSecret"], scope: "account:apps:write", approval: "confirm", summary: "New client secret (shown once)", status: "proposed", positionals: ["id"] },
|
|
2955
|
+
{ capability: "apps.delete", words: ["apps", "delete"], method: "DELETE", path: "/v1/apps/{id}", operationIds: ["deleteApp"], scope: "account:apps:delete", approval: "review", summary: "Remove an OAuth app", status: "proposed", positionals: ["id"] },
|
|
2956
|
+
{ capability: "mcp.connections", words: ["mcp", "connections", "list"], method: "GET", path: "/v1/mcp/connections", operationIds: ["listMcpConnections"], scope: "account:mcp_connections:read", approval: "none", summary: "Assistants connected through the MCP gateway", status: "proposed" },
|
|
2957
|
+
{ capability: "mcp.disconnect", words: ["mcp", "connections", "remove"], method: "DELETE", path: "/v1/mcp/connections/{id}", operationIds: ["deleteMcpConnection"], scope: "account:mcp_connections:delete", approval: "review", summary: "Disconnect an assistant", status: "proposed", positionals: ["id"] },
|
|
2958
|
+
{ capability: "credits.balance", words: ["credits", "balance"], method: "GET", path: "/v1/credits/balance", altPaths: ["/v1/credits"], operationIds: ["getCreditBalance", "getCredits"], scope: "account:credits:read", approval: "none", summary: "Credit balance, reservations, spend and monthly cap", status: "contract" },
|
|
2959
|
+
{ capability: "credits.ledger", words: ["credits", "ledger"], method: "GET", path: "/v1/credits/ledger", operationIds: ["listCreditLedger"], scope: "account:credits:read", approval: "none", summary: "Credit ledger", status: "contract", query: ["limit", "after", "type", "start", "end"] },
|
|
2960
|
+
{ capability: "credits.topup", words: ["credits", "topup"], method: "POST", path: "/v1/credits/topups", operationIds: ["createCreditTopup", "createCreditTopUp"], scope: "account:credits:write", approval: "confirm", summary: "Propose a top-up: returns a payment link; a person approves and pays", status: "planned", costsMoney: true, body: [{ flag: "credits", field: "credits", kind: "number" }] },
|
|
2961
|
+
{ capability: "usage", words: ["usage"], method: "GET", path: "/v1/usage", operationIds: ["getUsage"], scope: "account:usage:read", approval: "none", summary: "Usage per day, model, operation or source (counts and credits, never content)", status: "contract", positionals: ["start_date"], query: ["start_date", "end_date", "group_by", "key_id", "model", "operation", "source_id"] },
|
|
2962
|
+
{ capability: "usage.insights", words: ["usage", "insights"], method: "GET", path: "/v1/usage/insights", operationIds: ["getUsageInsights"], scope: "account:usage:read", approval: "none", summary: "Usage per day and product (console overview)", status: "planned", query: ["range"] },
|
|
2963
|
+
{ capability: "logs", words: ["logs"], method: "GET", path: "/v1/logs", operationIds: ["listRequestLogs", "listLogs"], scope: "account:usage:read", approval: "none", summary: "Request log: method, path, status, duration, cost, approval — never content", status: "planned", query: ["limit", "after", "key_id"] },
|
|
2964
|
+
{ capability: "invoices.list", words: ["invoices", "list"], method: "GET", path: "/v1/invoices", operationIds: ["listInvoices"], scope: "account:invoices:read", approval: "none", summary: "One invoice list (subscriptions and custom work), with source label", status: "planned", consoleToday: true, query: ["source"] },
|
|
2965
|
+
{ capability: "invoices.download", words: ["invoices", "download"], method: "GET", path: "/v1/invoices/{id}/pdf", operationIds: ["downloadInvoice"], scope: "account:invoices:read", approval: "none", summary: "Download an invoice PDF", status: "proposed", consoleToday: true, positionals: ["id"] },
|
|
2966
|
+
{ capability: "kb.list", words: ["kb", "list"], method: "GET", path: "/v1/knowledge-bases", operationIds: ["listKnowledgeBases"], scope: "prudai:knowledge_bases:read", approval: "none", summary: "Knowledge bases of the organisation", status: "planned", query: ["q", "include_deleted", "limit", "cursor"] },
|
|
2967
|
+
{ capability: "kb.create", words: ["kb", "create"], method: "POST", path: "/v1/knowledge-bases", operationIds: ["createKnowledgeBase"], scope: "prudai:knowledge_bases:write", approval: "confirm", summary: "Create a knowledge base (Idempotency-Key; a person approves)", status: "planned", body: [{ flag: "name", field: "name", kind: "string" }, { flag: "description", field: "description", kind: "string" }] },
|
|
2968
|
+
{ capability: "kb.get", words: ["kb", "get"], method: "GET", path: "/v1/knowledge-bases/{kb_id}", operationIds: ["getKnowledgeBase"], scope: "prudai:knowledge_bases:read", approval: "none", summary: "One knowledge base", status: "planned", positionals: ["kb_id"], query: ["include_deleted"] },
|
|
2969
|
+
{ capability: "kb.update", words: ["kb", "update"], method: "PATCH", path: "/v1/knowledge-bases/{kb_id}", operationIds: ["updateKnowledgeBase"], scope: "prudai:knowledge_bases:write", approval: "confirm", summary: "Rename or describe a knowledge base (If-Match: version)", status: "planned", positionals: ["kb_id"], body: [{ flag: "name", field: "name", kind: "string" }, { flag: "description", field: "description", kind: "string" }] },
|
|
2970
|
+
{ capability: "kb.delete", words: ["kb", "delete"], method: "DELETE", path: "/v1/knowledge-bases/{kb_id}", operationIds: ["deleteKnowledgeBase"], scope: "prudai:knowledge_bases:delete", approval: "review", summary: "Soft-delete a knowledge base (restorable)", status: "planned", positionals: ["kb_id"] },
|
|
2971
|
+
{ capability: "kb.restore", words: ["kb", "restore"], method: "POST", path: "/v1/knowledge-bases/{kb_id}/restore", operationIds: ["restoreKnowledgeBase"], scope: "prudai:knowledge_bases:write", approval: "confirm", summary: "Restore a soft-deleted knowledge base", status: "planned", positionals: ["kb_id"] },
|
|
2972
|
+
{ capability: "kb.docs", words: ["kb", "docs"], method: "GET", path: "/v1/knowledge-bases/{kb_id}/documents", operationIds: ["listKnowledgeBaseDocuments"], scope: "prudai:knowledge_bases:read", approval: "none", summary: "Documents with their processing status", status: "planned", positionals: ["kb_id"], query: ["status", "include_deleted", "limit", "cursor"] },
|
|
2973
|
+
{ capability: "kb.doc", words: ["kb", "doc"], method: "GET", path: "/v1/knowledge-bases/{kb_id}/documents/{document_id}", operationIds: ["getKnowledgeBaseDocument"], scope: "prudai:knowledge_bases:read", approval: "none", summary: "One document and its processing status", status: "planned", positionals: ["kb_id", "document_id"] },
|
|
2974
|
+
{ capability: "kb.upload", words: ["kb", "upload"], method: "POST", path: "/v1/knowledge-bases/{kb_id}/documents", operationIds: ["uploadKnowledgeBaseDocument"], scope: "prudai:knowledge_bases:write", approval: "confirm", summary: "Upload a document (multipart, max 25 MB; the file is <file> or --file; a person approves)", status: "planned", positionals: ["kb_id", "file"], body: [{ flag: "file", field: "file", kind: "file" }] },
|
|
2975
|
+
{ capability: "kb.doc.delete", words: ["kb", "doc", "delete"], method: "DELETE", path: "/v1/knowledge-bases/{kb_id}/documents/{document_id}", operationIds: ["deleteKnowledgeBaseDocument"], scope: "prudai:knowledge_bases:delete", approval: "review", summary: "Soft-delete a document (restorable)", status: "planned", positionals: ["kb_id", "document_id"] },
|
|
2976
|
+
{ capability: "kb.doc.restore", words: ["kb", "doc", "restore"], method: "POST", path: "/v1/knowledge-bases/{kb_id}/documents/{document_id}/restore", operationIds: ["restoreKnowledgeBaseDocument"], scope: "prudai:knowledge_bases:write", approval: "confirm", summary: "Restore a soft-deleted document", status: "planned", positionals: ["kb_id", "document_id"] },
|
|
2977
|
+
{ capability: "kb.query", words: ["kb", "query"], method: "POST", path: "/v1/knowledge-bases/{kb_id}/query", operationIds: ["queryKnowledgeBase"], scope: "prudai:knowledge_bases:read", approval: "none", summary: "Ask a question: the most relevant passages with their document as citation", readsViaPost: true, withoutPositionalsUse: "kb.search", status: "planned", positionals: ["kb_id"], body: [{ flag: "question", field: "question", kind: "string" }, { flag: "top-k", field: "top_k", kind: "number" }] },
|
|
2978
|
+
{ capability: "kb.search", words: ["kb", "search"], method: "POST", path: "/v1/knowledge-bases/query", operationIds: ["queryKnowledgeBases"], scope: "prudai:knowledge_bases:read", approval: "none", summary: "Ask a question over several knowledge bases: --kb <id>[,<id>…]|all|none (also --knowledge-bases) chooses which, default all. `prudai kb query` without an id does the same", readsViaPost: true, status: "planned", body: [{ flag: "question", field: "question", kind: "string" }, { flag: "top-k", field: "top_k", kind: "number" }, { flag: "kb", field: "knowledge_bases", kind: "kb-selection", aliases: ["knowledge-bases"] }] },
|
|
2979
|
+
{ capability: "kb.answer", words: ["kb", "answer"], method: "POST", path: "/v1/knowledge-bases/{kb_id}/answer", operationIds: ["answerFromKnowledgeBase"], scope: "prudai:knowledge_base_answers:read", approval: "none", summary: "A short answer with citations (spends credits)", status: "planned", positionals: ["kb_id"], body: [{ flag: "question", field: "question", kind: "string" }] },
|
|
2980
|
+
{ capability: "projects.list", words: ["projects", "list"], method: "GET", path: "/v1/projects", operationIds: ["listProjects"], scope: "prudai:projects:read", approval: "none", summary: "Your projects (dossiers); --q finds by name", status: "planned", today: IN_LEO, query: ["q", "limit", "cursor"], flags: [{ flag: "include-archived", note: "also archived projects", query: "include_archived" }] },
|
|
2981
|
+
{ capability: "projects.get", words: ["projects", "get"], method: "GET", path: PROJECT, operationIds: ["getProject"], scope: "prudai:projects:read", approval: "none", summary: "One project: <project> is its id or its exact name", status: "planned", today: IN_LEO, positionals: ["project"], project: "arg" },
|
|
2982
|
+
{ capability: "projects.docs", words: ["projects", "docs"], method: "GET", path: `${PROJECT}/documents`, operationIds: ["listProjectDocuments"], scope: "prudai:projects:read", approval: "none", summary: "Documents of a project with their processing status; --trash lists the trash", status: "planned", today: IN_LEO, positionals: ["project"], project: "arg", query: ["status", "q", "limit", "cursor"], flags: [DELETED_FLAG] },
|
|
2983
|
+
{ capability: "projects.doc", words: ["projects", "doc"], method: "GET", path: `${PROJECT}/documents/{document_id}`, operationIds: ["getProjectDocument"], scope: "prudai:projects:read", approval: "none", summary: "One document: kind, status, who uploaded it, subtitles, language", status: "planned", today: IN_LEO, positionals: ["project", "document_id"], project: "arg" },
|
|
2984
|
+
{ capability: "projects.doc.text", words: ["projects", "doc", "text"], method: "GET", path: `${PROJECT}/documents/{document_id}/text`, operationIds: ["getProjectDocumentText"], scope: "prudai:projects:read", approval: "none", summary: "The text of a document (the transcript of a recording) as plain text; --out writes it to a file", status: "planned", today: IN_LEO, positionals: ["project", "document_id"], project: "arg", output: "text", flags: OUT_FLAGS },
|
|
2985
|
+
{ capability: "projects.doc.original", words: ["projects", "doc", "original"], method: "GET", path: `${PROJECT}/documents/{document_id}/original`, operationIds: ["downloadProjectDocumentOriginal"], scope: "prudai:projects:read", approval: "none", summary: "Download the original file to --out (never to stdout)", status: "planned", today: IN_LEO, positionals: ["project", "document_id"], project: "arg", output: "bytes", flags: OUT_FLAGS },
|
|
2986
|
+
{ capability: "projects.upload", words: ["projects", "upload"], method: "POST", path: `${PROJECT}/documents`, operationIds: ["uploadProjectDocument"], scope: "prudai:projects:write", approval: "confirm", summary: "Upload one file to a project (multipart; the file is <file> or --file; a person approves)", status: "planned", today: IN_LEO, positionals: ["project", "file"], project: "arg", body: [{ flag: "file", field: "file", kind: "file" }] },
|
|
2987
|
+
{ capability: "projects.doc.delete", words: ["projects", "doc", "delete"], method: "DELETE", path: `${PROJECT}/documents/{document_id}`, operationIds: ["deleteProjectDocument"], scope: "prudai:projects:delete", approval: "review", summary: "Move a document to the trash (soft delete: it can be restored); a person reviews", status: "planned", today: IN_LEO, positionals: ["project", "document_id"], project: "arg", after: { action: "prudai projects doc restore <project> <document_id>", why: "bring it back from the trash" } },
|
|
2988
|
+
{ capability: "projects.doc.restore", words: ["projects", "doc", "restore"], method: "POST", path: `${PROJECT}/documents/{document_id}/restore`, operationIds: ["restoreProjectDocument"], scope: "prudai:projects:write", approval: "confirm", summary: "Restore a document from the trash (it is processed again); a person approves", status: "planned", today: IN_LEO, positionals: ["project", "document_id"], project: "arg", queued: true },
|
|
2989
|
+
{ capability: "projects.doc.purge", words: ["projects", "doc", "purge"], method: "POST", path: `${PROJECT}/documents/{document_id}/purge`, operationIds: ["purgeProjectDocument"], scope: "prudai:projects:delete", approval: "review", summary: "Remove a document from the trash for good: irreversible, a person reviews", status: "planned", today: IN_LEO, positionals: ["project", "document_id"], project: "arg", irreversible: true },
|
|
2990
|
+
{ capability: "memos.list", words: ["memos", "list"], method: "GET", path: `${PROJECT}/documents`, operationIds: ["listProjectDocuments"], scope: "prudai:projects:read", approval: "none", summary: "Recordings and transcripts of the project (the CLI filters on kind); --status, --limit; --trash lists the trash", status: "planned", today: IN_LEO, project: "memo", custom: "memos-list", query: ["status", "limit"], flags: [MEMO_PROJECT_FLAG, DELETED_FLAG] },
|
|
2991
|
+
{ capability: "memos.get", words: ["memos", "get"], method: "GET", path: `${PROJECT}/documents/{document_id}`, operationIds: ["getProjectDocument"], scope: "prudai:projects:read", approval: "none", summary: "One memo: kind, status, who recorded it, subtitles, language", status: "planned", today: IN_LEO, positionals: ["document_id"], project: "memo", flags: [MEMO_PROJECT_FLAG] },
|
|
2992
|
+
{ capability: "memos.transcript", words: ["memos", "transcript"], method: "GET", path: `${PROJECT}/documents/{document_id}/text`, operationIds: ["getProjectDocumentText"], scope: "prudai:projects:read", approval: "none", summary: "The transcript of a memo as plain text; --out writes it to a file", status: "planned", today: IN_LEO, positionals: ["document_id"], project: "memo", output: "text", flags: [MEMO_PROJECT_FLAG, ...OUT_FLAGS] },
|
|
2993
|
+
{ capability: "memos.download", words: ["memos", "download"], method: "GET", path: `${PROJECT}/documents/{document_id}/original`, operationIds: ["downloadProjectDocumentOriginal"], scope: "prudai:projects:read", approval: "none", summary: "Download the original recording or transcript to --out (never to stdout)", status: "planned", today: IN_LEO, positionals: ["document_id"], project: "memo", output: "bytes", flags: [MEMO_PROJECT_FLAG, ...OUT_FLAGS] },
|
|
2994
|
+
{ capability: "memos.upload", words: ["memos", "upload"], method: "POST", path: `${PROJECT}/documents`, operationIds: ["uploadProjectDocument"], scope: "prudai:projects:write", approval: "confirm", summary: "Upload a recording (.m4a .webm .mp3 .wav …) or a transcript (.vtt .srt) (multipart; the file is <file> or --file; a person approves)", status: "planned", today: IN_LEO, positionals: ["file"], project: "memo", body: [{ flag: "file", field: "file", kind: "file" }], flags: [MEMO_PROJECT_FLAG] },
|
|
2995
|
+
{ capability: "memos.delete", words: ["memos", "delete"], method: "DELETE", path: `${PROJECT}/documents/{document_id}`, operationIds: ["deleteProjectDocument"], scope: "prudai:projects:delete", approval: "review", summary: "Move a memo to the trash (soft delete: it can be restored); a person reviews", status: "planned", today: IN_LEO, positionals: ["document_id"], project: "memo", after: { action: "prudai memos restore <document_id>", why: "bring it back from the trash" }, flags: [MEMO_PROJECT_FLAG] },
|
|
2996
|
+
{ capability: "memos.restore", words: ["memos", "restore"], method: "POST", path: `${PROJECT}/documents/{document_id}/restore`, operationIds: ["restoreProjectDocument"], scope: "prudai:projects:write", approval: "confirm", summary: "Restore a memo from the trash (it is processed again); a person approves", status: "planned", today: IN_LEO, positionals: ["document_id"], project: "memo", queued: true, flags: [MEMO_PROJECT_FLAG] },
|
|
2997
|
+
{ capability: "memos.purge", words: ["memos", "purge"], method: "POST", path: `${PROJECT}/documents/{document_id}/purge`, operationIds: ["purgeProjectDocument"], scope: "prudai:projects:delete", approval: "review", summary: "Remove a memo from the trash for good: irreversible, a person reviews", status: "planned", today: IN_LEO, positionals: ["document_id"], project: "memo", irreversible: true, flags: [MEMO_PROJECT_FLAG] }
|
|
2998
|
+
];
|
|
2999
|
+
var PLATFORM_GROUPS = new Set(["account", "keys", "tokens", "apps", "credits", "usage", "logs", "invoices", "settings", "kb", "projects", "dossiers", "memos"]);
|
|
3000
|
+
var DEFAULT_ACTION = { credits: "balance", account: "show", projects: "list", memos: "list" };
|
|
3001
|
+
var GROUP_ALIASES = { dossiers: "projects" };
|
|
3002
|
+
var dealias = (words) => words[0] !== undefined && GROUP_ALIASES[words[0]] ? [GROUP_ALIASES[words[0]], ...words.slice(1)] : words;
|
|
3003
|
+
function match(rawWords) {
|
|
3004
|
+
const words = dealias(rawWords);
|
|
3005
|
+
const expanded = words.length === 1 && DEFAULT_ACTION[words[0]] ? [words[0], DEFAULT_ACTION[words[0]]] : words;
|
|
3006
|
+
let best;
|
|
3007
|
+
for (const op of PLATFORM_OPS) {
|
|
3008
|
+
if (expanded.slice(0, op.words.length).join(" ") === op.words.join(" ") && (!best || op.words.length > best.op.words.length)) {
|
|
3009
|
+
best = { op, positionals: expanded.slice(op.words.length) };
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
return best;
|
|
3013
|
+
}
|
|
3014
|
+
function bindOperation(op, catalog) {
|
|
3015
|
+
const found = catalog.commands.find((command) => op.operationIds.includes(command.operationId)) ?? catalog.commands.find((command) => command.method === op.method && [op.path, ...op.altPaths ?? []].some((path) => command.path === path || templateMatches(command.path, path.replace(/\{[^}]+\}/g, "x"))));
|
|
3016
|
+
if (!found || !op.readsViaPost)
|
|
3017
|
+
return found;
|
|
3018
|
+
const samePath = [op.path, ...op.altPaths ?? []].some((path) => found.path === path || templateMatches(found.path, path.replace(/\{[^}]+\}/g, "x")));
|
|
3019
|
+
if (found.method.toUpperCase() !== op.method || found.approval !== "none" || !samePath)
|
|
3020
|
+
return;
|
|
3021
|
+
return { ...found, readsViaPost: true, idempotencyKey: false, idempotencyDeclared: false, dryRun: false };
|
|
3022
|
+
}
|
|
3023
|
+
function platformCatalog(platform) {
|
|
3024
|
+
const commands = PLATFORM_OPS.map((op) => {
|
|
3025
|
+
const bound = bindOperation(op, platform);
|
|
3026
|
+
const base = { commandLine: `prudai ${op.words.join(" ")}`, product: "platform", name: op.words.join(" "), words: op.words, resource: op.words[0], action: op.words.slice(1).join(" ") };
|
|
3027
|
+
const scopes = [op.scope];
|
|
3028
|
+
const cost = op.costsMoney ? "costs money (a person approves and pays)" : undefined;
|
|
3029
|
+
if (bound) {
|
|
3030
|
+
return {
|
|
3031
|
+
...bound,
|
|
3032
|
+
...base,
|
|
3033
|
+
positionals: op.project ? op.positionals ?? [] : bound.positionals.filter((name) => !(op.orgScoped && name === "id")),
|
|
3034
|
+
scopes: bound.scopes?.length ? bound.scopes : scopes,
|
|
3035
|
+
...cost ? { cost } : {},
|
|
3036
|
+
status: bound.status ?? op.status,
|
|
3037
|
+
available: true
|
|
3038
|
+
};
|
|
3039
|
+
}
|
|
3040
|
+
return {
|
|
3041
|
+
...base,
|
|
3042
|
+
kind: "action",
|
|
3043
|
+
method: op.method,
|
|
3044
|
+
path: op.path,
|
|
3045
|
+
operationId: op.operationIds[0],
|
|
3046
|
+
summary: op.summary,
|
|
3047
|
+
approval: op.approval,
|
|
3048
|
+
parameters: [],
|
|
3049
|
+
positionals: op.positionals ?? [],
|
|
3050
|
+
idempotencyKey: op.method !== "GET" && !op.readsViaPost,
|
|
3051
|
+
idempotencyDeclared: false,
|
|
3052
|
+
dryRun: false,
|
|
3053
|
+
scopes,
|
|
3054
|
+
...cost ? { cost } : {},
|
|
3055
|
+
status: `${op.status}; not available yet${op.consoleToday ? " (account dashboard today)" : ""}`,
|
|
3056
|
+
available: false
|
|
3057
|
+
};
|
|
3058
|
+
});
|
|
3059
|
+
return { product: "platform", title: "Account and developer platform", origin: platform.origin, commands, warnings: [], scopeProducts: ["account"], ...platform.source ? { source: platform.source } : {} };
|
|
3060
|
+
}
|
|
3061
|
+
function coveredByPlatform(platform) {
|
|
3062
|
+
return new Set(PLATFORM_OPS.map((op) => bindOperation(op, platform)?.operationId).filter((id) => !!id));
|
|
3063
|
+
}
|
|
3064
|
+
function matchPlatform(words) {
|
|
3065
|
+
return match(words);
|
|
3066
|
+
}
|
|
3067
|
+
function notAvailable(op, extra = {}, typedAs) {
|
|
3068
|
+
const status = op.status === "contract" ? "in the platform contract, not in the spec this CLI could load" : op.status === "planned" ? "decided, not built yet" : "proposed, not built yet";
|
|
3069
|
+
return new NotAvailableError(`prudai ${typedAs ?? op.words.join(" ")} is not available yet: the platform API does not serve ${op.method} ${op.path} (${status}). ${op.method} ${op.path} was not sent.`, {
|
|
3070
|
+
planned: `${op.method} ${op.path}`,
|
|
3071
|
+
scope: op.scope,
|
|
3072
|
+
approval: op.approval,
|
|
3073
|
+
status: op.status,
|
|
3074
|
+
...op.costsMoney ? { costsMoney: true } : {},
|
|
3075
|
+
next: [
|
|
3076
|
+
op.today ?? (op.consoleToday ? `A person can do this in the account dashboard (${CONSOLE_URL}) today.` : "Not available anywhere yet: it arrives in the Prudai Console and this CLI together."),
|
|
3077
|
+
"The command starts working without a CLI release once the platform spec (/v1/openapi.json) lists the operation."
|
|
3078
|
+
],
|
|
3079
|
+
...extra
|
|
3080
|
+
});
|
|
3081
|
+
}
|
|
3082
|
+
function bodyFromFlags(op, ctx) {
|
|
3083
|
+
const body = {};
|
|
3084
|
+
for (const entry of op.body ?? []) {
|
|
3085
|
+
const spellings = [entry.flag, ...entry.aliases ?? []].filter((name) => str(ctx.flags, name) !== undefined);
|
|
3086
|
+
if (spellings.length > 1)
|
|
3087
|
+
throw new CliError(`Use either ${spellings.map((name) => `--${name}`).join(" or ")}, not both.`, 2, "validation_error");
|
|
3088
|
+
const raw = spellings[0] === undefined ? undefined : str(ctx.flags, spellings[0]);
|
|
3089
|
+
if (raw === undefined || entry.kind === "file")
|
|
3090
|
+
continue;
|
|
3091
|
+
if (entry.kind === "kb-selection")
|
|
3092
|
+
body[entry.field] = knowledgeBaseSelection(raw, entry.flag);
|
|
3093
|
+
else if (entry.kind === "csv")
|
|
3094
|
+
body[entry.field] = raw.split(",").map((value) => value.trim()).filter(Boolean);
|
|
3095
|
+
else if (entry.kind === "number" || entry.kind === "credits-mcr") {
|
|
3096
|
+
const value = Number(raw);
|
|
3097
|
+
if (!Number.isFinite(value) || value < 0)
|
|
3098
|
+
throw new CliError(`--${entry.flag} must be a non-negative number.`);
|
|
3099
|
+
body[entry.field] = entry.kind === "credits-mcr" ? Math.round(value * 1000) : value;
|
|
3100
|
+
} else
|
|
3101
|
+
body[entry.field] = raw;
|
|
3102
|
+
}
|
|
3103
|
+
return Object.keys(body).length ? body : undefined;
|
|
3104
|
+
}
|
|
3105
|
+
async function scopeCatalog(ctx, platform) {
|
|
3106
|
+
const live = platform.commands.find((command) => command.method === "GET" && command.path === "/v1/scopes");
|
|
3107
|
+
const token = await credentialFor(PLATFORM_PRODUCT, ctx);
|
|
3108
|
+
if (live && token) {
|
|
3109
|
+
const origin = resolveOrigin(PLATFORM_PRODUCT, ctx);
|
|
3110
|
+
if (origin) {
|
|
3111
|
+
try {
|
|
3112
|
+
const url = `${safeApiOrigin(origin)}/v1/scopes`;
|
|
3113
|
+
requireTrustedOrigin(url, ctx.env);
|
|
3114
|
+
const response = await requestJson(ctx.fetch, url, { token, env: ctx.env });
|
|
3115
|
+
const body = response.status === 200 && isRecord(response.body) ? response.body : undefined;
|
|
3116
|
+
const data = body && isRecord(body.data) ? body.data : body;
|
|
3117
|
+
const candidate = data && isRecord(data.catalog) ? data.catalog : data;
|
|
3118
|
+
if (isScopeCatalog(candidate))
|
|
3119
|
+
return { catalog: candidate, source: url, ...data && isRecord(data.bundles) ? { bundles: data.bundles } : {} };
|
|
3120
|
+
} catch {}
|
|
3121
|
+
}
|
|
3122
|
+
}
|
|
3123
|
+
const bundles = platform.spec && isRecord(platform.spec["x-prudai-scope-bundles"]) ? platform.spec["x-prudai-scope-bundles"] : undefined;
|
|
3124
|
+
return { source: "none", ...bundles ? { bundles } : {} };
|
|
3125
|
+
}
|
|
3126
|
+
async function parentGrant(_ctx) {
|
|
3127
|
+
return { grant: {}, note: "You act with your user rights; the server checks your role (Owner/Admin) and the organisation's HITL setting." };
|
|
3128
|
+
}
|
|
3129
|
+
async function scopeChecks(op, ctx, platform, body) {
|
|
3130
|
+
const data = await readData(ctx.flags);
|
|
3131
|
+
if (data !== undefined && !isRecord(data))
|
|
3132
|
+
throw new CliError("--data must be a JSON object here.");
|
|
3133
|
+
const merged = { ...data, ...body };
|
|
3134
|
+
const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
3135
|
+
const scopes = strings(merged.scopes);
|
|
3136
|
+
const bundles = strings(merged.bundles);
|
|
3137
|
+
if (op.capability === "keys.update" && !scopes.length)
|
|
3138
|
+
return [];
|
|
3139
|
+
const { catalog, source, bundles: known } = await scopeCatalog(ctx, platform);
|
|
3140
|
+
const expanded = [...scopes, ...bundles.flatMap((bundle) => known?.[bundle] ?? [])];
|
|
3141
|
+
const { problems, warnings } = checkScopes(expanded, catalog);
|
|
3142
|
+
for (const bundle of bundles.filter((name) => !known?.[name])) {
|
|
3143
|
+
problems.push({ scope: bundle, code: "scope_not_available", reason: `Unknown bundle "${bundle}". Bundles: ${Object.keys(known ?? {}).join(", ") || "none known"}.` });
|
|
3144
|
+
}
|
|
3145
|
+
const { grant, note } = await parentGrant(ctx);
|
|
3146
|
+
const cap = typeof merged.monthly_spend_cap_mcr === "number" ? merged.monthly_spend_cap_mcr / 1000 : null;
|
|
3147
|
+
problems.push(...checkAttenuation(grant, { scopes: expanded, expiresAt: typeof merged.expires_at === "string" ? merged.expires_at : null, monthlyCreditCap: cap }, catalog));
|
|
3148
|
+
if (problems.length) {
|
|
3149
|
+
throw new CliError(`Scope check failed. ${problems.map((problem) => `${problem.scope ? `${problem.scope}: ` : ""}${problem.reason}`).join(" ")}`, 2, problems[0].code);
|
|
3150
|
+
}
|
|
3151
|
+
return [...warnings, catalog ? `Scopes checked against ${source}.` : "Scope shape checked only: the platform does not serve its scope catalogue (GET /v1/scopes) yet, so the server checks availability.", ...note ? [note] : []];
|
|
3152
|
+
}
|
|
3153
|
+
async function platformCommand(words, ctx) {
|
|
3154
|
+
if (words[0] === "keys" && words[1] === "scopes")
|
|
3155
|
+
return keysScopes(words.slice(2), ctx);
|
|
3156
|
+
if (words[0] === "keys" && words[1] === "check")
|
|
3157
|
+
return keysCheck(words.slice(2), ctx);
|
|
3158
|
+
const found = match(words);
|
|
3159
|
+
if (!found) {
|
|
3160
|
+
const group = PLATFORM_OPS.filter((op2) => op2.words[0] === dealias(words)[0]).map((op2) => `prudai ${op2.words.join(" ")}${(op2.positionals ?? []).map((p) => ` <${p}>`).join("")}`);
|
|
3161
|
+
if (words[0] === "keys")
|
|
3162
|
+
group.unshift("prudai keys scopes [--product p]", "prudai keys check --scopes a,b");
|
|
3163
|
+
throw new CliError(`Unknown command. Available: ${group.join(" | ")}`);
|
|
3164
|
+
}
|
|
3165
|
+
let { op } = found;
|
|
3166
|
+
let positionals = found.positionals;
|
|
3167
|
+
const typedAs = found.op.words.join(" ");
|
|
3168
|
+
if (op.withoutPositionalsUse && positionals.length === 0) {
|
|
3169
|
+
op = PLATFORM_OPS.find((entry) => entry.capability === op.withoutPositionalsUse) ?? op;
|
|
3170
|
+
if (op !== found.op && str(ctx.flags, "kb") === undefined && str(ctx.flags, "knowledge-bases") === undefined) {
|
|
3171
|
+
ctx.stderr(`Note: no <kb_id> given, so this queries ALL knowledge bases of your organisation (--kb <id>[,<id>…]|none chooses which; "prudai kb query <kb_id>" asks one).`);
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
if (op.approval === "forbidden_for_agents") {
|
|
3175
|
+
throw new CliError(`prudai ${op.words.join(" ")} is for a person only (forbidden_for_agents): ${op.summary}. ${op.consoleToday ? `A person does this in the account dashboard (${CONSOLE_URL}).` : "It is not available anywhere yet; it arrives in the Prudai Console."} Nothing was sent.`, 2, "forbidden_for_agents");
|
|
3176
|
+
}
|
|
3177
|
+
const extraFlags = op.flags ?? [];
|
|
3178
|
+
const consumed = [...(op.body ?? []).flatMap((entry) => [entry.flag, ...entry.aliases ?? []]), ...op.query ?? [], ...extraFlags.map((entry) => entry.flag), ...op.orgScoped ? ["org"] : []];
|
|
3179
|
+
validateFlags(ctx.flags, ["json", "help", "yes", "dry-run", "no-dry-run", "refresh", "offline", "wait", "timeout", "profile", "api-url", "data", "idempotency-key", "if-match", ...consumed]);
|
|
3180
|
+
if ((op.positionals ?? []).length < positionals.length)
|
|
3181
|
+
throw new CliError(`Too many arguments for prudai ${op.words.join(" ")}${(op.positionals ?? []).length ? `; it takes ${op.positionals.map((p) => `<${p}>`).join(" ")}` : ""}.`);
|
|
3182
|
+
const pathPositionals = (op.positionals ?? []).filter((name) => name !== "file");
|
|
3183
|
+
const fileEntry = (op.body ?? []).find((entry) => entry.kind === "file");
|
|
3184
|
+
let fileArgument;
|
|
3185
|
+
if (fileEntry) {
|
|
3186
|
+
const flagged = str(ctx.flags, fileEntry.flag);
|
|
3187
|
+
if (flagged !== undefined && positionals.length > pathPositionals.length)
|
|
3188
|
+
throw new CliError(`Give the file once: as <file> or as --${fileEntry.flag}.`, 2, "validation_error");
|
|
3189
|
+
fileArgument = flagged ?? positionals[pathPositionals.length];
|
|
3190
|
+
positionals = positionals.slice(0, pathPositionals.length);
|
|
3191
|
+
}
|
|
3192
|
+
const platform = await loadProductCatalog(PLATFORM_PRODUCT, ctx.catalog);
|
|
3193
|
+
const command = bindOperation(op, platform);
|
|
3194
|
+
const body = bodyFromFlags(op, ctx);
|
|
3195
|
+
const warnings = op.check === "scopes" ? await scopeChecks(op, ctx, platform, body) : [];
|
|
3196
|
+
for (const warning of warnings)
|
|
3197
|
+
ctx.stderr(`Note: ${warning}`);
|
|
3198
|
+
if (!command)
|
|
3199
|
+
throw notAvailable(op, warnings.length ? { localChecks: warnings } : {}, op === found.op ? undefined : typedAs);
|
|
3200
|
+
if (op.project && positionals.length < pathPositionals.length) {
|
|
3201
|
+
throw new CliError(`prudai ${op.words.join(" ")} takes ${(op.positionals ?? []).map((p) => `<${p}>`).join(" ")}${fileEntry ? ` (or --${fileEntry.flag} <path>)` : ""}.`, 2, "missing_parameter");
|
|
3202
|
+
}
|
|
3203
|
+
const force = ctx.flags.force === true;
|
|
3204
|
+
const out = str(ctx.flags, "out");
|
|
3205
|
+
if (op.output === "bytes" && out === undefined)
|
|
3206
|
+
throw new CliError("--out <path> is required: file bytes are never written to stdout or a terminal.", 2, "validation_error");
|
|
3207
|
+
if (force && out === undefined)
|
|
3208
|
+
throw new CliError("--force replaces an existing --out file; give --out <path>.", 2, "validation_error");
|
|
3209
|
+
if (out !== undefined)
|
|
3210
|
+
checkOutTarget(out, force);
|
|
3211
|
+
if (fileEntry && fileArgument === undefined)
|
|
3212
|
+
throw new CliError(`prudai ${op.words.join(" ")} needs the file to upload: <file> or --${fileEntry.flag} <path>.`, 2, "missing_parameter");
|
|
3213
|
+
const upload = fileArgument !== undefined ? inspectUploadFile(fileArgument, fileEntry.field) : undefined;
|
|
3214
|
+
if (op.costsMoney)
|
|
3215
|
+
ctx.stderr("Note: this changes what the organisation pays. It waits for a person's approval (the answer carries the approval link) and a person pays; the CLI never pays.");
|
|
3216
|
+
if (op.orgScoped) {
|
|
3217
|
+
const org = str(ctx.flags, "org") ?? ctx.file.profiles[ctx.config.profile]?.organization?.id ?? undefined;
|
|
3218
|
+
if (!org)
|
|
3219
|
+
throw new CliError("Name the organisation: --org <organization id> (prudai whoami shows yours).");
|
|
3220
|
+
positionals = [org, ...positionals];
|
|
3221
|
+
}
|
|
3222
|
+
const origin = resolveOrigin(PLATFORM_PRODUCT, ctx, platform.spec);
|
|
3223
|
+
let project;
|
|
3224
|
+
let access;
|
|
3225
|
+
if (op.project) {
|
|
3226
|
+
access = await apiAccess(ctx, PLATFORM_PRODUCT, origin);
|
|
3227
|
+
const reference = op.project === "memo" ? memoProjectReference(ctx) : positionals[0];
|
|
3228
|
+
const listOp = PLATFORM_OPS.find((entry) => entry.capability === "projects.list");
|
|
3229
|
+
const getOp = PLATFORM_OPS.find((entry) => entry.capability === "projects.get");
|
|
3230
|
+
const commands = { list: bindOperation(listOp, platform), get: bindOperation(getOp, platform) };
|
|
3231
|
+
project = await resolveProject(access, reference, commands, { verify: !!upload && !ctx.flags["no-dry-run"] });
|
|
3232
|
+
positionals = [project.id, ...op.project === "memo" ? positionals : positionals.slice(1)];
|
|
3233
|
+
}
|
|
3234
|
+
if (op.custom === "memos-list")
|
|
3235
|
+
return listMemos(access, command, project, ctx);
|
|
3236
|
+
const flags = { ...ctx.flags };
|
|
3237
|
+
delete flags.org;
|
|
3238
|
+
for (const entry of op.body ?? [])
|
|
3239
|
+
for (const name of [entry.flag, ...entry.aliases ?? []])
|
|
3240
|
+
delete flags[name];
|
|
3241
|
+
for (const entry of extraFlags) {
|
|
3242
|
+
const given = flags[entry.flag] === true;
|
|
3243
|
+
delete flags[entry.flag];
|
|
3244
|
+
if (entry.query && given)
|
|
3245
|
+
flags[entry.query] = "true";
|
|
3246
|
+
}
|
|
3247
|
+
const target2 = project ? { project: { id: project.id, name: project.name } } : upload && positionals[0] ? { knowledge_base: positionals[0] } : undefined;
|
|
3248
|
+
const extras = {
|
|
3249
|
+
...body ? { body } : {},
|
|
3250
|
+
consumed: [...op.query ?? [], ...extraFlags.filter((entry) => entry.query).map((entry) => entry.query)],
|
|
3251
|
+
...upload ? { upload: { file: upload, ...target2 ? { target: target2 } : {} } } : {},
|
|
3252
|
+
...op.output === "bytes" ? { download: { out, force } } : {},
|
|
3253
|
+
...op.output === "text" ? { text: { ...out !== undefined ? { out } : {}, force } } : {},
|
|
3254
|
+
...op.irreversible ? { irreversible: true } : {},
|
|
3255
|
+
...op.queued ? { queued: true } : {},
|
|
3256
|
+
...op.after ? { after: op.after } : {},
|
|
3257
|
+
checkBody: (merged) => {
|
|
3258
|
+
for (const entry of op.body ?? [])
|
|
3259
|
+
if (entry.kind === "kb-selection" && isRecord(merged) && merged[entry.field] !== undefined)
|
|
3260
|
+
checkKnowledgeBaseField(merged[entry.field]);
|
|
3261
|
+
}
|
|
3262
|
+
};
|
|
3263
|
+
return executeOperation(command, positionals, origin, { ...ctx, flags }, extras);
|
|
3264
|
+
}
|
|
3265
|
+
async function keysScopes(rest, ctx) {
|
|
3266
|
+
validateFlags(ctx.flags, ["json", "help", "profile", "product", "refresh", "offline", "api-url"]);
|
|
3267
|
+
if (rest.length)
|
|
3268
|
+
throw new CliError("Usage: prudai keys scopes [--product <product>]");
|
|
3269
|
+
const platform = await loadProductCatalog(PLATFORM_PRODUCT, ctx.catalog);
|
|
3270
|
+
const { catalog, source, bundles } = await scopeCatalog(ctx, platform);
|
|
3271
|
+
if (!catalog) {
|
|
3272
|
+
throw new NotAvailableError("prudai keys scopes is not available yet: the platform does not serve its scope catalogue (GET /v1/scopes). GET /v1/scopes was not sent.", {
|
|
3273
|
+
planned: "GET /v1/scopes",
|
|
3274
|
+
scope: "none (public catalogue)",
|
|
3275
|
+
next: [
|
|
3276
|
+
"prudai keys check --scopes <a,b> checks the shape of a scope set (<product>:<object>:<verb>) today; the server checks the rest when the key is created.",
|
|
3277
|
+
"The command starts working without a CLI release once the platform spec (/v1/openapi.json) lists GET /v1/scopes."
|
|
3278
|
+
]
|
|
3279
|
+
});
|
|
3280
|
+
}
|
|
3281
|
+
const only = str(ctx.flags, "product");
|
|
3282
|
+
const products = catalog.products.filter((entry) => !only || entry.product === only);
|
|
3283
|
+
const rows = products.flatMap((entry) => entry.objects.flatMap((object3) => object3.scopes.map((scope) => ({
|
|
3284
|
+
scope: scope.scope,
|
|
3285
|
+
product: entry.product,
|
|
3286
|
+
productStatus: entry.status,
|
|
3287
|
+
object: object3.object,
|
|
3288
|
+
verb: scope.verb,
|
|
3289
|
+
issuable: scope.issuable && entry.status === "available",
|
|
3290
|
+
hitl: scope.hitl,
|
|
3291
|
+
explicitOnly: object3.explicit_only,
|
|
3292
|
+
description: object3.description,
|
|
3293
|
+
operations: (scope.operations ?? []).map((o) => `${o.method} ${o.path}`)
|
|
3294
|
+
}))));
|
|
3295
|
+
const reserved = catalog.products.filter((entry) => entry.status === "reserved").map((entry) => entry.product);
|
|
3296
|
+
ctx.emit(localEnvelope(rows, {
|
|
3297
|
+
context: { wildcard: "<product>:*:<verb> (never covers explicit-only objects)", bundles: bundles ?? {}, reservedProducts: reserved },
|
|
3298
|
+
provenance: { kind: "live", source },
|
|
3299
|
+
notIncluded: reserved.length ? [`Products ${reserved.join(", ")} are reserved: their scopes are not issuable yet.`] : [],
|
|
3300
|
+
next: [{ action: "prudai keys check --scopes <a,b>", why: "Check a scope set (and attenuation) before creating a key." }]
|
|
3301
|
+
}), rows.map((row) => `${row.scope.padEnd(36)} ${row.issuable ? "issuable" : "not yet "} ${row.hitl ? "HITL" : " "} ${row.explicitOnly ? "explicit-only" : ""}`).join(`
|
|
3302
|
+
`) + `
|
|
3303
|
+
Source: ${source}`);
|
|
3304
|
+
return 0;
|
|
3305
|
+
}
|
|
3306
|
+
async function keysCheck(rest, ctx) {
|
|
3307
|
+
validateFlags(ctx.flags, ["json", "help", "profile", "scopes", "bundles", "expires-at", "monthly-cap-credits", "refresh", "offline", "api-url"]);
|
|
3308
|
+
if (rest.length)
|
|
3309
|
+
throw new CliError("Usage: prudai keys check --scopes <a,b> [--bundles x] [--expires-at <iso>] [--monthly-cap-credits n]");
|
|
3310
|
+
const op = PLATFORM_OPS.find((entry) => entry.capability === "keys.create");
|
|
3311
|
+
const platform = await loadProductCatalog(PLATFORM_PRODUCT, ctx.catalog);
|
|
3312
|
+
const notes = await scopeChecks(op, ctx, platform, bodyFromFlags(op, ctx));
|
|
3313
|
+
const shapeOnly = notes.some((note) => note.startsWith("Scope shape checked only"));
|
|
3314
|
+
ctx.emit(localEnvelope({ ok: true, ...shapeOnly ? { checked: "shape" } : {}, notes }, { provenance: { kind: "cli", check: shapeOnly ? "scope shape" : "scopes+attenuation" }, notIncluded: ["The server re-checks everything when the key is created; this is a local pre-check."] }), [shapeOnly ? "Scope shape OK (catalogue not served yet)." : "Scopes OK.", ...notes].join(`
|
|
3315
|
+
`));
|
|
3316
|
+
return 0;
|
|
3317
|
+
}
|
|
3318
|
+
async function mcpCommand(words, ctx) {
|
|
3319
|
+
validateFlags(ctx.flags, ["json", "help", "check", "profile"]);
|
|
3320
|
+
if (words.length)
|
|
3321
|
+
throw new CliError("Usage: prudai mcp [--check]");
|
|
3322
|
+
const servers = [
|
|
3323
|
+
{ name: "prudai", url: MCP_GATEWAY, scope: "all products", status: "planned (one gateway, one OAuth connection; not live yet)" },
|
|
3324
|
+
...PRODUCTS.filter((entry) => entry.mcpUrl).map((entry) => ({ name: entry.product, url: entry.mcpUrl, scope: entry.product, status: "live" }))
|
|
3325
|
+
];
|
|
3326
|
+
const checked = [];
|
|
3327
|
+
for (const server of servers) {
|
|
3328
|
+
let reachable;
|
|
3329
|
+
if (ctx.flags.check) {
|
|
3330
|
+
try {
|
|
3331
|
+
const response = await ctx.fetch(server.url, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(5000) });
|
|
3332
|
+
reachable = response.status === 401 || response.status === 403 ? `reachable (HTTP ${response.status}: sign-in required)` : `HTTP ${response.status}`;
|
|
3333
|
+
} catch {
|
|
3334
|
+
reachable = "unreachable";
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
checked.push({
|
|
3338
|
+
...server,
|
|
3339
|
+
transport: "streamable-http",
|
|
3340
|
+
auth: "OAuth with your Prudai login; no API key in the client config",
|
|
3341
|
+
tools: ["search_tools", "describe_tool", "execute_tool", "get_guide"],
|
|
3342
|
+
connect: { claudeCode: `claude mcp add --transport http ${server.name} ${server.url}`, codex: `[mcp_servers.${server.name}]
|
|
3343
|
+
url = "${server.url}"` },
|
|
3344
|
+
...reachable ? { reachable } : {}
|
|
3345
|
+
});
|
|
3346
|
+
}
|
|
3347
|
+
ctx.emit(localEnvelope(checked, {
|
|
3348
|
+
context: { approval: "Writes through MCP follow the same x-prudai-approval levels; a gated call returns an approval request or uses MCP elicitation." },
|
|
3349
|
+
provenance: { kind: "cli", source: "registry in @prudai/cli" },
|
|
3350
|
+
notIncluded: ["The gateway at mcp.prudai.com is planned; until then connect per product."],
|
|
3351
|
+
next: [{ action: "prudai ops search <text>", why: "The same operations are reachable from this CLI." }]
|
|
3352
|
+
}), checked.map((server) => `${server.name.padEnd(8)} ${server.url} ${server.status}${server.reachable ? ` [${server.reachable}]` : ""}
|
|
3353
|
+
${server.connect.claudeCode}`).join(`
|
|
3354
|
+
`));
|
|
3355
|
+
return 0;
|
|
3356
|
+
}
|
|
3357
|
+
function platformHelp() {
|
|
3358
|
+
return PLATFORM_OPS.map((op) => `${["prudai", ...op.words, ...(op.positionals ?? []).map((p) => `<${p}>`)].join(" ").padEnd(44)} ${op.method} ${op.path} [${op.status}]${op.costsMoney ? " costs money" : ""}`);
|
|
3359
|
+
}
|
|
3360
|
+
|
|
3361
|
+
// src/version.ts
|
|
3362
|
+
var VERSION = "0.1.1";
|
|
3363
|
+
|
|
3364
|
+
// src/discovery.ts
|
|
3365
|
+
var CATALOG_FLAGS = ["json", "help", "profile", "refresh", "offline", "spec", "registry", "api-url"];
|
|
3366
|
+
var EXIT_CODES = { "0": "completed (also: dry run shown, help, logged in but not usable)", "1": "network, server or invalid response: check state before retrying a write", "2": "you must act: validation, auth, refused write, not available yet, or pending human approval" };
|
|
3367
|
+
var ERROR_CODES = {
|
|
3368
|
+
validation_error: "Bad flags, arguments or input; the message says which.",
|
|
3369
|
+
missing_parameter: "A required path, query, header or body value is missing.",
|
|
3370
|
+
invalid_parameter: "A value does not match the operation's schema.",
|
|
3371
|
+
not_authenticated: "No valid Keycloak login (not logged in, logged out, revoked, or idle too long): run prudai login.",
|
|
3372
|
+
legacy_login: "The profile holds a removed personal token (prudai_pat_…); run prudai login.",
|
|
3373
|
+
invalid_token: "The token broker rejected the login token (after one refresh): run prudai login.",
|
|
3374
|
+
unknown_product: "The token broker does not know that product (or auth token --product was wrong).",
|
|
3375
|
+
exchange_unavailable: "The token broker could not be reached or answered with an error; the login itself may be fine.",
|
|
3376
|
+
invalid_exchange_response: "The token broker answered with something that is not a single-audience token; nothing was used.",
|
|
3377
|
+
rate_limited: "The token broker is rate limiting this login; wait and retry.",
|
|
3378
|
+
login_unavailable: "The Keycloak login service is unavailable; try again.",
|
|
3379
|
+
login_failed: "The device login failed; run prudai login again.",
|
|
3380
|
+
expired_token: "The device code expired before it was approved; run prudai login again.",
|
|
3381
|
+
not_supported: "This command does not exist in the Keycloak model (auth switch-org: use another profile).",
|
|
3382
|
+
untrusted_origin: "Refused to send a credential outside https://*.prudai.com or localhost.",
|
|
3383
|
+
dry_run_unsupported: "The operation declares no dry run, so nothing was sent; use --no-dry-run --yes after checking the request.",
|
|
3384
|
+
forbidden_for_agents: "Only a human may do this, in the product app.",
|
|
3385
|
+
not_available: "Decided or proposed, but the platform does not serve it yet; details name the planned route and reference.",
|
|
3386
|
+
scope_not_available: "A requested scope is unknown, reserved or not issuable yet.",
|
|
3387
|
+
attenuation_violation: "A key may only create keys with a subset of its rights, an equal or shorter lifetime and an equal or lower credit limit.",
|
|
3388
|
+
insufficient_scope: "The credential lacks the scope; details.required_scope names it.",
|
|
3389
|
+
approval_timeout: "Still pending after the wait; nothing was executed.",
|
|
3390
|
+
"approval_rejected/approval_expired/approval_cancelled/approval_failed": "The person said no, the request lapsed or failed; nothing was executed.",
|
|
3391
|
+
operation_pending: "HTTP 202 without a recognisable approval request.",
|
|
3392
|
+
network_error: "No answer; the write may or may not have happened.",
|
|
3393
|
+
invalid_response: "The server answered with something that is not JSON.",
|
|
3394
|
+
invalid_envelope: "The server sent a malformed /v1 envelope.",
|
|
3395
|
+
invalid_spec: "A spec could not be read or turned into commands.",
|
|
3396
|
+
unknown_profile: "The selected profile does not exist; create it or pick another.",
|
|
3397
|
+
"<server code>": "Other HTTP errors carry the product's own code (context.error.code), e.g. not_found, conflict.",
|
|
3398
|
+
"http_<status>": "An HTTP error without a recognisable code; the message gives a hint per status.",
|
|
3399
|
+
unknown_command: "Not a command or product; run prudai help or prudai ops search.",
|
|
3400
|
+
unknown_operation: "describe found nothing; the message suggests search hits.",
|
|
3401
|
+
ambiguous_operation: "describe matched several operations; name the product or full command.",
|
|
3402
|
+
already_authenticated: "A login exists; log out first (and unset PRUDAI_REFRESH_TOKEN).",
|
|
3403
|
+
access_denied: "The person denied the device login, or the broker says this login may not use that product.",
|
|
3404
|
+
invalid_refresh_token: "auth set --stdin needs one Keycloak refresh token (from auth export --reveal).",
|
|
3405
|
+
stdin_required: "Pipe the token; a terminal is refused.",
|
|
3406
|
+
invalid_origin: "An API origin must be HTTPS (HTTP only on localhost) without path or credentials.",
|
|
3407
|
+
invalid_issuer: "PRUDAI_ISSUER must be an https realm URL (or localhost) on a trusted origin.",
|
|
3408
|
+
invalid_exchange_url: "PRUDAI_EXCHANGE_URL / profile exchangeUrl must be an https URL (or localhost) on a trusted origin.",
|
|
3409
|
+
invalid_device_response: "The login service answered the device login with something invalid.",
|
|
3410
|
+
invalid_token_response: "The login service issued something that is not a valid token; nothing was stored.",
|
|
3411
|
+
invalid_profile: "Profile names are 1–64 letters, digits, _ or -.",
|
|
3412
|
+
profile_exists: "profile create on an existing name.",
|
|
3413
|
+
profile_has_login: "profile delete refuses a profile with a login; log out first.",
|
|
3414
|
+
invalid_config: "The config file is unreadable or malformed.",
|
|
3415
|
+
unsafe_config: "The config file is a symlink or readable by others (needs 0600).",
|
|
3416
|
+
config_changed: "The login changed while this command ran; nothing was overwritten.",
|
|
3417
|
+
config_write_failed: "The config could not be written safely.",
|
|
3418
|
+
skill_exists: "skill install found a SKILL.md it did not write; use --force to replace it.",
|
|
3419
|
+
spec_fetch_failed: "An explicit --spec URL could not be fetched.",
|
|
3420
|
+
unexpected_error: "A local failure without a better code.",
|
|
3421
|
+
project_not_found: "A project name matched no project; details.candidates lists similar names. Nothing was sent.",
|
|
3422
|
+
ambiguous_project: "A project name matched more than one project; details.candidates has their ids. Pass the id. Nothing was sent.",
|
|
3423
|
+
invalid_file: "A file to upload does not exist, is empty, is a directory or a symlink. Nothing was sent.",
|
|
3424
|
+
invalid_out: "--out is not a usable file path (stdout is never used, the directory must exist).",
|
|
3425
|
+
file_exists: "--out already exists. Nothing was overwritten; --force replaces it.",
|
|
3426
|
+
file_changed: "The file changed while it was being checked or uploaded; check the state before retrying.",
|
|
3427
|
+
incomplete_download: "The download ended early; the partial file was removed.",
|
|
3428
|
+
file_unreadable: "The file to upload could not be opened or read while uploading; check the state before retrying.",
|
|
3429
|
+
write_failed: "The file could not be written to --out; nothing was kept.",
|
|
3430
|
+
dry_run_unconfirmed: "A purge preview (the irreversible removal from the trash) was not confirmed by the server as a preview, so the purge may have run; check before anything else.",
|
|
3431
|
+
approval_required: "HTTP 403: the write waits for a person's approval and the approvals service does not run it yet. Nothing was executed."
|
|
3432
|
+
};
|
|
3433
|
+
async function catalogWithPlatform(ctx, only) {
|
|
3434
|
+
const wantsPlatform = !only || only.includes("platform") || only.includes(PLATFORM_PRODUCT);
|
|
3435
|
+
const names2 = only?.filter((name) => name !== "platform");
|
|
3436
|
+
const catalogs = names2 && !names2.length ? [] : await loadCatalog(ctx.catalog, names2?.length ? [...new Set(names2)] : undefined);
|
|
3437
|
+
if (!wantsPlatform)
|
|
3438
|
+
return catalogs;
|
|
3439
|
+
const leo = catalogs.find((c) => c.product === PLATFORM_PRODUCT) ?? (await loadCatalog(ctx.catalog, [PLATFORM_PRODUCT]))[0];
|
|
3440
|
+
const covered = coveredByPlatform(leo);
|
|
3441
|
+
const trimmed = catalogs.map((c) => c.product === PLATFORM_PRODUCT ? { ...c, commands: c.commands.filter((command) => !covered.has(command.operationId)) } : c);
|
|
3442
|
+
return [...trimmed, platformCatalog(leo)];
|
|
3443
|
+
}
|
|
3444
|
+
function guideText(catalogs) {
|
|
3445
|
+
const products = catalogs?.map((c) => ` ${c.product.padEnd(6)} ${String(c.commands.length).padStart(4)} operations ${c.source ? `[${c.source.kind}${c.source.status ? `, ${c.source.status}` : ""}]` : c.notAvailable ? "[not available yet: no live spec]" : c.loginNeeded ? "[prudai login shows its commands]" : c.error ? `[${c.error}]` : ""} ${c.title}`).join(`
|
|
3446
|
+
`) ?? " run prudai products";
|
|
3447
|
+
return `prudai ${VERSION} — guide for people and coding agents
|
|
3448
|
+
|
|
3449
|
+
Prudai's CLI is the complete interface to Prudai: every product operation, the account and
|
|
3450
|
+
developer platform (members, roles, seats, keys, billing details, subscriptions, credits,
|
|
3451
|
+
usage, logs, invoices, apps), approvals and MCP. Anything the Prudai Console can do is a
|
|
3452
|
+
command here; when the platform does not serve something yet, the command says "not available
|
|
3453
|
+
yet" with the planned route — it never pretends. You need no other documentation: this guide
|
|
3454
|
+
plus ops search and describe are enough.
|
|
3455
|
+
|
|
3456
|
+
1. DISCOVER
|
|
3457
|
+
prudai products products, where their catalogue came from, op counts
|
|
3458
|
+
prudai ops search "<text>" [--product p|platform] [--approval none|confirm|review] [--limit n]
|
|
3459
|
+
find operations across ALL products and the platform
|
|
3460
|
+
commands, with scope, HITL level (approval), cost, status
|
|
3461
|
+
(available or not yet) and the exact command line
|
|
3462
|
+
prudai describe <product> <command…> parameters, body schema + example, responses, curl
|
|
3463
|
+
prudai describe irma:<operationId> …or by operationId, or: prudai describe GET /v1/risks
|
|
3464
|
+
prudai describe keys create platform commands too: route, scope, approval, status
|
|
3465
|
+
prudai <product> help every command of one product
|
|
3466
|
+
prudai help --json machine-readable command list
|
|
3467
|
+
Products:
|
|
3468
|
+
${products}
|
|
3469
|
+
|
|
3470
|
+
2. AUTHENTICATE (one identity: your Prudai account in Keycloak; credentials never come from a flag)
|
|
3471
|
+
People and agents: prudai login (= auth login: Keycloak device login; a person approves the code
|
|
3472
|
+
in the browser, with their own login and MFA). prudai auth login --no-browser prints
|
|
3473
|
+
the URL and code, so the approval can happen on any other device.
|
|
3474
|
+
Each call: the CLI turns your login into a 5-minute token for exactly one product (IRMA, ORDO or the
|
|
3475
|
+
platform) through the token broker (standard OAuth token exchange). Product tokens live in
|
|
3476
|
+
memory only. There are no API keys, personal tokens or per-product keys.
|
|
3477
|
+
CI / automation: log in once with the device flow on the runner (prudai login --no-browser), or move the
|
|
3478
|
+
session: prudai auth export --reveal | secret store, then printf %s "$TOKEN" | prudai auth set --stdin,
|
|
3479
|
+
or export PRUDAI_REFRESH_TOKEN (the refresh token of such a login). A person can end any session.
|
|
3480
|
+
Check: prudai whoami (= auth status: user, organisation; --online proves the session still lives)
|
|
3481
|
+
Profiles: one login per profile; prudai profile list|create|use; --profile <name> per call. A login
|
|
3482
|
+
belongs to one organisation: use another profile for another organisation.
|
|
3483
|
+
Token for another tool, without printing it:
|
|
3484
|
+
curl -H "Authorization: Bearer $(prudai auth token --reveal --product irma)" … (never run --reveal bare)
|
|
3485
|
+
prudai logout ends the session at Keycloak first. Tokens are only sent to https://*.prudai.com and
|
|
3486
|
+
localhost; another origin needs PRUDAI_ALLOW_ORIGIN=<exact origin> in the environment.
|
|
3487
|
+
|
|
3488
|
+
3. SCOPES <product>:<object>:<verb>, verb = read | write | delete
|
|
3489
|
+
read scopes never need a person. write and delete scopes are the HITL class: their
|
|
3490
|
+
operations carry an approval level (confirm, review, …; see 6), so a person approves before
|
|
3491
|
+
the server executes. A key only needs the scope; the approval happens per call.
|
|
3492
|
+
Wildcard <product>:*:<verb> covers every object of that product and verb, including later
|
|
3493
|
+
ones — but never explicit-only objects (licensed text, credit-spending chat/answers, api_keys,
|
|
3494
|
+
subscriptions). Invalid: *, *:x:read, p:*:*, p:o:*. prudai keys scopes lists them once the platform serves
|
|
3495
|
+
GET /v1/scopes (until then: not_available).
|
|
3496
|
+
Keys that create keys (account:api_keys:write, explicit-only): the new key gets a SUBSET of
|
|
3497
|
+
the creator's rights, an equal or shorter lifetime and an equal or lower credit limit; revoking
|
|
3498
|
+
the creator revokes its children. prudai keys check --scopes a,b explains refusals it can see
|
|
3499
|
+
(scope shape always; catalogue and attenuation once the platform serves them).
|
|
3500
|
+
Your login has no scope list: you act with your current role and rights per product.
|
|
3501
|
+
|
|
3502
|
+
4. CALL AN OPERATION
|
|
3503
|
+
prudai <product> <object> <verb> [positionals] [--param value] [--data '{…}'|@file.json]
|
|
3504
|
+
Positionals: path parameters, then required query parameters, in describe's order.
|
|
3505
|
+
Every answer is the /v1 envelope: data, context, completeness (honest totals, truncated?),
|
|
3506
|
+
notIncluded (what this answer does NOT tell you, and which call does), provenance, next
|
|
3507
|
+
(the logical follow-up calls, with arguments). Read all six. Follow pagination.
|
|
3508
|
+
|
|
3509
|
+
5. WRITE DELIBERATELY
|
|
3510
|
+
A write never executes by default. If the operation declares a dry run, the CLI sends
|
|
3511
|
+
?dryRun=true and shows dryRun: true (serverConfirmed says whether the server honoured it).
|
|
3512
|
+
Otherwise nothing is sent: dry_run_unsupported. --yes alone changes nothing; a real write
|
|
3513
|
+
needs BOTH --no-dry-run --yes. Every write carries an Idempotency-Key (printed on stderr);
|
|
3514
|
+
after an uncertain delivery repeat with --idempotency-key <that key> — replay protection is
|
|
3515
|
+
guaranteed where describe says idempotency.declared. Writes are never retried automatically.
|
|
3516
|
+
--if-match <etag> for optimistic concurrency. Deletes are soft (restore exists).
|
|
3517
|
+
|
|
3518
|
+
6. HUMAN APPROVAL (HITL)
|
|
3519
|
+
Levels per operation (x-prudai-approval): none, instruct, confirm, review (second person),
|
|
3520
|
+
forbidden_for_agents (refused locally; a human does it in the app).
|
|
3521
|
+
HTTP 202 = approval_required, exit 2, NOT success. The answer shows the approval link (only
|
|
3522
|
+
for trusted Prudai origins) and: prudai approvals wait <id> --product <p> --execute
|
|
3523
|
+
which waits for the human decision and then lets the server run exactly the approved call.
|
|
3524
|
+
Or add --wait to the write itself. The CLI never approves and never fabricates a grant.
|
|
3525
|
+
prudai approvals list|get|status|execute|cancel --product irma (IRMA today; central later).
|
|
3526
|
+
|
|
3527
|
+
7. CREDITS AND MONEY
|
|
3528
|
+
1 credit = EUR 0.01. Metered operations (chat, source answers, …) report their cost in
|
|
3529
|
+
the answer; ops search shows cost. prudai credits [balance|ledger], prudai usage.
|
|
3530
|
+
Anything that costs money (top-up, subscription, seats) waits for a human; an agent never pays.
|
|
3531
|
+
|
|
3532
|
+
8. ACCOUNT AND DEVELOPER PLATFORM (api.prudai.com /v1; [status] = contract|planned|proposed)
|
|
3533
|
+
${platformHelp().map((line) => ` ${line}`).join(`
|
|
3534
|
+
`)}
|
|
3535
|
+
prudai keys scopes | keys check --scopes … (scope catalogue from GET /v1/scopes once served;
|
|
3536
|
+
until then keys check checks the scope shape only)
|
|
3537
|
+
prudai approvals … prudai mcp [--check] (MCP: ${MCP_GATEWAY} planned; per product today)
|
|
3538
|
+
Seats, subscriptions and top-ups change what you pay: they wait for a person's approval
|
|
3539
|
+
(the answer carries the approval link) and a person pays. Deleting the organisation is
|
|
3540
|
+
console-only. "not available yet" (exit 2, error not_available) names the planned route,
|
|
3541
|
+
says where a person can do it today (account dashboard ${CONSOLE_URL}) or that it is not
|
|
3542
|
+
available anywhere yet, and sends nothing.
|
|
3543
|
+
|
|
3544
|
+
PROJECTS AND MEMOS: prudai projects … (alias dossiers) and prudai memos …
|
|
3545
|
+
(recordings .m4a/.webm/.mp3/.wav and transcripts .vtt/.srt in a project). <project> is a UUID or
|
|
3546
|
+
the exact project name, any case; a name that matches 0 or more than 1 project stops with the
|
|
3547
|
+
candidates (exit 2) and nothing is written. memos use the project "Transcribe" unless --project
|
|
3548
|
+
or PRUDAI_MEMOS_PROJECT says otherwise.
|
|
3549
|
+
prudai memos list audio and transcripts: id, filename, kind, status, uploaded_by, subtitles, language
|
|
3550
|
+
prudai memos transcript <id> [--out p] the transcript as plain text on stdout (--json: the whole envelope)
|
|
3551
|
+
prudai memos download <id> --out p the original file, mode 0600, never overwrites without --force
|
|
3552
|
+
prudai memos upload <file> dry run: size, sha256 and target, nothing is sent
|
|
3553
|
+
prudai memos upload <file> --no-dry-run --yes one multipart part named file, Idempotency-Key as always
|
|
3554
|
+
prudai memos delete <id> [--no-dry-run --yes] move to the trash (soft delete: it can be restored)
|
|
3555
|
+
prudai memos list --trash the trash; prudai memos restore <id> brings a memo back (it is processed again)
|
|
3556
|
+
prudai memos purge <id> [--no-dry-run --yes] remove from the trash for good: irreversible (a live memo is refused)
|
|
3557
|
+
Reading works as soon as the platform serves these routes. Uploading, deleting, restoring and purging wait for a
|
|
3558
|
+
person's approval (confirm / review): until the approvals service runs them they answer 403
|
|
3559
|
+
approval_required and nothing is executed. File bytes are only ever written to --out.
|
|
3560
|
+
|
|
3561
|
+
9. RAW ESCAPE HATCH AND EXTENSIONS
|
|
3562
|
+
prudai api <METHOD> <path> [--product p] [--data …] — any path on a product origin, same
|
|
3563
|
+
credential, trust, dry-run and HITL rules (unknown writes need --no-dry-run --yes; a query
|
|
3564
|
+
string only fills the operation's own query parameters, never a CLI flag).
|
|
3565
|
+
prudai <name> … runs an installed extension prudai-<name> from PATH, if there is one.
|
|
3566
|
+
|
|
3567
|
+
10. OUTPUT AND EXIT CODES
|
|
3568
|
+
--json: exactly one JSON document on stdout, also for help and errors. Progress, device
|
|
3569
|
+
codes and notes go to stderr. Shapes: every result = the /v1 envelope (products, auth,
|
|
3570
|
+
profiles, catalogue answers alike); dry run = {dryRun:true,…}; pending =
|
|
3571
|
+
{status:"approval_required",…}; failure = {error, message, exitCode, …details}; help = the
|
|
3572
|
+
command list. Credentials are redacted from all output (only auth token --reveal prints one).
|
|
3573
|
+
Exit 0 completed · 1 network/server (check state before retrying a write) · 2 you must act.
|
|
3574
|
+
Error codes: prudai help --json (errorCodes).
|
|
3575
|
+
|
|
3576
|
+
11. CATALOGUE
|
|
3577
|
+
Per product: --spec/PRUDAI_SPEC/profile.specs > product plugin > live <origin>/v1/openapi.json
|
|
3578
|
+
(no credential sent; cached 24 h, misses 1 h) > the copy bundled with this CLI, which
|
|
3579
|
+
exists only for APIs that are live. A product without either answers not_available (exit 2)
|
|
3580
|
+
until it serves its spec. --refresh asks again, --offline never fetches. prudai products
|
|
3581
|
+
shows the source of each.
|
|
3582
|
+
|
|
3583
|
+
12. GIVE AN AGENT THIS CLI
|
|
3584
|
+
prudai skill install [--target claude|codex|all] [--dir <skills-dir>] writes a skill
|
|
3585
|
+
generated from this same catalogue. Re-run after upgrading the CLI.
|
|
3586
|
+
`;
|
|
3587
|
+
}
|
|
3588
|
+
var HELP_COMMANDS = [
|
|
3589
|
+
"guide",
|
|
3590
|
+
"products",
|
|
3591
|
+
"ops search <text> [--product p] [--approval level] [--method M] [--limit n]",
|
|
3592
|
+
"ops list [--product p]",
|
|
3593
|
+
"describe <product> <command…> | <product>:<operationId> | <METHOD> <path>",
|
|
3594
|
+
"api <METHOD> <path> [--product p] [--data json|@file]",
|
|
3595
|
+
"<product> help",
|
|
3596
|
+
"<product> <object> <verb> [args] [flags]",
|
|
3597
|
+
"login | logout | whoami",
|
|
3598
|
+
"auth login [--no-browser] | status [--online] | logout | token [--reveal --product p] | export --reveal | set --stdin",
|
|
3599
|
+
"profile list|create <name>|use <name>|delete <name>|set <key> <value>|unset <key>",
|
|
3600
|
+
"keys scopes [--product p] | check --scopes a,b | list | get <id> | create --name --scopes | update <id> | rotate <id> | revoke <id>",
|
|
3601
|
+
"projects list [--q t] [--include-archived] | get <project> | docs <project> [--trash] | doc <project> <document_id> | doc text <project> <document_id> [--out p] | doc original <project> <document_id> --out p | upload <project> <file> | doc delete <project> <document_id> | doc restore <project> <document_id> | doc purge <project> <document_id> (alias: dossiers; delete = to the trash, purge = final)",
|
|
3602
|
+
"memos list [--project p] [--trash] | get <id> | transcript <id> [--out p] | download <id> --out p | upload <file> | delete <id> | restore <id> | purge <id>",
|
|
3603
|
+
"tokens list | revoke <id>",
|
|
3604
|
+
"apps list | get <id> | create --name --redirect-uris | delete <id>",
|
|
3605
|
+
"account [show] | orgs list|create --name | trial start <org> --product p | products list <org> | members list|invite --email --role|remove <id> | subscription show|change",
|
|
3606
|
+
"kb list | create --name | get <kb_id> | update <kb_id> | delete <kb_id> | restore <kb_id> | docs <kb_id> | doc <kb_id> <document_id> | doc delete|restore <kb_id> <document_id> | upload <kb_id> <file> | query [<kb_id>] --question q [--kb id,…|all|none] | search --question q [--kb id,…|all|none] | answer <kb_id> --question q",
|
|
3607
|
+
"credits [balance] | ledger | topup --amount n",
|
|
3608
|
+
"usage <start_date>",
|
|
3609
|
+
"logs",
|
|
3610
|
+
"invoices list | download <id>",
|
|
3611
|
+
"settings [show] | update",
|
|
3612
|
+
"approvals list|get <id>|status <id>|wait <id> [--execute]|execute <id>|cancel <id> --product <p>",
|
|
3613
|
+
"mcp [--check]",
|
|
3614
|
+
"skill install [--target claude|codex|all] [--dir path] [--print] [--force]",
|
|
3615
|
+
"version",
|
|
3616
|
+
"help"
|
|
3617
|
+
];
|
|
3618
|
+
var HELP = {
|
|
3619
|
+
name: "prudai",
|
|
3620
|
+
version: VERSION,
|
|
3621
|
+
usage: "prudai <command> [args] [flags] — start with prudai guide",
|
|
3622
|
+
commands: HELP_COMMANDS,
|
|
3623
|
+
flags: [
|
|
3624
|
+
"--json",
|
|
3625
|
+
"--profile <name>",
|
|
3626
|
+
"--spec <path-or-url>",
|
|
3627
|
+
"--registry <url-template>",
|
|
3628
|
+
"--api-url <origin>",
|
|
3629
|
+
"--data <json-or-@file>",
|
|
3630
|
+
"--no-dry-run --yes",
|
|
3631
|
+
"--idempotency-key <key>",
|
|
3632
|
+
"--if-match <etag>",
|
|
3633
|
+
"--wait [--timeout s]",
|
|
3634
|
+
"--refresh",
|
|
3635
|
+
"--offline",
|
|
3636
|
+
"--out <path> [--force]",
|
|
3637
|
+
"--project <id|name>"
|
|
3638
|
+
],
|
|
3639
|
+
credentials: "Keycloak login only: ~/.config/prudai/config.json (0600) via prudai login, or PRUDAI_REFRESH_TOKEN on a runner. Product tokens (5 minutes, one product) come from the token broker. Never a flag. Tokens go only to https://*.prudai.com, localhost, or an exact PRUDAI_ALLOW_ORIGIN.",
|
|
3640
|
+
exitCodes: EXIT_CODES,
|
|
3641
|
+
errorCodes: ERROR_CODES
|
|
3642
|
+
};
|
|
3643
|
+
async function guideCommand(words, ctx) {
|
|
3644
|
+
validateFlags(ctx.flags, CATALOG_FLAGS);
|
|
3645
|
+
if (words.length)
|
|
3646
|
+
throw new CliError("Usage: prudai guide");
|
|
3647
|
+
const catalogs = await loadCatalog(ctx.catalog);
|
|
3648
|
+
const guide = guideText(catalogs);
|
|
3649
|
+
ctx.emit(localEnvelope({ guide }, {
|
|
3650
|
+
provenance: { kind: "cli", version: VERSION, catalog: catalogs.map((c) => ({ product: c.product, source: c.source?.kind ?? "none" })) },
|
|
3651
|
+
next: [{ action: "prudai ops search <text>", why: "Find the operation you need." }]
|
|
3652
|
+
}), guide);
|
|
3653
|
+
return 0;
|
|
3654
|
+
}
|
|
3655
|
+
function productSummary(c) {
|
|
3656
|
+
return {
|
|
3657
|
+
product: c.product,
|
|
3658
|
+
aliases: findProduct(c.product)?.aliases ?? [],
|
|
3659
|
+
title: c.title,
|
|
3660
|
+
origin: c.origin || null,
|
|
3661
|
+
operations: c.commands.length,
|
|
3662
|
+
writes: c.commands.filter((command) => command.method !== "GET").length,
|
|
3663
|
+
source: c.source ?? null,
|
|
3664
|
+
approvals: c.approvalsPath ? `${c.origin}${c.approvalsPath}` : null,
|
|
3665
|
+
mcp: c.mcpUrl ?? null,
|
|
3666
|
+
...c.error ? { error: c.error } : {},
|
|
3667
|
+
...c.warnings.length ? { warnings: c.warnings } : {},
|
|
3668
|
+
...c.liveNote ? { liveSpec: c.liveNote } : {}
|
|
3669
|
+
};
|
|
3670
|
+
}
|
|
3671
|
+
async function productsCommand(words, ctx) {
|
|
3672
|
+
validateFlags(ctx.flags, CATALOG_FLAGS);
|
|
3673
|
+
if (words.length)
|
|
3674
|
+
throw new CliError("Usage: prudai products");
|
|
3675
|
+
const catalogs = await loadCatalog(ctx.catalog);
|
|
3676
|
+
const rows = catalogs.map(productSummary);
|
|
3677
|
+
ctx.emit(localEnvelope(rows, { provenance: { kind: "catalog" }, next: [{ action: "prudai ops search <text>", why: "Search operations across these products." }] }), rows.map((row) => `${row.product.padEnd(6)} ${String(row.operations).padStart(4)} ops ${row.source ? `${row.source.kind}${row.source.status ? `/${row.source.status}` : ""}` : "no spec"} ${row.origin ?? ""}
|
|
3678
|
+
${row.title}${row.source?.ref ? `
|
|
3679
|
+
spec: ${row.source.ref}` : ""}${row.source?.note ? `
|
|
3680
|
+
${row.source.note}` : ""}${row.error ? `
|
|
3681
|
+
${row.error}` : ""}`).join(`
|
|
3682
|
+
`));
|
|
3683
|
+
return 0;
|
|
3684
|
+
}
|
|
3685
|
+
async function opsCommand(words, ctx) {
|
|
3686
|
+
validateFlags(ctx.flags, [...CATALOG_FLAGS, "product", "approval", "method", "limit"]);
|
|
3687
|
+
const [action, ...rest] = words;
|
|
3688
|
+
if (action !== "search" && action !== "list")
|
|
3689
|
+
throw new CliError('Usage: prudai ops search "<text>" [--product p] [--approval level] [--method M] [--limit n] | prudai ops list [--product p]');
|
|
3690
|
+
const query = rest.join(" ").trim();
|
|
3691
|
+
if (action === "search" && !query)
|
|
3692
|
+
throw new CliError('Give search words: prudai ops search "risk register"');
|
|
3693
|
+
if (action === "list" && query)
|
|
3694
|
+
throw new CliError("prudai ops list takes no words; use ops search.");
|
|
3695
|
+
const product = str(ctx.flags, "product");
|
|
3696
|
+
const productName = product === "platform" ? "platform" : product ? findProduct(product)?.product ?? product : undefined;
|
|
3697
|
+
const catalogs = await catalogWithPlatform(ctx, productName ? [productName] : undefined);
|
|
3698
|
+
const all = searchOperations(catalogs, query, { product: productName, approval: str(ctx.flags, "approval"), method: str(ctx.flags, "method") });
|
|
3699
|
+
const limit = intFlag(ctx.flags, "limit", action === "list" ? 1000 : 20, 1, 5000);
|
|
3700
|
+
const hits = all.slice(0, limit).map(({ score: _score, ...hit }) => hit);
|
|
3701
|
+
const missing = catalogs.filter((c) => c.error).map((c) => `${c.product}: ${c.error}`);
|
|
3702
|
+
ctx.emit(localEnvelope(hits, {
|
|
3703
|
+
context: { query, ...product ? { product } : {} },
|
|
3704
|
+
completeness: { returned: hits.length, total: all.length, truncated: hits.length < all.length },
|
|
3705
|
+
notIncluded: [...missing, ...hits.length < all.length ? [`${all.length - hits.length} more; raise --limit or narrow the words.`] : []],
|
|
3706
|
+
provenance: { kind: "catalog", sources: catalogs.map((c) => ({ product: c.product, source: c.source?.kind ?? "none", ...c.source?.ref ? { ref: c.source.ref } : {} })) },
|
|
3707
|
+
next: hits.length ? [{ action: `prudai describe ${hits[0].command.replace(/^prudai /, "").replace(/ <[^>]+>/g, "")}`, why: "Parameters, body and an example call." }] : [{ action: "prudai products", why: "See which catalogues loaded." }]
|
|
3708
|
+
}), hits.length ? hits.map((hit) => `${hit.command}
|
|
3709
|
+
${hit.method} ${hit.path} — ${hit.summary}
|
|
3710
|
+
approval: ${hit.approval} scopes: ${hit.scopes.join(",") || "not declared"} cost: ${hit.cost}${hit.status ? ` status: ${hit.status}` : ""}`).join(`
|
|
3711
|
+
`) + (all.length > hits.length ? `
|
|
3712
|
+
(${all.length - hits.length} more)` : "") : "No operations match.");
|
|
3713
|
+
return 0;
|
|
3714
|
+
}
|
|
3715
|
+
function compactSchema(schema, depth = 0) {
|
|
3716
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema))
|
|
3717
|
+
return schema;
|
|
3718
|
+
const node = schema;
|
|
3719
|
+
if (depth > 4)
|
|
3720
|
+
return { type: node.type ?? "object", note: "nested; see the product reference" };
|
|
3721
|
+
const out = {};
|
|
3722
|
+
for (const key of ["type", "format", "enum", "const", "default", "minimum", "maximum", "minLength", "maxLength", "pattern"])
|
|
3723
|
+
if (node[key] !== undefined)
|
|
3724
|
+
out[key] = node[key];
|
|
3725
|
+
if (typeof node.description === "string")
|
|
3726
|
+
out.description = node.description.trim().split(`
|
|
3727
|
+
`)[0].slice(0, 200);
|
|
3728
|
+
if (Array.isArray(node.required) && node.required.length)
|
|
3729
|
+
out.required = node.required;
|
|
3730
|
+
if (node.properties && typeof node.properties === "object")
|
|
3731
|
+
out.properties = Object.fromEntries(Object.entries(node.properties).map(([key, value]) => [key, compactSchema(value, depth + 1)]));
|
|
3732
|
+
if (node.items)
|
|
3733
|
+
out.items = compactSchema(node.items, depth + 1);
|
|
3734
|
+
for (const key of ["oneOf", "anyOf", "allOf"])
|
|
3735
|
+
if (Array.isArray(node[key]))
|
|
3736
|
+
out[key] = node[key].map((value) => compactSchema(value, depth + 1));
|
|
3737
|
+
return out;
|
|
3738
|
+
}
|
|
3739
|
+
function exampleFrom(schema, name = "value", depth = 0) {
|
|
3740
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema) || depth > 5)
|
|
3741
|
+
return `<${name}>`;
|
|
3742
|
+
const node = schema;
|
|
3743
|
+
if (node.example !== undefined)
|
|
3744
|
+
return node.example;
|
|
3745
|
+
if (Array.isArray(node.examples) && node.examples.length)
|
|
3746
|
+
return node.examples[0];
|
|
3747
|
+
if (node.const !== undefined)
|
|
3748
|
+
return node.const;
|
|
3749
|
+
if (node.default !== undefined)
|
|
3750
|
+
return node.default;
|
|
3751
|
+
if (Array.isArray(node.enum) && node.enum.length)
|
|
3752
|
+
return node.enum[0];
|
|
3753
|
+
for (const key of ["oneOf", "anyOf"])
|
|
3754
|
+
if (Array.isArray(node[key]) && node[key].length)
|
|
3755
|
+
return exampleFrom(node[key][0], name, depth + 1);
|
|
3756
|
+
if (Array.isArray(node.allOf))
|
|
3757
|
+
return Object.assign({}, ...node.allOf.map((part) => {
|
|
3758
|
+
const value = exampleFrom(part, name, depth + 1);
|
|
3759
|
+
return value && typeof value === "object" ? value : {};
|
|
3760
|
+
}));
|
|
3761
|
+
const type = Array.isArray(node.type) ? node.type.find((t) => t !== "null") : node.type;
|
|
3762
|
+
if (type === "object" || node.properties) {
|
|
3763
|
+
const props = node.properties ?? {};
|
|
3764
|
+
const required = Array.isArray(node.required) ? node.required.filter((key) => typeof key === "string") : [];
|
|
3765
|
+
return Object.fromEntries(required.map((key) => [key, exampleFrom(props[key], key, depth + 1)]));
|
|
3766
|
+
}
|
|
3767
|
+
if (type === "array")
|
|
3768
|
+
return [exampleFrom(node.items, name, depth + 1)];
|
|
3769
|
+
if (type === "integer" || type === "number")
|
|
3770
|
+
return typeof node.minimum === "number" ? node.minimum : 1;
|
|
3771
|
+
if (type === "boolean")
|
|
3772
|
+
return false;
|
|
3773
|
+
if (node.format === "date-time")
|
|
3774
|
+
return "2026-01-01T00:00:00Z";
|
|
3775
|
+
if (node.format === "date")
|
|
3776
|
+
return "2026-01-01";
|
|
3777
|
+
if (node.format === "uuid")
|
|
3778
|
+
return "00000000-0000-4000-8000-000000000000";
|
|
3779
|
+
return `<${name}>`;
|
|
3780
|
+
}
|
|
3781
|
+
function param(parameter) {
|
|
3782
|
+
const schema = parameter.schema ?? {};
|
|
3783
|
+
return {
|
|
3784
|
+
name: parameter.name,
|
|
3785
|
+
in: parameter.in,
|
|
3786
|
+
required: parameter.required === true,
|
|
3787
|
+
...compactSchema(schema),
|
|
3788
|
+
...typeof parameter.description === "string" ? { description: parameter.description.trim().split(`
|
|
3789
|
+
`)[0].slice(0, 200) } : {}
|
|
3790
|
+
};
|
|
3791
|
+
}
|
|
3792
|
+
function describeCommand(command, catalog) {
|
|
3793
|
+
const positionals = command.positionals.map((name) => command.parameters.find((p) => p.name === name && (p.in === "path" || p.in === "query"))).filter(Boolean).map((p) => param(p));
|
|
3794
|
+
const flags = command.parameters.filter((p) => p.in === "query" && !command.positionals.includes(p.name) && p.name !== "dryRun" || p.in === "header" && !/^(idempotency-key|if-match)$/i.test(p.name)).map((p) => ({ flag: `--${p.in === "header" ? p.name.toLowerCase() : p.name}`, ...param(p) }));
|
|
3795
|
+
const writing = command.method !== "GET" && !command.readsViaPost;
|
|
3796
|
+
const body = command.inputSchema !== undefined ? { required: command.bodyRequired === true, schema: compactSchema(command.inputSchema), example: exampleFrom(command.inputSchema, "body") } : undefined;
|
|
3797
|
+
const base = ["prudai", command.product, command.name, ...command.positionals.map((name) => `<${name}>`)].join(" ");
|
|
3798
|
+
const dataArg = body ? ` --data '${JSON.stringify(body.example)}'` : "";
|
|
3799
|
+
const cli = writing ? [command.dryRun ? `${base}${dataArg} # dry run (server-side), nothing executes` : `${base}${dataArg} # refused: no dry run declared, shows nothing is sent`, `${base}${dataArg} --no-dry-run --yes`] : [`${base}${flags.length ? ` [${flags.slice(0, 3).map((f) => `${f.flag} <${f.name}>`).join("] [")}]` : ""}`];
|
|
3800
|
+
const url = `${catalog.origin || "https://<origin>"}${command.path.replace(/\{([^}]+)\}/g, "<$1>")}${writing && command.dryRun ? "?dryRun=true" : ""}`;
|
|
3801
|
+
const curl = [
|
|
3802
|
+
`curl -sS -X ${command.method} "${url}"`,
|
|
3803
|
+
`-H "Authorization: Bearer $(prudai auth token --reveal --product ${tokenProductFor(command.product)})"`,
|
|
3804
|
+
...writing ? [`-H "Idempotency-Key: $(uuidgen)"`] : [],
|
|
3805
|
+
...body ? [`-H "Content-Type: application/json" -d '${JSON.stringify(body.example)}'`] : [],
|
|
3806
|
+
...command.multipart ? [`-F "file=@<path>"`] : []
|
|
3807
|
+
].join(" \\\n ");
|
|
3808
|
+
return {
|
|
3809
|
+
command: commandLine(command),
|
|
3810
|
+
product: command.product,
|
|
3811
|
+
operationId: command.operationId,
|
|
3812
|
+
method: command.method,
|
|
3813
|
+
path: command.path,
|
|
3814
|
+
summary: command.summary,
|
|
3815
|
+
...command.description ? { description: command.description } : {},
|
|
3816
|
+
...command.tags ? { tags: command.tags } : {},
|
|
3817
|
+
approval: command.approval,
|
|
3818
|
+
...command.approvalSource === "default" ? { approvalSource: "default (spec declares none)" } : {},
|
|
3819
|
+
scopes: command.scopes ?? [],
|
|
3820
|
+
cost: command.cost ?? "not stated",
|
|
3821
|
+
...command.status ? { status: command.status } : {},
|
|
3822
|
+
...command.deprecated ? { deprecated: true } : {},
|
|
3823
|
+
dryRun: writing ? command.dryRun ? "declared: the CLI sends ?dryRun=true by default" : "not declared: nothing is sent without --no-dry-run --yes" : "not applicable (read)",
|
|
3824
|
+
idempotency: writing ? { sent: true, declared: command.idempotencyDeclared } : undefined,
|
|
3825
|
+
positionals,
|
|
3826
|
+
flags,
|
|
3827
|
+
...body ? { body } : {},
|
|
3828
|
+
...command.multipart ? { multipart: { contentType: "multipart/form-data", parts: "exactly one, named file", note: "A file is sent by the dedicated command (prudai projects upload, prudai memos upload, prudai kb upload) or by curl -F." } } : {},
|
|
3829
|
+
responses: command.responses ?? [],
|
|
3830
|
+
examples: { cli, curl },
|
|
3831
|
+
origin: catalog.origin || null,
|
|
3832
|
+
catalog: catalog.source ?? null
|
|
3833
|
+
};
|
|
3834
|
+
}
|
|
3835
|
+
function describeBound(bound, catalog, command) {
|
|
3836
|
+
const doc = describeCommand(bound, catalog);
|
|
3837
|
+
return bound.multipart ? { ...doc, examples: { ...doc.examples, cli: [`${command} # dry run: shows size and sha256, sends nothing`, `${command} --no-dry-run --yes`] } } : doc;
|
|
3838
|
+
}
|
|
3839
|
+
async function describePlatform(op, ctx) {
|
|
3840
|
+
const [leo] = await loadCatalog(ctx.catalog, [PLATFORM_PRODUCT]);
|
|
3841
|
+
const bound = bindOperation(op, leo);
|
|
3842
|
+
const flags = [
|
|
3843
|
+
...(op.body ?? []).map((entry) => ({ flag: `--${entry.flag}`, field: entry.field, kind: entry.kind, ...entry.aliases?.length ? { aliases: entry.aliases.map((name) => `--${name}`) } : {} })),
|
|
3844
|
+
...(op.query ?? []).map((name) => ({ flag: `--${name}`, in: "query" })),
|
|
3845
|
+
...op.orgScoped ? [{ flag: "--org", note: "organisation id; default: the organisation of your login" }] : [],
|
|
3846
|
+
...(op.flags ?? []).map((entry) => ({ flag: `--${entry.flag}`, note: entry.note }))
|
|
3847
|
+
];
|
|
3848
|
+
const commandText = ["prudai", ...op.words, ...(op.positionals ?? []).map((p) => `<${p}>`)].join(" ");
|
|
3849
|
+
const doc = {
|
|
3850
|
+
command: commandText,
|
|
3851
|
+
summary: op.summary,
|
|
3852
|
+
method: op.method,
|
|
3853
|
+
route: op.path,
|
|
3854
|
+
scope: op.scope,
|
|
3855
|
+
approval: op.approval,
|
|
3856
|
+
status: op.status,
|
|
3857
|
+
available: !!bound,
|
|
3858
|
+
...op.costsMoney ? { costsMoney: "a person approves and pays; the CLI never pays" } : {},
|
|
3859
|
+
...op.irreversible ? { irreversible: "the final removal: it cannot be undone; the dry run says so" } : {},
|
|
3860
|
+
flags,
|
|
3861
|
+
...bound ? { operation: describeBound(bound, leo, commandText) } : {}
|
|
3862
|
+
};
|
|
3863
|
+
ctx.emit(localEnvelope(doc, {
|
|
3864
|
+
provenance: { kind: "catalog", product: "platform", source: leo.source ?? null },
|
|
3865
|
+
notIncluded: bound ? [] : ["The platform does not serve this route yet, so there is no schema to show; the command answers not_available until it does."],
|
|
3866
|
+
next: [{ action: doc.command, why: bound ? "Run it (writes preview first)." : "Try it later; nothing is sent while it is not available." }]
|
|
3867
|
+
}), [
|
|
3868
|
+
`${doc.command}`,
|
|
3869
|
+
`${op.method} ${op.path} — ${op.summary}`,
|
|
3870
|
+
`scope: ${op.scope} approval: ${op.approval} status: ${op.status}${bound ? "" : " (not available yet)"}${op.costsMoney ? " costs money" : ""}`,
|
|
3871
|
+
...flags.length ? ["flags:", ...flags.map((f) => ` ${f.flag}${"field" in f ? ` → ${f.field}` : ""}`)] : []
|
|
3872
|
+
].join(`
|
|
3873
|
+
`));
|
|
3874
|
+
return 0;
|
|
3875
|
+
}
|
|
3876
|
+
async function describeOperationCommand(words, ctx) {
|
|
3877
|
+
validateFlags(ctx.flags, CATALOG_FLAGS);
|
|
3878
|
+
if (!words.length)
|
|
3879
|
+
throw new CliError("Usage: prudai describe <product> <command words> | <product>:<operationId> | <METHOD> <path>");
|
|
3880
|
+
const platformMatch = matchPlatform(words[0] === "prudai" ? words.slice(1) : words);
|
|
3881
|
+
if (platformMatch && !findProduct(words[0]))
|
|
3882
|
+
return describePlatform(platformMatch.op, ctx);
|
|
3883
|
+
const first = findProduct(words[0])?.product;
|
|
3884
|
+
const catalogs = await catalogWithPlatform(ctx, first ? [first] : undefined);
|
|
3885
|
+
const found = findOperation(catalogs, words);
|
|
3886
|
+
if ("candidates" in found) {
|
|
3887
|
+
const named = first ? catalogs.find((catalog) => catalog.product === first) : undefined;
|
|
3888
|
+
if (named && !found.candidates.length)
|
|
3889
|
+
throwIfUnusable(named);
|
|
3890
|
+
if (!found.candidates.length) {
|
|
3891
|
+
const hits = searchOperations(catalogs, words.join(" ")).slice(0, 5).map((hit) => hit.command);
|
|
3892
|
+
throw new CliError(`No operation matches "${words.join(" ")}".${hits.length ? ` Did you mean: ${hits.join(" | ")}` : " Try prudai ops search <words>."}`, 2, "unknown_operation");
|
|
3893
|
+
}
|
|
3894
|
+
throw new CliError(`"${words.join(" ")}" matches ${found.candidates.length} operations: ${found.candidates.slice(0, 10).join(" | ")}. Name the product or the full command.`, 2, "ambiguous_operation");
|
|
3895
|
+
}
|
|
3896
|
+
const doc = describeCommand(found.command, found.catalog);
|
|
3897
|
+
ctx.emit(localEnvelope(doc, {
|
|
3898
|
+
provenance: { kind: "catalog", product: found.catalog.product, source: found.catalog.source ?? null },
|
|
3899
|
+
notIncluded: ["Full JSON Schemas are compacted to 5 levels; the product reference has every field."],
|
|
3900
|
+
next: [{ action: doc.examples.cli[0].replace(/\s+#.*$/, ""), why: found.command.method === "GET" ? "Run it." : "Preview it first." }]
|
|
3901
|
+
}), [
|
|
3902
|
+
`${doc.command}`,
|
|
3903
|
+
`${doc.method} ${doc.path} — ${doc.summary}`,
|
|
3904
|
+
doc.description ? `
|
|
3905
|
+
${doc.description}
|
|
3906
|
+
` : "",
|
|
3907
|
+
`approval: ${doc.approval}${doc.approvalSource ? ` (${doc.approvalSource})` : ""} scopes: ${doc.scopes.join(", ") || "not declared (personal tokens act with your rights)"} cost: ${doc.cost}${doc.status ? ` status: ${doc.status}` : ""}`,
|
|
3908
|
+
`dry run: ${doc.dryRun}`,
|
|
3909
|
+
...doc.idempotency ? [`idempotency: key always sent; replay protection ${doc.idempotency.declared ? "declared" : "not declared"}`] : [],
|
|
3910
|
+
...doc.positionals.length ? ["positionals:", ...doc.positionals.map((p) => ` <${p.name}> (${p.in}${p.required ? ", required" : ""}) ${p.type ?? ""} ${p.description ?? ""}`)] : [],
|
|
3911
|
+
...doc.flags.length ? ["flags:", ...doc.flags.map((f) => ` ${f.flag}${f.required ? " (required)" : ""} ${f.type ?? ""}${f.enum ? ` ${JSON.stringify(f.enum)}` : ""} ${f.description ?? ""}`)] : [],
|
|
3912
|
+
...doc.body ? [`body${doc.body.required ? " (required)" : ""}: ${JSON.stringify(doc.body.schema)}`, `example: ${JSON.stringify(doc.body.example)}`] : [],
|
|
3913
|
+
`responses: ${doc.responses.map((r) => `${r.status}${r.description ? ` ${r.description}` : ""}`).join("; ")}`,
|
|
3914
|
+
"examples:",
|
|
3915
|
+
...doc.examples.cli.map((line) => ` ${line}`),
|
|
3916
|
+
` ${doc.examples.curl.replace(/\n/g, `
|
|
3917
|
+
`)}`
|
|
3918
|
+
].filter((line) => line !== "").join(`
|
|
3919
|
+
`));
|
|
3920
|
+
return 0;
|
|
3921
|
+
}
|
|
3922
|
+
|
|
3923
|
+
// src/skill.ts
|
|
3924
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3925
|
+
import { homedir as homedir2 } from "node:os";
|
|
3926
|
+
import { dirname as dirname4, join as join4, resolve as resolve3 } from "node:path";
|
|
3927
|
+
var SKILL_MARKER = "generated by `prudai skill install`";
|
|
3928
|
+
function skillMarkdown(catalogs, today) {
|
|
3929
|
+
const rows = catalogs.map((c) => `| ${c.product} | ${c.title} | ${c.commands.length} | ${c.source ? `${c.source.kind}${c.source.status ? ` (${c.source.status})` : ""}` : "none"} |`);
|
|
3930
|
+
return `---
|
|
3931
|
+
name: prudai
|
|
3932
|
+
description: Use the Prudai CLI (\`prudai\`) for anything with Prudai — LEO, IRMA and ORDO operations, service keys for the customer's own applications and scopes, organisations and members, credits, usage, invoices, approvals (HITL), MCP, and projects (dossiers) with their recordings and transcripts (memos: upload, read, download, delete to the trash, restore, purge). Trigger on any task that reads or changes data in a Prudai product or the Prudai account/developer platform, or asks which Prudai operation, scope or approval level applies.
|
|
3933
|
+
---
|
|
3934
|
+
|
|
3935
|
+
<!-- ${SKILL_MARKER} (@prudai/cli ${VERSION}, ${today}). Re-run it after upgrading; edits here are overwritten. -->
|
|
3936
|
+
|
|
3937
|
+
# Prudai CLI
|
|
3938
|
+
|
|
3939
|
+
\`prudai\` is the complete interface to Prudai for people and agents. Do not guess routes or
|
|
3940
|
+
scopes: discover them.
|
|
3941
|
+
|
|
3942
|
+
1. \`prudai ops search "<what you want>"\` — operations across all products, with the exact
|
|
3943
|
+
command, scope, approval level (HITL) and cost.
|
|
3944
|
+
2. \`prudai describe <product> <command…>\` — parameters, body schema, an example and curl.
|
|
3945
|
+
3. Run it with \`--json\`. Reads run directly; writes preview first (dry run) and need
|
|
3946
|
+
\`--no-dry-run --yes\` to execute. HTTP 202 = a human must approve:
|
|
3947
|
+
\`prudai approvals wait <id> --product <p> --execute\`.
|
|
3948
|
+
4. Exit codes: 0 done · 1 network/server (check state before retrying a write) · 2 you must act.
|
|
3949
|
+
"not available yet" (error not_available) means the platform has not built it: say so,
|
|
3950
|
+
do not work around it.
|
|
3951
|
+
|
|
3952
|
+
Files: \`prudai memos upload <file>\` and \`prudai projects upload <project> <file>\` preview first (size, sha256,
|
|
3953
|
+
target) and send only with \`--no-dry-run --yes\`. \`memos transcript <id>\` prints plain text; \`memos download <id> --out <path>\`
|
|
3954
|
+
writes the original to a private file (never stdout, never over an existing file without \`--force\`). \`memos delete\`
|
|
3955
|
+
moves a memo to the trash (soft delete; \`memos list --trash\` shows the trash, \`memos restore <id>\` brings it back) and only \`memos purge <id>\`
|
|
3956
|
+
removes it for good (irreversible, and only from the trash). Uploading, deleting, restoring and purging wait for a person's approval: until the platform's approvals
|
|
3957
|
+
service runs them the answer is 403 \`approval_required\` and nothing happened; say so, do not retry around it.
|
|
3958
|
+
|
|
3959
|
+
Never pass credentials as flags, never print a token (\`auth token --reveal\` only inside
|
|
3960
|
+
\`$(…)\`), never approve on a human's behalf, never pay. Credentials: \`prudai login\` (Keycloak device login; people and agents),
|
|
3961
|
+
or \`PRUDAI_REFRESH_TOKEN\` on a runner that logged in once.
|
|
3962
|
+
The CLI itself never logs in with a key. \`prudai keys\` manages service keys for the customer's own applications with your Keycloak login; the secret of a new or rotated key is shown once, so never print or log it.
|
|
3963
|
+
|
|
3964
|
+
| Product | What | Operations | Catalogue |
|
|
3965
|
+
| --- | --- | --- | --- |
|
|
3966
|
+
${rows.join(`
|
|
3967
|
+
`)}
|
|
3968
|
+
|
|
3969
|
+
## Full guide (\`prudai guide\`)
|
|
3970
|
+
|
|
3971
|
+
\`\`\`text
|
|
3972
|
+
${guideText(catalogs).trimEnd()}
|
|
3973
|
+
\`\`\`
|
|
3974
|
+
`;
|
|
3975
|
+
}
|
|
3976
|
+
async function skillCommand(words, ctx) {
|
|
3977
|
+
validateFlags(ctx.flags, ["json", "help", "target", "dir", "print", "force", "refresh", "offline", "profile"]);
|
|
3978
|
+
if (words[0] !== "install" || words.length !== 1)
|
|
3979
|
+
throw new CliError("Usage: prudai skill install [--target claude|codex|all] [--dir <skills-dir>] [--print] [--force]");
|
|
3980
|
+
const catalogs = await loadCatalog(ctx.catalog);
|
|
3981
|
+
const content = skillMarkdown(catalogs, new Date(ctx.now()).toISOString().slice(0, 10));
|
|
3982
|
+
if (ctx.flags.print) {
|
|
3983
|
+
if (ctx.json)
|
|
3984
|
+
ctx.emit(localEnvelope({ content }, { provenance: { kind: "cli", version: VERSION } }));
|
|
3985
|
+
else
|
|
3986
|
+
ctx.emit(content, content);
|
|
3987
|
+
return 0;
|
|
3988
|
+
}
|
|
3989
|
+
const home = ctx.options.home ?? ctx.env.HOME ?? homedir2();
|
|
3990
|
+
const target2 = str(ctx.flags, "target") ?? (str(ctx.flags, "dir") ? "dir" : "claude");
|
|
3991
|
+
const dirs = { claude: join4(home, ".claude", "skills"), codex: join4(home, ".codex", "skills") };
|
|
3992
|
+
let roots;
|
|
3993
|
+
if (str(ctx.flags, "dir")) {
|
|
3994
|
+
if (str(ctx.flags, "target"))
|
|
3995
|
+
throw new CliError("Use --dir or --target, not both.");
|
|
3996
|
+
roots = [resolve3(str(ctx.flags, "dir"))];
|
|
3997
|
+
} else if (target2 === "all")
|
|
3998
|
+
roots = [dirs.claude, dirs.codex];
|
|
3999
|
+
else if (dirs[target2])
|
|
4000
|
+
roots = [dirs[target2]];
|
|
4001
|
+
else
|
|
4002
|
+
throw new CliError("--target is claude, codex or all.");
|
|
4003
|
+
const written = [];
|
|
4004
|
+
for (const root of roots) {
|
|
4005
|
+
const path = join4(root, "prudai", "SKILL.md");
|
|
4006
|
+
if (existsSync4(path)) {
|
|
4007
|
+
const current = readFileSync3(path, "utf8");
|
|
4008
|
+
if (!current.includes(SKILL_MARKER) && !ctx.flags.force) {
|
|
4009
|
+
throw new CliError(`${path} exists and was not written by prudai skill install; nothing was changed. Move it, or pass --force to replace it.`, 2, "skill_exists");
|
|
4010
|
+
}
|
|
4011
|
+
if (current === content) {
|
|
4012
|
+
written.push({ path, status: "unchanged" });
|
|
4013
|
+
continue;
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
mkdirSync3(dirname4(path), { recursive: true });
|
|
4017
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
4018
|
+
writeFileSync3(temporary, content, { mode: 420 });
|
|
4019
|
+
renameSync4(temporary, path);
|
|
4020
|
+
written.push({ path, status: "written" });
|
|
4021
|
+
}
|
|
4022
|
+
ctx.emit(localEnvelope(written, { provenance: { kind: "cli", version: VERSION }, next: [{ action: "Start a new agent session", why: "Skills load at session start." }] }), written.map((entry) => `${entry.status}: ${entry.path}`).join(`
|
|
4023
|
+
`));
|
|
4024
|
+
return 0;
|
|
4025
|
+
}
|
|
4026
|
+
|
|
4027
|
+
// src/system.ts
|
|
4028
|
+
import { spawn } from "node:child_process";
|
|
4029
|
+
import { accessSync as accessSync2, constants as constants3, statSync as statSync2 } from "node:fs";
|
|
4030
|
+
import { constants as osConstants } from "node:os";
|
|
4031
|
+
import { delimiter, join as join5 } from "node:path";
|
|
4032
|
+
function which(binary, env2 = process.env, platform = process.platform) {
|
|
4033
|
+
if (!binary || /[\\/]/.test(binary))
|
|
4034
|
+
return;
|
|
4035
|
+
const windows = platform === "win32";
|
|
4036
|
+
const extensions = windows ? [...(env2.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean), ""] : [""];
|
|
4037
|
+
for (const directory of (windows ? env2.Path ?? env2.PATH : env2.PATH)?.split(delimiter) ?? []) {
|
|
4038
|
+
if (!directory)
|
|
4039
|
+
continue;
|
|
4040
|
+
for (const extension of extensions) {
|
|
4041
|
+
const candidate = join5(directory, binary + extension);
|
|
4042
|
+
try {
|
|
4043
|
+
if (!statSync2(candidate).isFile())
|
|
4044
|
+
continue;
|
|
4045
|
+
if (!windows)
|
|
4046
|
+
accessSync2(candidate, constants3.X_OK);
|
|
4047
|
+
return candidate;
|
|
4048
|
+
} catch {}
|
|
4049
|
+
}
|
|
4050
|
+
}
|
|
4051
|
+
return;
|
|
4052
|
+
}
|
|
4053
|
+
function openDetached(command, url) {
|
|
4054
|
+
const child = spawn(command[0], [...command.slice(1), url], { stdio: "ignore", detached: true, windowsHide: true });
|
|
4055
|
+
child.on("error", () => {});
|
|
4056
|
+
child.unref();
|
|
4057
|
+
}
|
|
4058
|
+
function runInherited(path, args) {
|
|
4059
|
+
return new Promise((resolve4, reject) => {
|
|
4060
|
+
const child = spawn(path, args, { stdio: "inherit" });
|
|
4061
|
+
child.once("error", reject);
|
|
4062
|
+
child.once("close", (code, signal) => resolve4(code ?? (signal ? 128 + (osConstants.signals[signal] ?? 0) : 1)));
|
|
4063
|
+
});
|
|
4064
|
+
}
|
|
4065
|
+
async function readStdinText(maxChars = Infinity) {
|
|
4066
|
+
process.stdin.setEncoding("utf8");
|
|
4067
|
+
let text = "";
|
|
4068
|
+
for await (const chunk of process.stdin) {
|
|
4069
|
+
text += chunk;
|
|
4070
|
+
if (text.length > maxChars)
|
|
4071
|
+
return text.slice(0, maxChars + 1);
|
|
4072
|
+
}
|
|
4073
|
+
return text;
|
|
4074
|
+
}
|
|
4075
|
+
|
|
4076
|
+
// src/cli.ts
|
|
4077
|
+
var GUIDE = guideText();
|
|
4078
|
+
function matchCommand(commands, rest) {
|
|
4079
|
+
for (let n = Math.min(3, rest.length);n >= 1; n--) {
|
|
4080
|
+
const operation = commands.find((entry) => entry.name === rest.slice(0, n).join(" "));
|
|
4081
|
+
if (operation)
|
|
4082
|
+
return { operation, positionals: rest.slice(n) };
|
|
4083
|
+
}
|
|
4084
|
+
return;
|
|
4085
|
+
}
|
|
4086
|
+
var PROFILE_KEYS = /^(?:(productApiUrls|specs)\.([a-z][a-z0-9-]{0,63})|(registryUrl))$/;
|
|
4087
|
+
function setProfileValue(profile, key, value, env2, stderr) {
|
|
4088
|
+
const match2 = PROFILE_KEYS.exec(key);
|
|
4089
|
+
if (!match2)
|
|
4090
|
+
throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, registryUrl.");
|
|
4091
|
+
const next = { ...profile };
|
|
4092
|
+
if (match2[3]) {
|
|
4093
|
+
if (value === undefined) {
|
|
4094
|
+
delete next.registryUrl;
|
|
4095
|
+
return next;
|
|
4096
|
+
}
|
|
4097
|
+
if (!value.includes("{product}"))
|
|
4098
|
+
throw new CliError("registryUrl must be a URL template containing {product}.");
|
|
4099
|
+
secureUrl(value.replaceAll("{product}", "product"));
|
|
4100
|
+
next.registryUrl = value;
|
|
4101
|
+
return next;
|
|
4102
|
+
}
|
|
4103
|
+
const field = match2[1];
|
|
4104
|
+
const product = match2[2];
|
|
4105
|
+
const map = { ...next[field] ?? {} };
|
|
4106
|
+
if (value === undefined)
|
|
4107
|
+
delete map[product];
|
|
4108
|
+
else if (field === "productApiUrls") {
|
|
4109
|
+
map[product] = safeApiOrigin(value);
|
|
4110
|
+
if (!isTrustedOrigin(map[product], env2))
|
|
4111
|
+
stderr(`Warning: ${map[product]} is outside https://*.prudai.com and localhost. Commands will refuse to send a token there unless PRUDAI_ALLOW_ORIGIN=${map[product]} is set in the environment.`);
|
|
4112
|
+
} else {
|
|
4113
|
+
if (!value.trim())
|
|
4114
|
+
throw new CliError("A spec source must be a path or URL.");
|
|
4115
|
+
if (/^https?:\/\//i.test(value))
|
|
4116
|
+
secureUrl(value);
|
|
4117
|
+
map[product] = /^https?:\/\//i.test(value) ? value : resolvePath(value);
|
|
4118
|
+
}
|
|
4119
|
+
if (Object.keys(map).length)
|
|
4120
|
+
next[field] = map;
|
|
4121
|
+
else
|
|
4122
|
+
delete next[field];
|
|
4123
|
+
return next;
|
|
4124
|
+
}
|
|
4125
|
+
function profileCommand(words, flags, env2, file, save, emit, stderr) {
|
|
4126
|
+
validateFlags(flags, new Set(["json", "profile"]));
|
|
4127
|
+
const [, action, name, value] = words;
|
|
4128
|
+
let selection;
|
|
4129
|
+
try {
|
|
4130
|
+
selection = selectedProfile(env2, file, str(flags, "profile"));
|
|
4131
|
+
} catch (error) {
|
|
4132
|
+
if (!str(flags, "profile") && env2.PRUDAI_PROFILE)
|
|
4133
|
+
throw new CliError(`PRUDAI_PROFILE="${env2.PRUDAI_PROFILE}" is not a valid profile name. Unset it or set it to 1–64 letters, digits, "_" or "-".`, 2, "invalid_profile");
|
|
4134
|
+
throw error;
|
|
4135
|
+
}
|
|
4136
|
+
if (action === "list" && words.length === 2) {
|
|
4137
|
+
const source = str(flags, "profile") ? "flag" : env2.PRUDAI_PROFILE ? "PRUDAI_PROFILE" : file.defaultProfile ? "defaultProfile" : "implicit";
|
|
4138
|
+
emit({
|
|
4139
|
+
active: selection.name,
|
|
4140
|
+
activeExists: selection.exists,
|
|
4141
|
+
activeSource: source,
|
|
4142
|
+
profiles: Object.keys(file.profiles),
|
|
4143
|
+
...!selection.exists && selection.explicit ? { next: `prudai profile create ${selection.name}` } : {}
|
|
4144
|
+
});
|
|
4145
|
+
return 0;
|
|
4146
|
+
}
|
|
4147
|
+
if (action === "create" && name && words.length === 3) {
|
|
4148
|
+
if (!names(name))
|
|
4149
|
+
throw new CliError('Invalid profile name. Use 1–64 letters, digits, "_" or "-".', 2, "invalid_profile");
|
|
4150
|
+
if (Object.hasOwn(file.profiles, name))
|
|
4151
|
+
throw new CliError(`Profile "${name}" already exists. Select it with \`prudai profile use ${name}\`.`, 2, "profile_exists");
|
|
4152
|
+
save({ ...file, profiles: { ...file.profiles, [name]: {} } });
|
|
4153
|
+
emit({ profile: name, status: "created", next: `prudai profile use ${name}, then prudai auth login --profile ${name}` });
|
|
4154
|
+
return 0;
|
|
4155
|
+
}
|
|
4156
|
+
if (action === "use" && name && words.length === 3) {
|
|
4157
|
+
if (!Object.hasOwn(file.profiles, name))
|
|
4158
|
+
throw unknownProfile(name);
|
|
4159
|
+
save({ ...file, defaultProfile: name });
|
|
4160
|
+
if (env2.PRUDAI_PROFILE && env2.PRUDAI_PROFILE !== name)
|
|
4161
|
+
stderr(`Note: PRUDAI_PROFILE=${env2.PRUDAI_PROFILE} is set and still takes precedence in this shell.`);
|
|
4162
|
+
emit({ profile: name, status: "default" });
|
|
4163
|
+
return 0;
|
|
4164
|
+
}
|
|
4165
|
+
if (action === "delete" && name && words.length === 3) {
|
|
4166
|
+
if (!Object.hasOwn(file.profiles, name))
|
|
4167
|
+
throw unknownProfile(name);
|
|
4168
|
+
if (file.profiles[name].login || file.profiles[name].token)
|
|
4169
|
+
throw new CliError(`Profile "${name}" holds a login. Run \`prudai auth logout --profile ${name}\` first, so the session is ended before it is forgotten.`, 2, "profile_has_login");
|
|
4170
|
+
const { [name]: _removed, ...profiles } = file.profiles;
|
|
4171
|
+
const next = { ...file, profiles };
|
|
4172
|
+
if (next.defaultProfile === name)
|
|
4173
|
+
delete next.defaultProfile;
|
|
4174
|
+
save(next);
|
|
4175
|
+
emit({ profile: name, status: "deleted" });
|
|
4176
|
+
return 0;
|
|
4177
|
+
}
|
|
4178
|
+
if (action === "set" && name && value !== undefined && words.length === 4 || action === "unset" && name && words.length === 3) {
|
|
4179
|
+
if (!selection.exists && selection.explicit)
|
|
4180
|
+
throw unknownProfile(selection.name);
|
|
4181
|
+
const profile = setProfileValue(file.profiles[selection.name] ?? {}, name, action === "set" ? value : undefined, env2, stderr);
|
|
4182
|
+
save({ ...file, profiles: { ...file.profiles, [selection.name]: profile } });
|
|
4183
|
+
emit({ profile: selection.name, status: action === "set" ? "set" : "unset", key: name });
|
|
4184
|
+
return 0;
|
|
4185
|
+
}
|
|
4186
|
+
throw new CliError("Usage: prudai profile list | create <name> | use <name> | delete <name> | set <key> <value> | unset <key>");
|
|
4187
|
+
}
|
|
4188
|
+
function systemBrowser(env2) {
|
|
4189
|
+
if (!process.stderr.isTTY)
|
|
4190
|
+
return;
|
|
4191
|
+
const command = process.platform === "darwin" ? ["open"] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler"] : env2.DISPLAY || env2.WAYLAND_DISPLAY ? ["xdg-open"] : undefined;
|
|
4192
|
+
if (!command || !which(command[0]))
|
|
4193
|
+
return;
|
|
4194
|
+
return (url) => openDetached(command, url);
|
|
4195
|
+
}
|
|
4196
|
+
async function processStdin() {
|
|
4197
|
+
if (process.stdin.isTTY)
|
|
4198
|
+
throw new CliError('Refusing to read a token from a terminal. Pipe it: printf %s "$TOKEN" | prudai auth set --stdin', 2, "stdin_required");
|
|
4199
|
+
const text = await readStdinText(8192);
|
|
4200
|
+
if (text.length > 8192)
|
|
4201
|
+
throw new CliError("Expected one refresh token on stdin.", 2, "invalid_refresh_token");
|
|
4202
|
+
return text;
|
|
4203
|
+
}
|
|
4204
|
+
async function defaultRunExternal(binary, args) {
|
|
4205
|
+
const path = which(binary);
|
|
4206
|
+
if (!path)
|
|
4207
|
+
return;
|
|
4208
|
+
return await runInherited(path, args);
|
|
4209
|
+
}
|
|
4210
|
+
var BUILTINS = new Set([
|
|
4211
|
+
"help",
|
|
4212
|
+
"version",
|
|
4213
|
+
"guide",
|
|
4214
|
+
"products",
|
|
4215
|
+
"ops",
|
|
4216
|
+
"describe",
|
|
4217
|
+
"api",
|
|
4218
|
+
"auth",
|
|
4219
|
+
"login",
|
|
4220
|
+
"logout",
|
|
4221
|
+
"whoami",
|
|
4222
|
+
"profile",
|
|
4223
|
+
"approvals",
|
|
4224
|
+
"skill",
|
|
4225
|
+
"mcp",
|
|
4226
|
+
"account",
|
|
4227
|
+
"keys",
|
|
4228
|
+
"tokens",
|
|
4229
|
+
"apps",
|
|
4230
|
+
"credits",
|
|
4231
|
+
"usage",
|
|
4232
|
+
"logs",
|
|
4233
|
+
"invoices",
|
|
4234
|
+
"settings",
|
|
4235
|
+
"kb",
|
|
4236
|
+
"projects",
|
|
4237
|
+
"dossiers",
|
|
4238
|
+
"memos"
|
|
4239
|
+
]);
|
|
4240
|
+
var ALIASES = { login: ["auth", "login"], logout: ["auth", "logout"], whoami: ["auth", "status"] };
|
|
4241
|
+
async function authCommand(words, ctx, options) {
|
|
4242
|
+
const { flags, env: env2, config, file } = ctx;
|
|
4243
|
+
validateFlags(flags, new Set(["json", "profile", "no-browser", "stdin", "reveal", "online", "product", "device-name"]));
|
|
4244
|
+
const action = words[1];
|
|
4245
|
+
if (action === "switch-org")
|
|
4246
|
+
throw new CliError("A Keycloak login belongs to one organisation. To work in another one, use another profile: prudai profile create <name> && prudai auth login --profile <name>.", 2, "not_supported");
|
|
4247
|
+
if (words.length !== 2)
|
|
4248
|
+
throw new CliError("Usage: prudai auth login|status|logout|token [--reveal --product p]|set --stdin|export --reveal");
|
|
4249
|
+
if (action === "set" && !flags.stdin)
|
|
4250
|
+
throw new CliError('The refresh token is read from stdin only: printf %s "$TOKEN" | prudai auth set --stdin');
|
|
4251
|
+
if (flags.stdin && action !== "set")
|
|
4252
|
+
throw new CliError("--stdin belongs to prudai auth set.");
|
|
4253
|
+
if (flags.reveal && action !== "token" && action !== "export")
|
|
4254
|
+
throw new CliError("--reveal belongs to prudai auth token and prudai auth export.");
|
|
4255
|
+
if (flags.online && action !== "status")
|
|
4256
|
+
throw new CliError("--online belongs to prudai auth status.");
|
|
4257
|
+
if (flags.product && action !== "token")
|
|
4258
|
+
throw new CliError("--product belongs to prudai auth token.");
|
|
4259
|
+
const save = options.saveConfig ?? ((cfg) => writeConfig(configPath(env2), cfg));
|
|
4260
|
+
const authOptions = {
|
|
4261
|
+
config,
|
|
4262
|
+
file,
|
|
4263
|
+
save,
|
|
4264
|
+
load: options.readConfig ?? (() => readConfig(configPath(env2))),
|
|
4265
|
+
fetch: ctx.fetch,
|
|
4266
|
+
stderr: ctx.stderr,
|
|
4267
|
+
now: options.now,
|
|
4268
|
+
sleep: options.sleep,
|
|
4269
|
+
env: env2,
|
|
4270
|
+
openBrowser: flags["no-browser"] ? undefined : options.openBrowser ?? (options.env ? undefined : systemBrowser(env2)),
|
|
4271
|
+
readStdin: options.readStdin ?? processStdin,
|
|
4272
|
+
session: ctx.session
|
|
4273
|
+
};
|
|
4274
|
+
if (action === "token" || action === "export") {
|
|
4275
|
+
if (flags.reveal) {
|
|
4276
|
+
if (ctx.json)
|
|
4277
|
+
throw new CliError("--reveal prints the bare credential and cannot be combined with --json.", 2, "validation_error");
|
|
4278
|
+
const secret = action === "export" ? authExport(authOptions) : await revealProductToken(authOptions, str(flags, "product") ?? "prudai");
|
|
4279
|
+
if (action === "export")
|
|
4280
|
+
ctx.stderr("This refresh token is a login for as long as its session lives. Keep it in a secret store; `prudai auth logout` ends the session.");
|
|
4281
|
+
ctx.reveal();
|
|
4282
|
+
ctx.emit(secret, secret);
|
|
4283
|
+
return 0;
|
|
4284
|
+
}
|
|
4285
|
+
if (action === "export")
|
|
4286
|
+
throw new CliError("`prudai auth export` prints a secret: pass --reveal and use it inside a pipe or $(…).", 2, "validation_error");
|
|
4287
|
+
const meta = authToken(authOptions);
|
|
4288
|
+
ctx.emit(localEnvelope(meta, { provenance: { kind: "local" }, notIncluded: ["The secret itself; use --reveal only inside $(…)."] }), JSON.stringify(meta, null, 2));
|
|
4289
|
+
return 0;
|
|
4290
|
+
}
|
|
4291
|
+
const result = action === "login" ? await authLogin(authOptions) : action === "status" ? await authStatus(authOptions, !!flags.online) : action === "logout" ? await authLogout(authOptions) : action === "set" ? await authSet(authOptions) : (() => {
|
|
4292
|
+
throw new CliError("Unknown auth command. Use login, status, logout, token, export or set --stdin.");
|
|
4293
|
+
})();
|
|
4294
|
+
const message2 = result.message;
|
|
4295
|
+
ctx.emit(localEnvelope(result, { provenance: { kind: "auth", origin: config.issuer } }), typeof message2 === "string" ? `${message2}
|
|
4296
|
+
${JSON.stringify(result, null, 2)}` : JSON.stringify(result, null, 2));
|
|
4297
|
+
return 0;
|
|
4298
|
+
}
|
|
4299
|
+
async function productCommand(words, ctx) {
|
|
4300
|
+
const word = words[0];
|
|
4301
|
+
if (!/^[a-z][a-z0-9-]*$/.test(word))
|
|
4302
|
+
throw new CliError("Invalid product or command. Run prudai help.");
|
|
4303
|
+
const catalog = await loadProductCatalog(word, ctx.catalog);
|
|
4304
|
+
throwIfUnusable(catalog);
|
|
4305
|
+
if (catalog.error && !catalog.commands.length)
|
|
4306
|
+
throw new CliError(catalog.error, 2, "unknown_command");
|
|
4307
|
+
for (const warning of catalog.warnings)
|
|
4308
|
+
ctx.stderr(`Warning: ${warning}`);
|
|
4309
|
+
const product = catalog.product;
|
|
4310
|
+
if (words[1] === "help" || ctx.flags.help || words.length === 1) {
|
|
4311
|
+
validateFlags(ctx.flags, GLOBAL_FLAGS);
|
|
4312
|
+
ctx.emit(localEnvelope(catalog.commands, {
|
|
4313
|
+
context: { product, origin: catalog.origin || null },
|
|
4314
|
+
provenance: { kind: "catalog", source: catalog.source ?? null },
|
|
4315
|
+
notIncluded: catalog.warnings,
|
|
4316
|
+
next: [{ action: `prudai describe ${product} <command>`, why: "Parameters, body and examples." }]
|
|
4317
|
+
}), [
|
|
4318
|
+
`prudai ${product} <command> [args] [flags] (${catalog.commands.length} commands; catalogue: ${catalog.source?.kind ?? "none"}${catalog.source?.ref ? ` ${catalog.source.ref}` : ""})`,
|
|
4319
|
+
...catalog.commands.map((entry) => ` ${[entry.name, ...entry.positionals.map((name) => `<${name}>`)].join(" ").padEnd(48)} ${entry.method} ${entry.path} approval: ${entry.approval}`)
|
|
4320
|
+
].join(`
|
|
4321
|
+
`));
|
|
4322
|
+
return 0;
|
|
4323
|
+
}
|
|
4324
|
+
const matched = matchCommand(catalog.commands, words.slice(1));
|
|
4325
|
+
if (!matched)
|
|
4326
|
+
throw new CliError(`Unknown ${product} command. Run prudai ${product} help, or prudai ops search "<words>" --product ${product}.`);
|
|
4327
|
+
return executeOperation(matched.operation, matched.positionals, resolveOrigin(product, ctx, catalog.spec), ctx);
|
|
4328
|
+
}
|
|
4329
|
+
async function runCli(args, options = {}) {
|
|
4330
|
+
const stdout = options.stdout ?? ((text) => console.log(text));
|
|
4331
|
+
const stderr = options.stderr ?? ((text) => console.error(text));
|
|
4332
|
+
const json = args.includes("--json");
|
|
4333
|
+
const secrets = new Set;
|
|
4334
|
+
let revealing = false;
|
|
4335
|
+
const redact = (text) => {
|
|
4336
|
+
if (revealing)
|
|
4337
|
+
return text;
|
|
4338
|
+
let out = text.replace(/prudai_(?:pat|sk_(?:live|test))_[A-Za-z0-9_-]{20,}/g, "[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, "[redacted]");
|
|
4339
|
+
for (const secret of secrets)
|
|
4340
|
+
if (secret.length >= 8)
|
|
4341
|
+
out = out.split(secret).join("[redacted]");
|
|
4342
|
+
return out;
|
|
4343
|
+
};
|
|
4344
|
+
const emit = (value, human) => stdout(redact(json ? JSON.stringify(value) : human ?? JSON.stringify(value, null, 2)));
|
|
4345
|
+
const errOut = (text) => stderr(redact(text));
|
|
4346
|
+
try {
|
|
4347
|
+
const first = args.findIndex((arg) => !arg.startsWith("-"));
|
|
4348
|
+
const word = first === 0 ? args[0] : undefined;
|
|
4349
|
+
if (word && /^[a-z][a-z0-9-]{0,63}$/.test(word) && !BUILTINS.has(word) && !findProduct(word) && !options.plugins?.some((plugin) => plugin.product === word)) {
|
|
4350
|
+
const runExternal = options.runExternal ?? (options.env ? undefined : defaultRunExternal);
|
|
4351
|
+
const code = runExternal ? await runExternal(`prudai-${word}`, args.slice(1)) : undefined;
|
|
4352
|
+
if (code !== undefined)
|
|
4353
|
+
return code === 0 ? 0 : code === 1 ? 1 : 2;
|
|
4354
|
+
}
|
|
4355
|
+
const parsed = parseArgs(args);
|
|
4356
|
+
const flags = parsed.flags;
|
|
4357
|
+
let words = parsed.words;
|
|
4358
|
+
if (words[0] && ALIASES[words[0]])
|
|
4359
|
+
words = [...ALIASES[words[0]], ...words.slice(1)];
|
|
4360
|
+
const command = words[0];
|
|
4361
|
+
if (!command || command === "help" || flags.help && words.length === 1 && !findProduct(command)) {
|
|
4362
|
+
if (command === "help" && words.length !== 1)
|
|
4363
|
+
throw new CliError("Usage: prudai help");
|
|
4364
|
+
validateFlags(flags, GLOBAL_FLAGS);
|
|
4365
|
+
emit(HELP, `${HELP.usage}
|
|
4366
|
+
|
|
4367
|
+
Commands:
|
|
4368
|
+
${HELP.commands.map((line) => ` prudai ${line}`).join(`
|
|
4369
|
+
`)}
|
|
4370
|
+
|
|
4371
|
+
Flags: ${HELP.flags.join(" ")}
|
|
4372
|
+
|
|
4373
|
+
${HELP.credentials}
|
|
4374
|
+
Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth, refused, not available, pending approval)`);
|
|
4375
|
+
return 0;
|
|
4376
|
+
}
|
|
4377
|
+
if (command === "version") {
|
|
4378
|
+
validateFlags(flags, ["json"]);
|
|
4379
|
+
emit(localEnvelope({ name: "prudai", version: VERSION }), VERSION);
|
|
4380
|
+
return 0;
|
|
4381
|
+
}
|
|
4382
|
+
const env2 = options.env ?? process.env;
|
|
4383
|
+
const file = options.readConfig ? options.readConfig() : readConfig(configPath(env2));
|
|
4384
|
+
const save = options.saveConfig ?? ((cfg) => writeConfig(configPath(env2), cfg));
|
|
4385
|
+
if (command === "profile")
|
|
4386
|
+
return profileCommand(words, flags, env2, file, save, (value, human) => emit(localEnvelope(value, { provenance: { kind: "local", source: "profiles" } }), human ?? JSON.stringify(value, null, 2)), errOut);
|
|
4387
|
+
for (const [name, value] of Object.entries(env2))
|
|
4388
|
+
if (value && /^PRUDAI_(?:[A-Z0-9_]+_)?(?:API_KEY|TOKEN|REFRESH_TOKEN)$/.test(name))
|
|
4389
|
+
secrets.add(value);
|
|
4390
|
+
for (const profile of Object.values(file.profiles))
|
|
4391
|
+
for (const secret of [profile.token, profile.login?.refreshToken, profile.login?.accessToken])
|
|
4392
|
+
if (secret)
|
|
4393
|
+
secrets.add(secret);
|
|
4394
|
+
const config = resolveConfig(env2, file, str(flags, "profile"));
|
|
4395
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
4396
|
+
const now = options.now ?? Date.now;
|
|
4397
|
+
const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
4398
|
+
const base = { flags, env: env2, file, config, options };
|
|
4399
|
+
const productWord = command === "describe" ? words[1] : command === "ops" || command === "api" || command === "approvals" ? str(flags, "product") : command;
|
|
4400
|
+
const named = productWord ? findProduct(productWord)?.product ?? productWord : undefined;
|
|
4401
|
+
const catalog = {
|
|
4402
|
+
env: env2,
|
|
4403
|
+
fetch: fetchImpl,
|
|
4404
|
+
now,
|
|
4405
|
+
plugins: options.plugins,
|
|
4406
|
+
refresh: !!flags.refresh,
|
|
4407
|
+
offline: !!flags.offline || env2.PRUDAI_OFFLINE === "1",
|
|
4408
|
+
explicitSpec: (product) => {
|
|
4409
|
+
const profile = file.profiles[config.profile];
|
|
4410
|
+
const registry = str(flags, "registry") ?? env2.PRUDAI_REGISTRY_URL ?? profile?.registryUrl;
|
|
4411
|
+
return (named === product ? str(flags, "spec") ?? env2.PRUDAI_SPEC : undefined) ?? profile?.specs?.[product] ?? (registry ? registry.replaceAll("{product}", encodeURIComponent(product)) : undefined);
|
|
4412
|
+
},
|
|
4413
|
+
originFor: (product) => resolveOrigin(product, base, undefined, named === product),
|
|
4414
|
+
credentialFor: (product) => session.productToken(product),
|
|
4415
|
+
hasLogin: () => session.hasLogin
|
|
4416
|
+
};
|
|
4417
|
+
const reveal = () => {
|
|
4418
|
+
revealing = true;
|
|
4419
|
+
};
|
|
4420
|
+
const session = new Session({ config, file, env: env2, fetch: fetchImpl, now, save, load: options.readConfig ?? (() => readConfig(configPath(env2))), onSecret: (secret) => secrets.add(secret), override: options.credentials });
|
|
4421
|
+
const ctx = { options, env: env2, file, config, flags, json, emit, stderr: errOut, fetch: fetchImpl, now, sleep, catalog, reveal, session };
|
|
4422
|
+
if (command === "auth")
|
|
4423
|
+
return await authCommand(words, ctx, options);
|
|
4424
|
+
if (command === "guide")
|
|
4425
|
+
return await guideCommand(words.slice(1), ctx);
|
|
4426
|
+
if (command === "products")
|
|
4427
|
+
return await productsCommand(words.slice(1), ctx);
|
|
4428
|
+
if (command === "ops")
|
|
4429
|
+
return await opsCommand(words.slice(1), ctx);
|
|
4430
|
+
if (command === "describe")
|
|
4431
|
+
return await describeOperationCommand(words.slice(1), ctx);
|
|
4432
|
+
if (command === "api")
|
|
4433
|
+
return await apiCommand(words.slice(1), ctx);
|
|
4434
|
+
if (command === "approvals")
|
|
4435
|
+
return await approvalsCommand(words.slice(1), ctx);
|
|
4436
|
+
if (command === "skill")
|
|
4437
|
+
return await skillCommand(words.slice(1), ctx);
|
|
4438
|
+
if (command === "mcp" && words[1] !== "connections")
|
|
4439
|
+
return await mcpCommand(words.slice(1), ctx);
|
|
4440
|
+
if (command === "mcp" || PLATFORM_GROUPS.has(command))
|
|
4441
|
+
return await platformCommand(words, ctx);
|
|
4442
|
+
return await productCommand(words, ctx);
|
|
4443
|
+
} catch (error) {
|
|
4444
|
+
const failure = error instanceof CliError ? error : new CliError("Unexpected local or server failure.", 1, "unexpected_error");
|
|
4445
|
+
emit(errorDocument(failure), `Error: ${failure.message}${failure instanceof DetailedCliError ? `
|
|
4446
|
+
${JSON.stringify(failure.details, null, 2)}` : ""}`);
|
|
4447
|
+
return failure.exitCode;
|
|
4448
|
+
}
|
|
4449
|
+
}
|
|
4450
|
+
|
|
4451
|
+
// src/bin.ts
|
|
4452
|
+
process.exitCode = await runCli(process.argv.slice(2));
|