@prudai/cli 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -227,9 +227,61 @@ function parseEnvelope(body) {
227
227
  }
228
228
  return body;
229
229
  }
230
- function renderEnvelope(body) {
230
+ function envelopeRows(data) {
231
+ if (Array.isArray(data))
232
+ return { rows: data };
233
+ if (!isRecord(data))
234
+ return;
235
+ if (Object.hasOwn(data, "id") && (data.id === null || typeof data.id !== "object"))
236
+ return;
237
+ const arrays = Object.entries(data).filter(([, value]) => Array.isArray(value));
238
+ if (arrays.length !== 1)
239
+ return;
240
+ const [key, rows] = arrays[0];
241
+ if (!Array.isArray(rows) || !rows.every(isRecord))
242
+ return;
243
+ const { [key]: _rows, ...metadata } = data;
244
+ return { rows, ...Object.keys(metadata).length ? { metadata } : {} };
245
+ }
246
+ function renderTable(rows) {
247
+ if (!rows.length)
248
+ return "No items.";
249
+ const records = rows.map((row) => isRecord(row) ? row : { value: row });
250
+ const fields = [...new Set(records.flatMap((row) => Object.keys(row)))];
251
+ const priority = ["id", "name", "title", "label", "filename", "file_name", "email", "status", "state", "kind", "type", "code", "reference", "role", "summary", "created_at", "createdAt", "updated_at", "updatedAt"];
252
+ const columns = [...priority.filter((key) => fields.includes(key)), ...fields.filter((key) => !priority.includes(key))].slice(0, 6);
253
+ if (!columns.length)
254
+ return `${rows.length} empty records.`;
255
+ let shortened = fields.length > columns.length;
256
+ const cell = (value) => {
257
+ const text = (value === undefined || value === null ? "-" : typeof value === "string" ? value : JSON.stringify(value)).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
258
+ if (text.length <= 64)
259
+ return text;
260
+ shortened = true;
261
+ return `${text.slice(0, 63)}…`;
262
+ };
263
+ const headings = columns.map((key) => key.replaceAll("_", " ").toUpperCase());
264
+ const cells = records.map((row) => columns.map((key) => cell(row[key])));
265
+ const widths = headings.map((heading) => heading.length);
266
+ for (const row of cells)
267
+ row.forEach((value, index) => {
268
+ widths[index] = Math.max(widths[index], value.length);
269
+ });
270
+ const line = (values) => values.map((value, index) => value.padEnd(widths[index])).join(" ").trimEnd();
271
+ return [
272
+ line(headings),
273
+ line(widths.map((width) => "-".repeat(width))),
274
+ ...cells.map(line),
275
+ ...shortened ? ["Table shows core fields or shortened values; use --json for the full data."] : []
276
+ ].join(`
277
+ `);
278
+ }
279
+ function renderEnvelope(body, options = {}) {
280
+ const collection = options.list === false ? undefined : envelopeRows(body.data);
231
281
  return [
232
- JSON.stringify(body.data, null, 2),
282
+ collection ? renderTable(collection.rows) : JSON.stringify(body.data, null, 2),
283
+ ...collection?.metadata ? [`Data metadata: ${JSON.stringify(collection.metadata)}`] : [],
284
+ ...collection ? [`Returned: ${body.completeness.returned ?? collection.rows.length} | Total: ${body.completeness.total ?? "unknown"} | Truncated: ${body.completeness.truncated === true ? "yes" : body.completeness.truncated === false ? "no" : "not reported"}`] : [],
233
285
  `Context: ${JSON.stringify(body.context)}`,
234
286
  `Completeness: ${JSON.stringify(body.completeness)}`,
235
287
  `Not included: ${JSON.stringify(body.notIncluded)}`,
@@ -311,7 +363,8 @@ var GLOBAL_FLAGS = new Set([
311
363
  "api-url",
312
364
  "data",
313
365
  "idempotency-key",
314
- "if-match"
366
+ "if-match",
367
+ "org"
315
368
  ]);
316
369
  function parseArgs(args) {
317
370
  const words = [];
@@ -322,6 +375,14 @@ function parseArgs(args) {
322
375
  flags.help = true;
323
376
  continue;
324
377
  }
378
+ if (arg === "-v") {
379
+ flags.version = true;
380
+ continue;
381
+ }
382
+ if (arg === "--version" && words.length === 0) {
383
+ flags.version = true;
384
+ continue;
385
+ }
325
386
  if (arg === "-y") {
326
387
  flags.yes = true;
327
388
  continue;
@@ -386,1958 +447,2076 @@ import { dirname, join } from "node:path";
386
447
  // src/openapi.ts
387
448
  import { readFile, stat } from "node:fs/promises";
388
449
  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]);
450
+
451
+ // src/keycloak.ts
452
+ var CLIENT_ID = "prudai-cli";
453
+ var DEVICE_SCOPE = "offline_access";
454
+ var FORM = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
455
+ var record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
456
+ var positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
457
+ var USER_CODE = /^[A-Za-z0-9][A-Za-z0-9-]{2,30}[A-Za-z0-9]$/;
458
+ var JWT = /^[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}$/;
459
+ var TOKEN_SHAPE = /^[A-Za-z0-9._~+/=-]{20,8192}$/;
460
+ function endpoints(issuer, env) {
461
+ let url;
462
+ try {
463
+ url = secureUrl(issuer);
464
+ } catch {
465
+ throw new CliError("The Keycloak issuer must be an https URL (or localhost), without credentials.", 2, "invalid_issuer");
417
466
  }
418
- return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, resolve(doc, item, chain)]));
467
+ if (url.search || url.hash)
468
+ throw new CliError("The Keycloak issuer must be a plain realm URL.", 2, "invalid_issuer");
469
+ requireTrustedOrigin(url.href, env);
470
+ const base = `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
471
+ return { issuer: base, device: `${base}/protocol/openid-connect/auth/device`, token: `${base}/protocol/openid-connect/token`, revoke: `${base}/protocol/openid-connect/revoke` };
419
472
  }
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 "";
473
+ async function postForm(fetchImpl, url, form) {
474
+ let response;
431
475
  try {
432
- return new URL(first.url, "https://server.invalid").pathname.replace(/\/+$/, "");
476
+ response = await fetchImpl(url, { method: "POST", headers: FORM, body: new URLSearchParams(form).toString(), redirect: "error", signal: AbortSignal.timeout(15000) });
433
477
  } catch {
434
- return "";
478
+ throw new CliError("Could not reach the login service; check the network and try again.", 1, "network_error");
435
479
  }
480
+ const text = await response.text();
481
+ let body = {};
482
+ try {
483
+ body = record(text ? JSON.parse(text) : {});
484
+ } catch {}
485
+ return { status: response.status, body, headers: response.headers };
436
486
  }
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("{"))
487
+ function retryAfter(headers, now) {
488
+ const raw = headers.get("retry-after");
489
+ if (!raw)
490
+ return 0;
491
+ const seconds = /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : (Date.parse(raw) - now) / 1000;
492
+ return Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.ceil(seconds), 60) : 0;
493
+ }
494
+ function readClaims(token) {
495
+ if (!JWT.test(token))
441
496
  return;
497
+ let payload;
442
498
  try {
443
- return new URL(first.url).origin;
499
+ payload = record(JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8")));
444
500
  } catch {
445
501
  return;
446
502
  }
503
+ const str2 = (v) => typeof v === "string" && v.length <= 320 ? v : undefined;
504
+ const aud = typeof payload.aud === "string" ? [payload.aud] : Array.isArray(payload.aud) ? payload.aud.filter((v) => typeof v === "string") : undefined;
505
+ return {
506
+ sub: str2(payload.sub),
507
+ exp: typeof payload.exp === "number" ? payload.exp : undefined,
508
+ iat: typeof payload.iat === "number" ? payload.iat : undefined,
509
+ aud,
510
+ azp: str2(payload.azp),
511
+ scope: str2(payload.scope),
512
+ name: str2(payload.name),
513
+ email: str2(payload.email),
514
+ username: str2(payload.preferred_username),
515
+ organizationId: str2(payload.organization_id),
516
+ organizationName: str2(payload.organization_name)
517
+ };
447
518
  }
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;
519
+ function tokensFrom(body, now, previousRefresh) {
520
+ const access = body.access_token;
521
+ const refresh = typeof body.refresh_token === "string" ? body.refresh_token : previousRefresh;
522
+ 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") {
523
+ throw new CliError("Invalid token response from the login service. Nothing was stored.", 1, "invalid_token_response");
524
+ }
525
+ const claims = readClaims(access) ?? {};
526
+ const lifetime = positive(body.expires_in) ? body.expires_in * 1000 : undefined;
527
+ const expiry = claims.exp ? claims.exp * 1000 : lifetime ? now + lifetime : NaN;
528
+ if (!Number.isFinite(expiry) || expiry <= now)
529
+ throw new CliError("Invalid token response from the login service. Nothing was stored.", 1, "invalid_token_response");
530
+ return { accessToken: access, refreshToken: refresh, accessExpiresAt: expiry, claims };
456
531
  }
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");
532
+ async function deviceLogin(issuer, options) {
533
+ const ep = endpoints(issuer, options.env);
534
+ const start = await postForm(options.fetch, ep.device, { client_id: CLIENT_ID, scope: DEVICE_SCOPE });
535
+ if (start.status !== 200) {
536
+ 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");
463
537
  }
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}`));
538
+ const d = start.body;
539
+ 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))
540
+ throw new CliError("Invalid device-login response.", 1, "invalid_device_response");
541
+ const pairing = (raw) => {
542
+ let u;
543
+ try {
544
+ u = new URL(String(raw));
545
+ } catch {
546
+ throw new CliError("Invalid pairing URL.", 1, "invalid_device_response");
547
+ }
548
+ if (u.origin !== new URL(ep.issuer).origin || u.username || u.password || u.hash)
549
+ throw new CliError("The pairing URL does not match the login service.", 1, "invalid_device_response");
550
+ return u.href;
551
+ };
552
+ const verificationUri = pairing(d.verification_uri);
553
+ const openUri = d.verification_uri_complete !== undefined ? pairing(d.verification_uri_complete) : verificationUri;
554
+ options.stderr(`Open ${verificationUri} and enter code ${d.user_code}. Waiting for approval.`);
555
+ if (options.openBrowser) {
556
+ try {
557
+ options.openBrowser(openUri);
558
+ } catch {}
471
559
  }
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]))
560
+ const started = options.now();
561
+ const deadline = started + Math.min(d.expires_in, 900) * 1000;
562
+ let interval = Math.max(typeof d.interval === "number" ? d.interval : 5, 1) * 1000;
563
+ let warned = false;
564
+ while (options.now() < deadline) {
565
+ await options.sleep(Math.min(interval, Math.max(deadline - options.now(), 0)));
566
+ if (options.now() >= deadline)
567
+ break;
568
+ 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) => {
569
+ if (error2 instanceof CliError && error2.exitCode === 1)
570
+ return;
571
+ throw error2;
572
+ });
573
+ if (!poll) {
574
+ if (!warned)
575
+ options.stderr("The login service could not be reached; still waiting.");
576
+ warned = true;
481
577
  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
578
  }
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}`));
579
+ if (poll.status === 200)
580
+ return tokensFrom(poll.body, options.now());
581
+ const error = String(poll.body.error ?? "");
582
+ if (error === "authorization_pending")
583
+ continue;
584
+ if (error === "slow_down" || poll.status === 429) {
585
+ interval += 5000;
586
+ interval = Math.max(interval, retryAfter(poll.headers, options.now()) * 1000);
608
587
  continue;
609
588
  }
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) });
589
+ if (poll.status >= 500) {
590
+ if (!warned)
591
+ options.stderr("The login service is temporarily unavailable; still waiting.");
592
+ warned = true;
593
+ continue;
594
+ }
595
+ if (error === "access_denied")
596
+ throw new CliError("Login was denied in the browser. Run `prudai login` again if that was a mistake.", 2, "access_denied");
597
+ if (error === "expired_token")
598
+ throw new CliError("The device code expired. Run `prudai login` again.", 2, "expired_token");
599
+ throw new CliError("Login failed. Run `prudai login` again.", 2, "login_failed");
612
600
  }
613
- return commands;
601
+ throw new CliError("The device code expired. Run `prudai login` again.", 2, "expired_token");
614
602
  }
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)";
603
+ async function refreshLogin(issuer, refreshToken, options) {
604
+ const ep = endpoints(issuer, options.env);
605
+ const reply = await postForm(options.fetch, ep.token, { grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: refreshToken });
606
+ if (reply.status === 200)
607
+ return tokensFrom(reply.body, options.now(), refreshToken);
608
+ if (reply.status === 400 || reply.status === 401) {
609
+ throw new CliError("Your login is no longer valid (logged out, revoked or idle for too long). Run `prudai login`.", 2, "not_authenticated");
641
610
  }
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
- }));
611
+ throw new CliError(`The login service answered HTTP ${reply.status}; try again in a moment.`, 1, "login_unavailable");
612
+ }
613
+ async function revokeLogin(issuer, refreshToken, options) {
614
+ const ep = endpoints(issuer, options.env);
615
+ const reply = await postForm(options.fetch, ep.revoke, { client_id: CLIENT_ID, token: refreshToken, token_type_hint: "refresh_token" });
616
+ return reply.status;
617
+ }
618
+
619
+ // src/exchange.ts
620
+ var TOKEN_PRODUCTS = ["prudai", "irma", "ordo"];
621
+ function tokenProductFor(product) {
622
+ return product === "irma" ? "irma" : product === "ordo" ? "ordo" : "prudai";
623
+ }
624
+ var PRODUCT_AUDIENCE = { prudai: "prudai-api", irma: "irma-backend", ordo: "ordo-backend" };
625
+ var audienceAllowed = (product, aud) => aud.length === 1 && aud[0] === PRODUCT_AUDIENCE[product];
626
+ var record2 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
627
+ var message = (body) => typeof body.error_description === "string" ? body.error_description.slice(0, 200).replace(/[\u0000-\u001f\u007f]/g, " ") : "";
628
+ function exchangeEndpoint(raw, env) {
629
+ let url;
630
+ try {
631
+ url = secureUrl(raw);
632
+ } catch {
633
+ throw new CliError("The exchange URL must be an https URL (or localhost), without credentials.", 2, "invalid_exchange_url");
648
634
  }
649
- return out;
635
+ if (url.search)
636
+ throw new CliError("The exchange URL must not carry a query string.", 2, "invalid_exchange_url");
637
+ requireTrustedOrigin(url.href, env);
638
+ return url.href;
650
639
  }
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
- }
640
+ async function exchangeToken(options) {
641
+ const url = exchangeEndpoint(options.url, options.env);
642
+ let response;
643
+ try {
644
+ response = await options.fetch(url, {
645
+ method: "POST",
646
+ redirect: "error",
647
+ signal: AbortSignal.timeout(15000),
648
+ headers: { authorization: `Bearer ${options.loginToken}`, "content-type": "application/x-www-form-urlencoded", accept: "application/json", "x-prudai-agent": "prudai-cli" },
649
+ body: new URLSearchParams({ product: options.product }).toString()
650
+ });
651
+ } catch {
652
+ throw new CliError("Could not reach the token broker; check the network and try again.", 1, "exchange_unavailable");
681
653
  }
682
- if (text.charCodeAt(0) === 65279)
683
- text = text.slice(1);
654
+ const text = await response.text();
655
+ let body = {};
684
656
  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");
657
+ body = record2(text ? JSON.parse(text) : {});
658
+ } catch {}
659
+ const status = response.status;
660
+ if (status === 200) {
661
+ const token = body.access_token;
662
+ const claims = typeof token === "string" ? readClaims(token) : undefined;
663
+ const lifetime = body.expires_in;
664
+ 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) {
665
+ throw new CliError("Invalid answer from the token broker. Nothing was used.", 1, "invalid_exchange_response");
666
+ }
667
+ if (!audienceAllowed(options.product, claims.aud))
668
+ throw new CliError("The token broker returned a token for another audience than this product. Nothing was used.", 1, "invalid_exchange_response");
669
+ const expiry = Math.min(options.now() + lifetime * 1000, claims.exp ? claims.exp * 1000 : Infinity);
670
+ return { token, expiresAt: expiry, audience: claims.aud[0] };
691
671
  }
672
+ const code = String(body.error ?? "");
673
+ if (status === 401)
674
+ throw new CliError("invalid_token", 2, "invalid_token");
675
+ if (status === 403)
676
+ throw new CliError(`Access to ${options.product} is not allowed for this login${message(body) ? `: ${message(body)}` : ""}.`, 2, "access_denied");
677
+ if (status === 400)
678
+ throw new CliError(`The token broker refused the request${code ? ` (${code})` : ""}.`, 2, code === "unknown_product" ? "unknown_product" : "invalid_request");
679
+ if (status === 429) {
680
+ const wait = Number(response.headers.get("retry-after"));
681
+ 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");
682
+ }
683
+ throw new CliError(`The token broker is unavailable (HTTP ${status}); try again in a moment.`, 1, "exchange_unavailable");
692
684
  }
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}`);
685
+
686
+ // src/session.ts
687
+ var SKEW_MS = 30000;
688
+
689
+ class Session {
690
+ o;
691
+ login;
692
+ products = new Map;
693
+ pending = new Map;
694
+ constructor(o) {
695
+ this.o = o;
696
+ const stored = o.file.profiles[o.config.profile]?.login;
697
+ this.login = { refreshToken: o.config.refreshToken };
698
+ if (o.config.refreshSource === "file" && stored) {
699
+ this.login.accessToken = stored.accessToken;
700
+ this.login.accessExpiresAt = stored.accessExpiresAt;
731
701
  }
702
+ for (const secret of [o.config.refreshToken, this.login.accessToken])
703
+ if (secret)
704
+ o.onSecret?.(secret);
732
705
  }
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
- }
706
+ get hasLogin() {
707
+ return !!this.login.refreshToken || !!this.o.override;
761
708
  }
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");
709
+ get cachedLoginToken() {
710
+ return this.login.accessToken;
768
711
  }
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
- }
712
+ get refreshTokenValue() {
713
+ return this.login.refreshToken;
785
714
  }
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);
715
+ once(key, work) {
716
+ const running = this.pending.get(key);
717
+ if (running)
718
+ return running;
719
+ const promise = work().finally(() => this.pending.delete(key));
720
+ this.pending.set(key, promise);
721
+ return promise;
800
722
  }
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());
723
+ async loginToken(force = false) {
724
+ const { accessToken, accessExpiresAt, refreshToken } = this.login;
725
+ if (!refreshToken)
726
+ throw notAuthenticated();
727
+ if (!force && accessToken && accessExpiresAt && accessExpiresAt - SKEW_MS > this.o.now())
728
+ return accessToken;
729
+ return this.once("login", async () => {
730
+ const tokens = await refreshLogin(this.o.config.issuer, refreshToken, { fetch: this.o.fetch, env: this.o.env, now: this.o.now });
731
+ this.adopt(tokens);
732
+ return tokens.accessToken;
733
+ });
806
734
  }
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
- }
735
+ adopt(tokens) {
736
+ const startedFrom = this.login?.refreshToken ?? this.o.config.refreshToken;
737
+ this.login = { accessToken: tokens.accessToken, accessExpiresAt: tokens.accessExpiresAt, refreshToken: tokens.refreshToken };
738
+ this.o.onSecret?.(tokens.accessToken);
739
+ this.o.onSecret?.(tokens.refreshToken);
740
+ if (this.o.config.refreshSource !== "file")
741
+ return;
742
+ try {
743
+ const latest = this.o.load ? this.o.load() : this.o.file;
744
+ const profile = latest.profiles[this.o.config.profile];
745
+ if (!profile?.login || profile.login.refreshToken !== startedFrom)
746
+ return;
747
+ const login = { ...profile.login, refreshToken: tokens.refreshToken, accessToken: tokens.accessToken, accessExpiresAt: tokens.accessExpiresAt };
748
+ this.o.save({ ...latest, profiles: { ...latest.profiles, [this.o.config.profile]: { ...profile, login } } });
749
+ } catch {}
750
+ }
751
+ async productToken(product) {
752
+ if (this.o.override) {
753
+ const token = await this.o.override.productToken(product);
754
+ if (!token)
755
+ throw notAuthenticated();
756
+ this.o.onSecret?.(token);
757
+ return token;
820
758
  }
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}`);
759
+ const wanted = tokenProductFor(product);
760
+ const cached = this.products.get(wanted);
761
+ if (cached && cached.expiresAt - SKEW_MS > this.o.now())
762
+ return cached.token;
763
+ return this.once(`product:${wanted}`, async () => {
764
+ let login = await this.loginToken();
765
+ const ask = () => exchangeToken({ fetch: this.o.fetch, env: this.o.env, now: this.o.now, url: this.o.config.exchangeUrl, loginToken: login, product: wanted });
766
+ let result;
767
+ try {
768
+ result = await ask();
769
+ } catch (error) {
770
+ if (!(error instanceof CliError && error.code === "invalid_token"))
771
+ throw error;
772
+ login = await this.loginToken(true);
773
+ try {
774
+ result = await ask();
775
+ } catch (again) {
776
+ if (again instanceof CliError && again.code === "invalid_token")
777
+ throw notAuthenticated("The login was rejected by the token broker.");
778
+ throw again;
779
+ }
780
+ }
781
+ this.products.set(wanted, { token: result.token, expiresAt: result.expiresAt });
782
+ this.o.onSecret?.(result.token);
783
+ return result.token;
784
+ });
825
785
  }
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");
786
+ forget(product) {
787
+ this.products.delete(tokenProductFor(product));
832
788
  }
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 };
789
+ }
790
+ function notAuthenticated(why) {
791
+ return new CliError(`${why ? `${why} ` : ""}Not logged in. Run \`prudai login\`.`, 2, "not_authenticated");
792
+ }
793
+ function loginClaims(session) {
794
+ const token = session.cachedLoginToken;
795
+ return token ? readClaims(token) : undefined;
836
796
  }
837
797
 
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"
798
+ // src/organization.ts
799
+ function organizationDeclaration(spec) {
800
+ const raw = isRecord(spec) ? spec["x-prudai-organization"] : undefined;
801
+ if (raw === undefined)
802
+ return;
803
+ if (!isRecord(raw) || typeof raw.header !== "string" || !/^x-[a-z0-9-]+$/i.test(raw.header) || /^x-prudai-(?:agent$|approval)/i.test(raw.header) || raw.description !== undefined && typeof raw.description !== "string") {
804
+ throw new CliError("Invalid x-prudai-organization: header must start with x-, contain only letters, digits and hyphens, and may not replace a CLI transport or approval header.", 2, "invalid_spec");
805
+ }
806
+ return { header: raw.header, ...typeof raw.description === "string" ? { description: raw.description } : {} };
807
+ }
808
+ function organizationChoice(product, ctx, useFlag = true) {
809
+ const flag = useFlag ? str(ctx.flags, "org") : undefined;
810
+ const environment = ctx.env[`PRUDAI_${product.toUpperCase().replaceAll("-", "_")}_ORG`];
811
+ const profile = ctx.config.orgs?.[product];
812
+ const login = (ctx.session ? loginClaims(ctx.session)?.organizationId : undefined) ?? (ctx.config.refreshSource !== "env" ? ctx.config.organization?.id ?? undefined : undefined);
813
+ const id = flag ?? environment ?? profile ?? login;
814
+ if (id === undefined)
815
+ return;
816
+ if (!id.trim() || /[^\x21-\x7e]/.test(id))
817
+ throw new CliError("Organization id must be a non-empty value without spaces or control characters.", 2, "invalid_parameter");
818
+ return { id, product, source: flag !== undefined ? "flag" : environment !== undefined ? "environment" : profile !== undefined ? "profile" : "login" };
819
+ }
820
+ function organizationHeaders(product, declaration, ctx) {
821
+ const choice = organizationChoice(product, ctx);
822
+ if (!declaration && choice && choice.source !== "login") {
823
+ throw new CliError(`${product} does not declare organization selection (x-prudai-organization). Remove --org, PRUDAI_${product.toUpperCase().replaceAll("-", "_")}_ORG or profile orgs.${product}; nothing was sent.`, 2, "organization_not_supported");
866
824
  }
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));
825
+ if (choice)
826
+ ctx.selection.organization = choice;
827
+ return declaration && choice && choice.source !== "login" ? { [declaration.header]: choice.id } : {};
873
828
  }
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;
829
+ function assertOrganizationMatches(body, selected, mayHaveWritten = false, contextOperation = false) {
830
+ if (!selected || !isRecord(body))
831
+ return;
832
+ const contextOrg = isRecord(body.context) && isRecord(body.context.organization) ? body.context.organization.id : undefined;
833
+ const dataOrg = contextOperation && isRecord(body.data) && isRecord(body.data.organization) ? body.data.organization.id : undefined;
834
+ if (selected.source === "login") {
835
+ const actual = typeof contextOrg === "string" ? contextOrg : dataOrg;
836
+ if (typeof actual === "string")
837
+ selected.id = actual;
838
+ return;
839
+ }
840
+ for (const received of [contextOrg, dataOrg]) {
841
+ if (typeof received !== "string" || received === selected.id)
842
+ continue;
843
+ throw new CliError(`Organization mismatch: chosen ${selected.id}, received ${received}. Response data was not shown.${mayHaveWritten ? " The action may have been executed in the other organization. Check state before retrying." : ""}`, 2, "organization_mismatch");
884
844
  }
885
- return;
886
845
  }
887
- function bundledManifest() {
888
- if (!manifestCache) {
889
- const path = bundledPath("manifest.json");
890
- manifestCache = path ? JSON.parse(readFileSync(path, "utf8")) : { products: {} };
846
+
847
+ // src/openapi.ts
848
+ function object(value, label) {
849
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
850
+ throw new CliError(`Invalid OpenAPI ${label}`, 2, "invalid_spec");
891
851
  }
892
- return manifestCache;
852
+ return value;
893
853
  }
894
- function readBundledJson(name) {
895
- const path = bundledPath(name);
896
- return path ? JSON.parse(readFileSync(path, "utf8")) : undefined;
854
+ function resolve(doc, value, chain = []) {
855
+ if (Array.isArray(value))
856
+ return value.map((item) => resolve(doc, item, chain));
857
+ if (!value || typeof value !== "object")
858
+ return value;
859
+ const node = value;
860
+ if (typeof node.$ref === "string") {
861
+ const ref = node.$ref;
862
+ if (!ref.startsWith("#/"))
863
+ throw new CliError("External OpenAPI references are not supported", 2, "invalid_spec");
864
+ if (chain.includes(ref))
865
+ throw new CliError(`Cyclic OpenAPI reference: ${ref}`, 2, "invalid_spec");
866
+ let target = doc;
867
+ for (const part of ref.slice(2).split("/")) {
868
+ const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
869
+ const record3 = object(target, `reference ${ref}`);
870
+ if (!Object.hasOwn(record3, key))
871
+ throw new CliError(`Unresolved OpenAPI reference: ${ref}`, 2, "invalid_spec");
872
+ target = record3[key];
873
+ }
874
+ const { $ref: _ref, ...siblings } = node;
875
+ return resolve(doc, { ...object(target, `reference ${ref}`), ...siblings }, [...chain, ref]);
876
+ }
877
+ return Object.fromEntries(Object.entries(node).map(([key, item]) => [key, resolve(doc, item, chain)]));
897
878
  }
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;
879
+ var APPROVALS = new Set(["none", "instruct", "confirm", "review", "forbidden_for_agents"]);
880
+ var METHODS = new Set(["get", "post", "put", "patch", "delete"]);
881
+ var PAGINATION = new Set(["limit", "offset", "cursor", "after", "page", "page_size", "pageSize", "per_page"]);
882
+ var WORD = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
883
+ var PARAM = /^\{[^}]+\}$/;
884
+ var RESERVED_FIRST = new Set(["auth", "help"]);
885
+ function serverBasePath(spec) {
886
+ const servers = spec?.servers;
887
+ const first = Array.isArray(servers) ? servers[0] : undefined;
888
+ if (!first || typeof first.url !== "string" || first.url.includes("{"))
889
+ return "";
890
+ try {
891
+ return new URL(first.url, "https://server.invalid").pathname.replace(/\/+$/, "");
892
+ } catch {
893
+ return "";
894
+ }
904
895
  }
905
- function readCache(env, product) {
906
- const dir = cacheDir(env);
907
- if (!dir)
896
+ function serverOrigin(spec) {
897
+ const servers = spec?.servers;
898
+ const first = Array.isArray(servers) ? servers[0] : undefined;
899
+ if (!first || typeof first.url !== "string" || !/^https?:\/\//i.test(first.url) || first.url.includes("{"))
908
900
  return;
909
901
  try {
910
- return JSON.parse(readFileSync(join(dir, "specs", `${product}.json`), "utf8"));
902
+ return new URL(first.url).origin;
911
903
  } catch {
912
904
  return;
913
905
  }
914
906
  }
915
- function writeCache(env, product, entry) {
916
- const dir = cacheDir(env);
917
- if (!dir)
907
+ function annotatedWords(value, label) {
908
+ if (value === undefined)
918
909
  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";
910
+ const command = typeof value === "string" ? value : value && typeof value === "object" && !Array.isArray(value) ? value.command : undefined;
911
+ const words = typeof command === "string" ? command.trim().split(/\s+/) : [];
912
+ if (!words.length || words.length > 3 || !words.every((word) => WORD.test(word)))
913
+ throw new CliError(`Invalid x-prudai-cli: ${label}`, 2, "invalid_spec");
914
+ return words;
929
915
  }
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})` };
916
+ function generateCommands(product, spec, options = {}) {
917
+ if (!/^[a-z][a-z0-9-]*$/.test(product))
918
+ throw new CliError("Invalid product name", 2, "invalid_spec");
919
+ const doc = object(spec, "document");
920
+ const organization = organizationDeclaration(doc);
921
+ if (typeof doc.openapi !== "string" || !/^3\.1\./.test(doc.openapi)) {
922
+ throw new CliError("Expected an OpenAPI 3.1 specification", 2, "invalid_spec");
948
923
  }
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)" } } : {};
924
+ const base = serverBasePath(doc);
925
+ const items = new Map;
926
+ for (const [specPath, item] of Object.entries(object(doc.paths, "paths"))) {
927
+ const path = `${base}${specPath}`;
928
+ if (!path.startsWith("/v1/"))
929
+ continue;
930
+ items.set(path, object(resolve(doc, item), `path ${specPath}`));
951
931
  }
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
- }
932
+ const hasItemChild = (path) => [...items.keys()].some((other) => other.startsWith(`${path}/{`));
933
+ const itemHasPatch = (path) => [...items].some(([other, item]) => other.startsWith(`${path}/{`) && !other.slice(path.length + 1).includes("/") && ("patch" in item));
934
+ const drafts = [];
935
+ for (const [path, pathItem] of items) {
936
+ const segments = path.slice(4).split("/");
937
+ const statics = segments.filter((part) => !PARAM.test(part));
938
+ if (!statics.length || !statics.every((word) => WORD.test(word)))
939
+ throw new CliError(`Invalid resource path: ${path}`, 2, "invalid_spec");
940
+ if (RESERVED_FIRST.has(statics[0]))
941
+ continue;
942
+ const endsWithParam = PARAM.test(segments.at(-1));
943
+ const last = statics.at(-1);
944
+ for (const [method, rawOperation] of Object.entries(pathItem)) {
945
+ if (!METHODS.has(method))
946
+ continue;
947
+ const op = object(rawOperation, `operation ${method} ${path}`);
948
+ const write = method !== "get";
949
+ const approvalValue = op["x-prudai-approval"];
950
+ let approval = typeof approvalValue === "string" ? approvalValue : approvalValue && typeof approvalValue === "object" ? approvalValue.level : write ? undefined : "none";
951
+ let approvalSource = "spec";
952
+ if (approvalValue === undefined && write && options.lenientApproval) {
953
+ approval = method === "delete" ? "review" : "confirm";
954
+ approvalSource = "default";
984
955
  }
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 };
956
+ if (typeof approval !== "string" || !APPROVALS.has(approval)) {
957
+ throw new CliError(`Missing or invalid x-prudai-approval: ${method.toUpperCase()} ${path}`, 2, "invalid_spec");
1036
958
  }
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;
959
+ const parameters = new Map;
960
+ for (const candidate of [...Array.isArray(pathItem.parameters) ? pathItem.parameters : [], ...Array.isArray(op.parameters) ? op.parameters : []]) {
961
+ const parameter = object(candidate, "parameter");
962
+ if (typeof parameter.name !== "string" || typeof parameter.in !== "string")
963
+ throw new CliError("Invalid OpenAPI parameter", 2, "invalid_spec");
964
+ parameters.set(`${parameter.in}:${parameter.name}`, parameter);
965
+ }
966
+ const params = [...parameters.values()];
967
+ const all = statics.join("-");
968
+ const hasParam = segments.some((part) => PARAM.test(part));
969
+ const firstLast = statics.length === 1 ? [statics[0]] : hasParam ? [statics.slice(0, -1).join("-"), last] : [statics[0], last];
970
+ const allButLast = statics.length === 1 ? [last] : [statics.slice(0, -1).join("-"), last];
971
+ let kind;
972
+ let preferred;
973
+ let fallback;
974
+ if (method === "get") {
975
+ const collection = hasItemChild(path) || "post" in pathItem || statics.length === 1 && params.some((p) => p.in === "query" && PAGINATION.has(p.name));
976
+ if (endsWithParam) {
977
+ kind = "get";
978
+ preferred = fallback = [all, "get"];
979
+ } else if (collection) {
980
+ kind = "list";
981
+ preferred = fallback = [all, "list"];
982
+ } else {
983
+ kind = "read";
984
+ preferred = firstLast;
985
+ fallback = allButLast;
1104
986
  }
987
+ } else if (method === "post") {
988
+ const collection = !endsWithParam && (statics.length === 1 || hasItemChild(path) || ("get" in pathItem));
989
+ if (collection) {
990
+ kind = "create";
991
+ preferred = fallback = [all, "create"];
992
+ } else if (endsWithParam) {
993
+ kind = "action";
994
+ preferred = fallback = [all, "post"];
995
+ } else {
996
+ kind = last === "restore" ? "restore" : "action";
997
+ preferred = firstLast;
998
+ fallback = allButLast;
999
+ }
1000
+ } else if (method === "delete") {
1001
+ kind = "delete";
1002
+ preferred = fallback = [all, "delete"];
1003
+ } else if (method === "put" && (("patch" in pathItem) || !endsWithParam && itemHasPatch(path))) {
1004
+ kind = "replace";
1005
+ preferred = fallback = [all, "replace"];
1006
+ } else {
1007
+ kind = "update";
1008
+ preferred = fallback = [all, "update"];
1105
1009
  }
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 });
1010
+ const label = `${method.toUpperCase()} ${path}`;
1011
+ const pinned = annotatedWords(op["x-prudai-cli"], label);
1012
+ if (pinned)
1013
+ preferred = fallback = pinned;
1014
+ const operationId = typeof op.operationId === "string" ? op.operationId : `${method} ${path}`;
1015
+ const body = op.requestBody ? object(op.requestBody, "request body") : undefined;
1016
+ const content = body?.content ? object(body.content, "request content") : undefined;
1017
+ const jsonBody = content?.["application/json"] ? object(content["application/json"], "JSON request content") : undefined;
1018
+ const multipart = !jsonBody && !!content?.["multipart/form-data"];
1019
+ const security = op.security ?? doc.security;
1020
+ const securityScopes = Array.isArray(security) ? security.flatMap((requirement) => Object.values(object(requirement, "security")).flatMap((values) => Array.isArray(values) ? values.filter((v) => typeof v === "string") : [])) : [];
1021
+ const explicitScopes = typeof op["x-prudai-scope"] === "string" ? [op["x-prudai-scope"]] : op["x-prudai-scopes"];
1022
+ if (explicitScopes !== undefined && (!Array.isArray(explicitScopes) || !explicitScopes.every((value) => typeof value === "string"))) {
1023
+ throw new CliError(`Invalid x-prudai-scopes: ${label}`, 2, "invalid_spec");
1155
1024
  }
1025
+ const scopes = [...new Set([...securityScopes, ...explicitScopes ?? []])];
1026
+ const placeholders = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
1027
+ const requiredQuery = params.filter((p) => p.in === "query" && p.required === true).map((p) => p.name);
1028
+ const declaresKey = params.some((p) => p.in === "header" && p.name.toLowerCase() === "idempotency-key");
1029
+ 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;
1030
+ drafts.push({ preferred, fallback, pinned: !!pinned, command: {
1031
+ product,
1032
+ ...organization ? { organization } : {},
1033
+ kind,
1034
+ method: method.toUpperCase(),
1035
+ path,
1036
+ operationId,
1037
+ summary: typeof op.summary === "string" ? op.summary : operationId,
1038
+ approval,
1039
+ parameters: params,
1040
+ positionals: [...placeholders, ...requiredQuery],
1041
+ idempotencyKey: write,
1042
+ idempotencyDeclared: write && declaresKey,
1043
+ dryRun: write && declaresDryRun,
1044
+ ...jsonBody?.schema !== undefined ? { inputSchema: jsonBody.schema } : {},
1045
+ ...body?.required === true && !multipart ? { bodyRequired: true } : {},
1046
+ ...multipart ? { multipart: true } : {},
1047
+ ...scopes.length ? { scopes } : {},
1048
+ ...approvalSource === "default" ? { approvalSource } : {},
1049
+ ...describeOperation(doc, op, scopes)
1050
+ } });
1156
1051
  }
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
1052
  }
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.`]
1053
+ const count = new Map;
1054
+ for (const draft of drafts)
1055
+ count.set(draft.preferred.join(" "), (count.get(draft.preferred.join(" ")) ?? 0) + 1);
1056
+ const named = drafts.map((draft) => {
1057
+ const words = !draft.pinned && count.get(draft.preferred.join(" ")) > 1 ? draft.fallback : draft.preferred;
1058
+ return { draft, words, name: words.join(" ") };
1215
1059
  });
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;
1060
+ const byName = new Map;
1061
+ for (const entry of named)
1062
+ byName.set(entry.name, [...byName.get(entry.name) ?? [], entry]);
1063
+ const commands = [];
1064
+ for (const [name, entries] of byName) {
1065
+ if (entries.length > 1) {
1066
+ if (!options.onAmbiguous)
1067
+ throw new CliError(`Ambiguous generated command: ${product} ${name}. Pin names with x-prudai-cli.`, 2, "invalid_spec");
1068
+ options.onAmbiguous(name, entries.map(({ draft: draft2 }) => `${draft2.command.method} ${draft2.command.path}`));
1069
+ continue;
1294
1070
  }
1295
- throw new CliError(`Approval request ${opts.id} is ${status}; nothing was executed.`, 2, `approval_${status}`);
1071
+ const { draft, words } = entries[0];
1072
+ commands.push({ ...draft.command, name, words, resource: words.length === 1 ? words[0] : words.slice(0, -1).join(" "), action: words.length === 1 ? "" : words.at(-1) });
1296
1073
  }
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;
1074
+ return commands;
1312
1075
  }
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;
1076
+ function describeOperation(doc, op, scopes) {
1077
+ const out = {};
1078
+ if (typeof op.description === "string" && op.description.trim())
1079
+ out.description = op.description.trim();
1080
+ if (Array.isArray(op.tags)) {
1081
+ const tags = op.tags.filter((tag) => typeof tag === "string");
1082
+ if (tags.length)
1083
+ out.tags = tags;
1347
1084
  }
1348
- if (action === "wait") {
1349
- return waitForApproval(ctx, { ...t, id: idOf(id), execute: !!ctx.flags.execute, timeoutSeconds: intFlag(ctx.flags, "timeout", 600, 5, 3600) });
1085
+ if (typeof op["x-prudai-status"] === "string")
1086
+ out.status = op["x-prudai-status"];
1087
+ if (op.deprecated === true)
1088
+ out.deprecated = true;
1089
+ const explicit = op["x-prudai-cost"] ?? op["x-prudai-credits"];
1090
+ if (typeof explicit === "string" || typeof explicit === "number")
1091
+ out.cost = String(explicit);
1092
+ else if (explicit && typeof explicit === "object")
1093
+ out.cost = JSON.stringify(explicit);
1094
+ else {
1095
+ const objects = doc["x-prudai-scope-objects"] && typeof doc["x-prudai-scope-objects"] === "object" ? doc["x-prudai-scope-objects"] : {};
1096
+ const spends = scopes.some((scope) => {
1097
+ const entry = objects[scope.split(":").slice(0, 2).join(":")];
1098
+ return typeof entry?.description === "string" && /spends credits/i.test(entry.description);
1099
+ });
1100
+ if (spends)
1101
+ out.cost = "credits (metered)";
1350
1102
  }
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;
1103
+ if (op.responses && typeof op.responses === "object") {
1104
+ out.responses = Object.entries(op.responses).map(([status, response]) => ({
1105
+ status,
1106
+ description: response && typeof response === "object" && typeof response.description === "string" ? response.description.trim().split(`
1107
+ `)[0] : ""
1108
+ }));
1359
1109
  }
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);
1110
+ return out;
1111
+ }
1112
+ var MAX_SPEC_BYTES = 32 * 1024 * 1024;
1113
+ var specTooLarge = () => new CliError(`Specification is larger than ${MAX_SPEC_BYTES / 1024 / 1024} MB`, 2, "invalid_spec");
1114
+ async function loadSpec(source, fetchImpl = fetch) {
1115
+ let text;
1116
+ if (/^https?:\/\//i.test(source)) {
1117
+ const url = secureUrl(source);
1118
+ try {
1119
+ const response = await fetchImpl(url, { redirect: "error", signal: AbortSignal.timeout(15000) });
1120
+ if (!response.ok)
1121
+ throw new CliError(`Could not load specification (HTTP ${response.status})`, response.status >= 400 && response.status < 500 ? 2 : 1, "spec_fetch_failed");
1122
+ if (Number(response.headers.get("content-length")) > MAX_SPEC_BYTES)
1123
+ throw specTooLarge();
1124
+ text = await response.text();
1125
+ if (text.length > MAX_SPEC_BYTES)
1126
+ throw specTooLarge();
1127
+ } catch (error) {
1128
+ if (error instanceof CliError)
1129
+ throw error;
1130
+ throw new CliError("Could not fetch specification", 1, "spec_fetch_failed");
1131
+ }
1132
+ } else {
1133
+ try {
1134
+ if ((await stat(source)).size > MAX_SPEC_BYTES)
1135
+ throw specTooLarge();
1136
+ text = await readFile(source, "utf8");
1137
+ } catch (error) {
1138
+ if (error instanceof CliError)
1139
+ throw error;
1140
+ throw new CliError("Could not read specification file", 2, "invalid_spec");
1141
+ }
1142
+ }
1143
+ if (text.charCodeAt(0) === 65279)
1144
+ text = text.slice(1);
1397
1145
  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.`);
1146
+ const parsed = text.trimStart().startsWith("{") ? JSON.parse(text) : parseYaml(text, { logLevel: "error", merge: true, uniqueKeys: false });
1147
+ return object(parsed, "document");
1403
1148
  } catch (error) {
1404
1149
  if (error instanceof CliError)
1405
1150
  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}.`);
1151
+ throw new CliError("Specification must contain valid JSON or YAML", 2, "invalid_spec");
1421
1152
  }
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);
1153
+ }
1154
+ function isSafeHeaderName(name) {
1155
+ 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);
1156
+ }
1157
+ function validateInput(value, schema, label) {
1158
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
1159
+ return;
1160
+ const node = schema;
1161
+ const invalid = (detail) => {
1162
+ throw new CliError(`Invalid ${label}: ${detail}`, 2, "invalid_parameter");
1163
+ };
1164
+ const types = Array.isArray(node.type) ? node.type : node.type ? [node.type] : [];
1165
+ if (types.length && !types.some((type) => {
1166
+ if (type === "null")
1167
+ return value === null;
1168
+ if (type === "array")
1169
+ return Array.isArray(value);
1170
+ if (type === "object")
1171
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1172
+ if (type === "integer")
1173
+ return typeof value === "number" && Number.isInteger(value);
1174
+ if (type === "number")
1175
+ return typeof value === "number" && Number.isFinite(value);
1176
+ return typeof value === type;
1177
+ }))
1178
+ invalid(`expected ${types.join(" or ")}`);
1179
+ if (Array.isArray(node.enum) && !node.enum.some((candidate) => JSON.stringify(candidate) === JSON.stringify(value)))
1180
+ invalid("value is outside enum");
1181
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
1182
+ const record3 = value;
1183
+ if (Array.isArray(node.required)) {
1184
+ for (const key of node.required)
1185
+ if (typeof key === "string" && !Object.hasOwn(record3, key))
1186
+ invalid(`missing required field ${key}`);
1187
+ }
1188
+ if (node.properties && typeof node.properties === "object" && !Array.isArray(node.properties)) {
1189
+ for (const [key, child] of Object.entries(node.properties))
1190
+ if (Object.hasOwn(record3, key))
1191
+ validateInput(record3[key], child, `${label}.${key}`);
1192
+ }
1442
1193
  }
1194
+ if (Array.isArray(value) && node.items)
1195
+ value.forEach((item, index) => validateInput(item, node.items, `${label}[${index}]`));
1443
1196
  }
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");
1197
+ function buildOperationRequest(command, args = {}) {
1198
+ if (command.approval === "forbidden_for_agents")
1199
+ throw new CliError("This operation is forbidden for agents; use the app", 2, "forbidden_for_agents");
1200
+ if (command.bodyRequired && args.body === undefined)
1201
+ throw new CliError("Missing required request body; use --data", 2, "missing_parameter");
1202
+ if (args.body !== undefined)
1203
+ validateInput(args.body, command.inputSchema, "request body");
1204
+ const placeholders = [...command.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
1205
+ const path = command.path.replace(/\{([^}]+)\}/g, (_match, name) => {
1206
+ const value = args.params?.[name] ?? (name === "id" || placeholders.length === 1 ? args.id : undefined);
1207
+ if (!value)
1208
+ throw new CliError(`Missing path parameter: ${name}`, 2, "missing_parameter");
1209
+ if (value === "." || value === "..")
1210
+ throw new CliError(`Invalid path parameter: ${name}`, 2, "invalid_parameter");
1211
+ return encodeURIComponent(value);
1212
+ });
1213
+ const query = new URLSearchParams;
1214
+ for (const [name, value] of Object.entries(args.query ?? {})) {
1215
+ if (value === undefined || value === null)
1216
+ continue;
1217
+ for (const item of Array.isArray(value) ? value : [value]) {
1218
+ if (!["string", "number", "boolean"].includes(typeof item))
1219
+ throw new CliError(`Invalid query parameter: ${name}`, 2, "invalid_parameter");
1220
+ query.append(name, String(item));
1221
+ }
1450
1222
  }
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");
1223
+ if (command.method !== "GET" && !command.readsViaPost) {
1224
+ query.delete("dryRun");
1225
+ if (command.dryRun)
1226
+ query.set("dryRun", String(args.dryRun !== false));
1227
+ else if (args.dryRun !== false)
1228
+ 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");
1229
+ }
1230
+ for (const parameter of command.parameters) {
1231
+ if (parameter.required === true && parameter.in === "query" && !query.has(String(parameter.name)))
1232
+ throw new CliError(`Missing query parameter: ${parameter.name}`, 2, "missing_parameter");
1233
+ if (parameter.in !== "query" || !query.has(parameter.name))
1234
+ continue;
1235
+ const schema = parameter.schema;
1236
+ const values = query.getAll(parameter.name);
1237
+ for (const value of values) {
1238
+ const valueSchema = schema?.type === "array" ? schema.items : schema;
1239
+ let parsed = value;
1240
+ if (valueSchema?.type === "integer" || valueSchema?.type === "number")
1241
+ parsed = value.trim() === "" ? NaN : Number(value);
1242
+ else if (valueSchema?.type === "boolean")
1243
+ parsed = value === "true" ? true : value === "false" ? false : value;
1244
+ validateInput(parsed, valueSchema, `query parameter ${parameter.name}`);
1455
1245
  }
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);
1246
+ }
1247
+ const headers = {};
1248
+ const declaredHeaders = new Map(command.parameters.filter((parameter) => parameter.in === "header").map((parameter) => [parameter.name.toLowerCase(), parameter]));
1249
+ const suppliedHeaders = new Map;
1250
+ for (const [name, value] of Object.entries(args.headers ?? {})) {
1251
+ const normalized = name.toLowerCase();
1252
+ const organizationHeader = command.organization?.header.toLowerCase() === normalized;
1253
+ if (!organizationHeader && !isSafeHeaderName(name))
1254
+ throw new CliError(`Header cannot be supplied as input: ${name}`, 2, "invalid_parameter");
1255
+ if (!organizationHeader && !declaredHeaders.has(normalized) && normalized !== "if-match" && normalized !== "idempotency-key")
1256
+ throw new CliError(`Undeclared header parameter: ${name}`, 2, "invalid_parameter");
1257
+ if (typeof value !== "string" || /[^\t\x20-\x7e\x80-\xff]/.test(value))
1258
+ throw new CliError(`Invalid header parameter: ${name}`, 2, "invalid_parameter");
1259
+ if (suppliedHeaders.has(normalized))
1260
+ throw new CliError(`Duplicate header parameter: ${name}`, 2, "invalid_parameter");
1261
+ suppliedHeaders.set(normalized, value);
1262
+ }
1263
+ if (command.idempotencyKey || args.idempotencyKey !== undefined || suppliedHeaders.has("idempotency-key")) {
1264
+ const suppliedKey = suppliedHeaders.get("idempotency-key");
1265
+ if (suppliedKey && args.idempotencyKey && suppliedKey !== args.idempotencyKey)
1266
+ throw new CliError("Conflicting Idempotency-Key inputs", 2, "invalid_parameter");
1267
+ suppliedHeaders.set("idempotency-key", args.idempotencyKey ?? suppliedKey ?? crypto.randomUUID());
1268
+ }
1269
+ for (const parameter of command.parameters) {
1270
+ if (parameter.in === "cookie" && parameter.required)
1271
+ throw new CliError("Required cookie parameters are unsupported; use token authentication", 2, "invalid_parameter");
1272
+ if (parameter.in !== "header")
1273
+ continue;
1274
+ let value = suppliedHeaders.get(parameter.name.toLowerCase());
1275
+ if (value === undefined && parameter.required && isSafeHeaderName(parameter.name)) {
1276
+ const schema = parameter.schema;
1277
+ 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;
1278
+ if (fixed !== undefined && !/[^\t\x20-\x7e\x80-\xff]/.test(fixed)) {
1279
+ value = fixed;
1280
+ suppliedHeaders.set(parameter.name.toLowerCase(), fixed);
1281
+ }
1462
1282
  }
1463
- } finally {
1464
- await handle.close();
1283
+ if (parameter.required && value === undefined)
1284
+ throw new CliError(`Missing header parameter: ${parameter.name}`, 2, "missing_parameter");
1285
+ if (value !== undefined)
1286
+ validateInput(value, parameter.schema, `header parameter ${parameter.name}`);
1287
+ }
1288
+ for (const [name, value] of suppliedHeaders)
1289
+ headers[name === "idempotency-key" ? "Idempotency-Key" : name] = value;
1290
+ if (headers["Idempotency-Key"] !== undefined) {
1291
+ const key = headers["Idempotency-Key"];
1292
+ if (!key.trim() || /[^\t\x20-\x7e\x80-\xff]/.test(key))
1293
+ throw new CliError("Invalid Idempotency-Key", 2, "invalid_parameter");
1294
+ }
1295
+ if (args.body !== undefined)
1296
+ headers["Content-Type"] = "application/json";
1297
+ return { method: command.method, path: query.size ? `${path}?${query}` : path, ...args.body !== undefined ? { body: args.body } : {}, headers };
1298
+ }
1299
+
1300
+ // src/products.ts
1301
+ var PRODUCTS = [
1302
+ {
1303
+ product: "leo",
1304
+ aliases: [],
1305
+ title: "LEO and the Prudai platform API (models, chat, sources, citations, account, usage, credits)",
1306
+ scopeProducts: ["prudai", "account"],
1307
+ origin: "https://api.prudai.com",
1308
+ liveSpecPath: "/v1/openapi.json"
1309
+ },
1310
+ {
1311
+ product: "irma",
1312
+ aliases: [],
1313
+ title: "IRMA — GRC/ISMS (risks, controls, incidents, audits, registers)",
1314
+ scopeProducts: ["irma"],
1315
+ origin: "https://api.irma.prudai.com",
1316
+ liveSpecPath: "/v1/openapi.json",
1317
+ bundled: "irma.json",
1318
+ approvalsPath: "/approvals",
1319
+ mcpUrl: "https://api.irma.prudai.com/mcp"
1320
+ },
1321
+ {
1322
+ product: "ordo",
1323
+ aliases: [],
1324
+ title: "ORDO — legal practice management and DMS (matters, documents, time, deadlines)",
1325
+ scopeProducts: ["ordo"],
1326
+ origin: "https://api.ordo.prudai.com",
1327
+ liveSpecPath: "/v1/openapi.json"
1465
1328
  }
1329
+ ];
1330
+ var PLATFORM_PRODUCT = "leo";
1331
+ var MCP_GATEWAY = "https://mcp.prudai.com";
1332
+ var CONSOLE_URL = "https://account.prudai.com";
1333
+ function findProduct(word) {
1334
+ return PRODUCTS.find((entry) => entry.product === word || entry.aliases.includes(word));
1466
1335
  }
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;
1336
+
1337
+ // src/catalog.ts
1338
+ var POSITIVE_TTL_MS = 24 * 3600000;
1339
+ var NEGATIVE_TTL_MS = 3600000;
1340
+ var LIVE_TIMEOUT_MS = 4000;
1341
+ var manifestCache;
1342
+ function bundledPath(name) {
1343
+ for (const candidate of [new URL(`./specs/${name}`, import.meta.url), new URL(`../specs/${name}`, import.meta.url)]) {
1344
+ if (existsSync(candidate))
1345
+ return candidate.pathname;
1473
1346
  }
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");
1347
+ return;
1477
1348
  }
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");
1349
+ function bundledManifest() {
1350
+ if (!manifestCache) {
1351
+ const path = bundledPath("manifest.json");
1352
+ manifestCache = path ? JSON.parse(readFileSync(path, "utf8")) : { products: {} };
1501
1353
  }
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;
1354
+ return manifestCache;
1507
1355
  }
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);
1356
+ function readBundledJson(name) {
1357
+ const path = bundledPath(name);
1358
+ return path ? JSON.parse(readFileSync(path, "utf8")) : undefined;
1359
+ }
1360
+ function cacheDir(env) {
1361
+ if (env.PRUDAI_CACHE_DIR)
1362
+ return env.PRUDAI_CACHE_DIR;
1363
+ if (env.XDG_CACHE_HOME)
1364
+ return join(env.XDG_CACHE_HOME, "prudai");
1365
+ return env.HOME ? join(env.HOME, ".cache", "prudai") : undefined;
1366
+ }
1367
+ function readCache(env, product) {
1368
+ const dir = cacheDir(env);
1369
+ if (!dir)
1512
1370
  return;
1513
- }
1514
1371
  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);
1372
+ return JSON.parse(readFileSync(join(dir, "specs", `${product}.json`), "utf8"));
1373
+ } catch {
1522
1374
  return;
1523
1375
  }
1524
- unlinkSync(temporary);
1525
1376
  }
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;
1377
+ function writeCache(env, product, entry) {
1378
+ const dir = cacheDir(env);
1379
+ if (!dir)
1380
+ return;
1530
1381
  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");
1382
+ const path = join(dir, "specs", `${product}.json`);
1383
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
1384
+ const temporary = `${path}.${process.pid}.tmp`;
1385
+ writeFileSync(temporary, JSON.stringify(entry), { mode: 384 });
1386
+ renameSync(temporary, path);
1387
+ } catch {}
1388
+ }
1389
+ function isSpec(value) {
1390
+ return !!value && typeof value === "object" && !Array.isArray(value) && typeof value.openapi === "string" && !!value.paths && typeof value.paths === "object";
1391
+ }
1392
+ var hasLogin = (ctx) => ctx.hasLogin ? ctx.hasLogin() : true;
1393
+ var notLoggedInMessage = (product) => `${product} shows its commands to a logged-in person only. Not logged in. Run \`prudai login\`.`;
1394
+ async function liveSpec(info, ctx) {
1395
+ if (!info.liveSpecPath)
1396
+ return {};
1397
+ const origin = ctx.originFor?.(info.product) ?? info.origin;
1398
+ const url = `${origin.replace(/\/+$/, "")}${info.liveSpecPath}`;
1399
+ const cached = readCache(ctx.env, info.product);
1400
+ const age = cached ? ctx.now() - Date.parse(cached.fetchedAt) : Infinity;
1401
+ if (cached && cached.url === url && !ctx.refresh) {
1402
+ if (cached.ok && cached.spec && age < POSITIVE_TTL_MS)
1403
+ return { spec: cached.spec, source: { kind: "cache", location: url, fetchedAt: cached.fetchedAt } };
1404
+ const refusedAnonymous = !cached.ok && !cached.authed && (cached.status === 401 || cached.status === 403);
1405
+ const retryWithLogin = refusedAnonymous && !!ctx.credentialFor && hasLogin(ctx);
1406
+ if (refusedAnonymous && ctx.credentialFor && !retryWithLogin && age < NEGATIVE_TTL_MS)
1407
+ return { note: `live spec refused without a login at ${url} (HTTP ${cached.status}, checked ${cached.fetchedAt})`, loginNeeded: notLoggedInMessage(info.product) };
1408
+ if (!cached.ok && age < NEGATIVE_TTL_MS && !retryWithLogin)
1409
+ return { note: `live spec unavailable at ${url} (HTTP ${cached.status ?? "error"}, checked ${cached.fetchedAt})` };
1534
1410
  }
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);
1411
+ if (ctx.offline) {
1412
+ return cached?.ok && cached.spec && cached.url === url ? { spec: cached.spec, source: { kind: "cache", location: url, fetchedAt: cached.fetchedAt, note: "stale cache (offline)" } } : {};
1413
+ }
1414
+ if (!isTrustedOrigin(url, ctx.env))
1415
+ return { note: `live spec skipped: ${origin} is not a trusted origin` };
1416
+ let status;
1417
+ let authed = false;
1418
+ let loginNeeded;
1419
+ let credentialFailure;
1420
+ const attempt = async (token) => {
1421
+ const response = await ctx.fetch(secureUrl(url).href, { headers: { accept: "application/json", ...token ? { authorization: `Bearer ${token}` } : {} }, redirect: "error", signal: AbortSignal.timeout(LIVE_TIMEOUT_MS) });
1422
+ status = response.status;
1423
+ if (!response.ok)
1424
+ return;
1425
+ const parsed = JSON.parse(await response.text());
1426
+ return isSpec(parsed) ? parsed : undefined;
1544
1427
  };
1545
- process.once("SIGINT", onSignal);
1546
- process.once("SIGTERM", onSignal);
1547
1428
  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;
1429
+ let parsed = await attempt();
1430
+ if (!parsed && (status === 401 || status === 403) && ctx.credentialFor) {
1431
+ if (!hasLogin(ctx))
1432
+ loginNeeded = notLoggedInMessage(info.product);
1433
+ else {
1434
+ const token = await ctx.credentialFor(info.product).catch((error) => {
1435
+ if (error instanceof CliError && error.code === "not_authenticated")
1436
+ return;
1437
+ credentialFailure = error instanceof CliError ? error : new CliError("The token broker could not be reached; try again in a moment.", 1, "exchange_unavailable");
1438
+ return;
1439
+ });
1440
+ if (!token && !credentialFailure)
1441
+ loginNeeded = notLoggedInMessage(info.product);
1442
+ if (token) {
1443
+ authed = true;
1444
+ parsed = await attempt(token);
1445
+ }
1446
+ }
1557
1447
  }
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");
1448
+ if (parsed) {
1449
+ const fetchedAt = new Date(ctx.now()).toISOString();
1450
+ writeCache(ctx.env, info.product, { url, fetchedAt, ok: true, spec: parsed });
1451
+ return { spec: parsed, source: { kind: "live", location: url, fetchedAt, ...authed ? { note: "served to a logged-in person only" } : {} } };
1560
1452
  }
1561
- closeSync(fd);
1562
- closed = true;
1563
- moveIntoPlace(temporary, target2, rawOut, options.force);
1564
- return { path: target2, bytes, sha256: hash.digest("hex") };
1453
+ } catch {}
1454
+ if (!credentialFailure)
1455
+ writeCache(ctx.env, info.product, { url, fetchedAt: new Date(ctx.now()).toISOString(), ok: false, ...status ? { status } : {}, ...authed ? { authed } : {} });
1456
+ if (cached?.ok && cached.spec && cached.url === url)
1457
+ return { spec: cached.spec, source: { kind: "cache", location: url, fetchedAt: cached.fetchedAt, note: "stale cache; the live spec could not be fetched" } };
1458
+ return { note: `live spec unavailable at ${url}${status ? ` (HTTP ${status})` : ""}`, ...loginNeeded ? { loginNeeded } : {}, ...credentialFailure ? { credentialFailure } : {} };
1459
+ }
1460
+ async function loadProductCatalog(word, ctx) {
1461
+ const info = findProduct(word);
1462
+ const product = info?.product ?? word;
1463
+ const plugin = ctx.plugins?.find((entry) => entry.product === product);
1464
+ const base = {
1465
+ product,
1466
+ title: info?.title ?? product,
1467
+ origin: ctx.originFor?.(product) ?? plugin?.apiUrl ?? info?.origin ?? "",
1468
+ commands: [],
1469
+ warnings: [],
1470
+ scopeProducts: info?.scopeProducts ?? [product],
1471
+ ...info?.approvalsPath ? { approvalsPath: info.approvalsPath } : {},
1472
+ ...info?.mcpUrl ? { mcpUrl: info.mcpUrl } : {}
1473
+ };
1474
+ let spec;
1475
+ let source;
1476
+ let refusal = {};
1477
+ const explicit = ctx.explicitSpec?.(product);
1478
+ if (explicit) {
1479
+ spec = await loadSpec(explicit, ctx.fetch);
1480
+ source = { kind: "explicit", location: explicit };
1481
+ } else if (plugin) {
1482
+ spec = plugin.spec;
1483
+ source = { kind: "plugin", location: `plugin:${product}` };
1484
+ } else if (info) {
1485
+ const live = await liveSpec(info, ctx);
1486
+ if (live.note)
1487
+ base.liveNote = live.note;
1488
+ refusal = live;
1489
+ if (live.spec) {
1490
+ spec = live.spec;
1491
+ source = live.source;
1492
+ } else if (info.bundled) {
1493
+ const bundled = readBundledJson(info.bundled);
1494
+ const meta = bundledManifest().products[info.product];
1495
+ if (bundled) {
1496
+ spec = bundled;
1497
+ source = { kind: "bundled", location: `specs/${info.bundled}`, ref: meta?.ref, status: meta?.status, note: meta?.note };
1498
+ }
1499
+ }
1500
+ }
1501
+ if (!spec) {
1502
+ if (!info)
1503
+ return { ...base, error: `Unknown product "${word}". Run prudai products to list them, or pass --spec <path-or-url>.` };
1504
+ if (refusal.loginNeeded)
1505
+ return { ...base, loginNeeded: true, error: refusal.loginNeeded };
1506
+ if (refusal.credentialFailure)
1507
+ return { ...base, credentialFailure: { code: refusal.credentialFailure.code, exitCode: refusal.credentialFailure.exitCode }, error: refusal.credentialFailure.message };
1508
+ 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.` };
1509
+ }
1510
+ try {
1511
+ const lenient = source?.kind !== "explicit" && source?.kind !== "plugin";
1512
+ const commands = generateCommands(product, spec, {
1513
+ lenientApproval: lenient,
1514
+ ...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.`) } : {}
1515
+ });
1516
+ const defaulted = commands.filter((command) => command.approvalSource === "default").length;
1517
+ if (defaulted)
1518
+ base.warnings.push(`${defaulted} write operation(s) declare no x-prudai-approval; the CLI assumes the default level (confirm, delete: review).`);
1519
+ if (!commands.length)
1520
+ 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).");
1521
+ return { ...base, source, commands, spec };
1565
1522
  } catch (error) {
1566
- if (!closed)
1567
- try {
1568
- closeSync(fd);
1569
- } catch {}
1570
- try {
1571
- unlinkSync(temporary);
1572
- } catch {}
1573
- if (error instanceof CliError)
1523
+ if (source?.kind === "explicit" || source?.kind === "plugin")
1574
1524
  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);
1525
+ return { ...base, source, error: error instanceof CliError ? error.message : "The spec could not be read." };
1579
1526
  }
1580
1527
  }
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
- }
1528
+ async function loadCatalog(ctx, only) {
1529
+ const words = only?.length ? only : [...PRODUCTS.map((entry) => entry.product), ...(ctx.plugins ?? []).map((entry) => entry.product).filter((name) => !findProduct(name))];
1530
+ return Promise.all(words.map((word) => loadProductCatalog(word, ctx)));
1588
1531
  }
1589
- async function writeStreamToFile(out, stream, options) {
1590
- return writeChunks(out, interruptible(stream), options);
1532
+ function commandLine(command) {
1533
+ return [command.commandLine ?? `prudai ${command.product} ${command.name}`, ...command.positionals.map((name) => `<${name}>`)].join(" ");
1591
1534
  }
1592
- async function writeTextToFile(out, text, force) {
1593
- return writeChunks(out, async function* () {
1594
- yield new TextEncoder().encode(text);
1595
- }(), { force });
1535
+ var tokens = (text) => text.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9à-ÿ]+/i).filter(Boolean);
1536
+ var SEARCH_SYNONYMS = [
1537
+ ["setup", "onboarding", "inrichten", "inrichting", "start", "startpad", "context", "initialization"],
1538
+ ["tenant", "omgeving", "organisatie", "organization", "organisation", "org", "context"],
1539
+ ["bibliotheek", "bibliotheken", "library", "libraries", "normenkader", "normenkaders", "framework", "frameworks"],
1540
+ ["eis", "eisen", "requirement", "requirements"],
1541
+ ["dekken", "gedekt", "dekking", "coverage", "cover"]
1542
+ ];
1543
+ var wordMatches = (word, term) => word === term || term.length > 2 && (word === `${term}s` || term === `${word}s`);
1544
+ function searchOperations(catalogs, query, filters = {}) {
1545
+ const terms = tokens(query);
1546
+ const concepts = terms.map((term) => ({ term, alternatives: new Set([term, ...SEARCH_SYNONYMS.filter((group) => group.includes(term)).flat()]) }));
1547
+ const hits = [];
1548
+ for (const catalog of catalogs) {
1549
+ if (filters.product && catalog.product !== (findProduct(filters.product)?.product ?? filters.product))
1550
+ continue;
1551
+ for (const command of catalog.commands) {
1552
+ if (filters.approval && command.approval !== filters.approval)
1553
+ continue;
1554
+ if (filters.method && command.method !== filters.method.toUpperCase())
1555
+ continue;
1556
+ const fields = [
1557
+ [tokens(command.commandLine ?? `${command.product} ${command.name}`), 8],
1558
+ [tokens(command.summary), 7],
1559
+ [tokens(command.path), 5],
1560
+ [tokens(command.operationId), 4],
1561
+ [tokens((command.tags ?? []).join(" ")), 3],
1562
+ [tokens((command.scopes ?? []).join(" ")), 2],
1563
+ [tokens((command.description ?? "").replace(/idempotency-key/gi, "")), 1]
1564
+ ];
1565
+ let score = 0;
1566
+ let matched = 0;
1567
+ let directPrimary = 0;
1568
+ for (const { term, alternatives } of concepts) {
1569
+ let best = 0;
1570
+ for (const [words, weight] of fields) {
1571
+ const direct = words.some((word) => wordMatches(word, term));
1572
+ if (direct && weight >= 7)
1573
+ directPrimary++;
1574
+ if (direct)
1575
+ best = Math.max(best, weight * 2);
1576
+ else if (words.some((word) => [...alternatives].some((alias) => wordMatches(word, alias))))
1577
+ best = Math.max(best, weight);
1578
+ }
1579
+ if (best) {
1580
+ matched++;
1581
+ score += best;
1582
+ }
1583
+ }
1584
+ if (terms.length && matched !== terms.length)
1585
+ continue;
1586
+ score += directPrimary * 100;
1587
+ if (concepts.length === 1 && concepts[0].alternatives.has(command.name.toLowerCase()))
1588
+ score += 30;
1589
+ hits.push({
1590
+ command: commandLine(command),
1591
+ product: command.product,
1592
+ method: command.method,
1593
+ path: command.path,
1594
+ operationId: command.operationId,
1595
+ summary: command.summary,
1596
+ approval: command.approval,
1597
+ scopes: command.scopes ?? [],
1598
+ cost: command.cost ?? "not stated",
1599
+ dryRun: command.dryRun,
1600
+ ...command.status ? { status: command.status } : {},
1601
+ ...command.available === false ? { available: false } : {},
1602
+ score
1603
+ });
1604
+ }
1605
+ }
1606
+ return hits.sort((a, b) => b.score - a.score || a.command.localeCompare(b.command));
1596
1607
  }
1597
- function terminalSafe(text) {
1598
- return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "?");
1608
+ function findOperation(catalogs, ref) {
1609
+ const words = ref.flatMap((part) => part.split(/\s+/)).filter(Boolean);
1610
+ if (words[0] === "prudai")
1611
+ words.shift();
1612
+ const productFirst = words[0] ? findProduct(words[0])?.product ?? (catalogs.some((c) => c.product === words[0]) ? words[0] : undefined) : undefined;
1613
+ const scoped = productFirst ? catalogs.filter((catalog) => catalog.product === productFirst) : catalogs;
1614
+ const rest = productFirst ? words.slice(1) : words;
1615
+ const found = [];
1616
+ if (rest.length === 2 && /^(get|post|put|patch|delete)$/i.test(rest[0])) {
1617
+ const [method, path] = [rest[0].toUpperCase(), rest[1].split("?")[0]];
1618
+ for (const catalog of scoped)
1619
+ for (const command of catalog.commands)
1620
+ if (command.method === method && (command.path === path || templateMatches(command.path, path)))
1621
+ found.push({ catalog, command });
1622
+ } else if (rest.length === 1 && rest[0].includes(":") && !productFirst) {
1623
+ const [product, operationId] = rest[0].split(/:(.*)/s);
1624
+ for (const catalog of catalogs.filter((c) => c.product === (findProduct(product)?.product ?? product)))
1625
+ for (const command of catalog.commands)
1626
+ if (command.operationId === operationId)
1627
+ found.push({ catalog, command });
1628
+ } else {
1629
+ for (const catalog of scoped) {
1630
+ for (const command of catalog.commands) {
1631
+ if (productFirst && rest.slice(0, command.words.length).join(" ") === command.name && rest.length <= command.words.length + command.positionals.length)
1632
+ found.push({ catalog, command });
1633
+ else if (rest.length === 1 && command.operationId === rest[0])
1634
+ found.push({ catalog, command });
1635
+ }
1636
+ }
1637
+ const longest = Math.max(0, ...found.map((entry) => entry.command.words.length));
1638
+ found.splice(0, found.length, ...found.filter((entry) => entry.command.words.length === longest || !productFirst));
1639
+ }
1640
+ const unique = [...new Map(found.map((entry) => [`${entry.catalog.product} ${entry.command.method} ${entry.command.path}`, entry])).values()];
1641
+ if (unique.length === 1)
1642
+ return unique[0];
1643
+ return { candidates: unique.map((entry) => commandLine(entry.command)) };
1644
+ }
1645
+ function templateMatches(template, path) {
1646
+ const a = template.split("/");
1647
+ const b = path.split("/");
1648
+ return a.length === b.length && a.every((part, index) => /^\{[^}]+\}$/.test(part) ? !!b[index] : part === b[index]);
1599
1649
  }
1600
1650
 
1601
1651
  // 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");
1652
+ import { readFile as readFile3 } from "node:fs/promises";
1653
+
1654
+ // src/output.ts
1655
+ function localEnvelope(data, parts = {}) {
1656
+ const count = Array.isArray(data) ? data.length : undefined;
1657
+ return {
1658
+ data,
1659
+ context: parts.context ?? {},
1660
+ completeness: parts.completeness ?? (count !== undefined ? { returned: count, total: count, truncated: false } : { complete: true }),
1661
+ notIncluded: parts.notIncluded ?? [],
1662
+ provenance: parts.provenance ?? { kind: "cli" },
1663
+ next: parts.next ?? []
1664
+ };
1616
1665
  }
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.");
1666
+
1667
+ class DetailedCliError extends CliError {
1668
+ details;
1669
+ constructor(message2, code, details, exitCode = 2) {
1670
+ super(message2, exitCode, code);
1671
+ this.details = details;
1672
+ this.name = "DetailedCliError";
1633
1673
  }
1634
1674
  }
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);
1675
+
1676
+ class NotAvailableError extends DetailedCliError {
1677
+ constructor(message2, details) {
1678
+ super(message2, "not_available", details);
1679
+ this.name = "NotAvailableError";
1645
1680
  }
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");
1681
+ }
1682
+ function throwIfUnusable(catalog) {
1683
+ if (catalog.notAvailable)
1684
+ throw productNotAvailable(catalog);
1685
+ if (catalog.loginNeeded)
1686
+ throw new CliError(catalog.error, 2, "not_authenticated");
1687
+ if (catalog.credentialFailure)
1688
+ throw new CliError(catalog.error, catalog.credentialFailure.exitCode, catalog.credentialFailure.code);
1689
+ }
1690
+ function productNotAvailable(catalog) {
1691
+ return new NotAvailableError(catalog.error, {
1692
+ product: catalog.product,
1693
+ ...catalog.liveNote ? { liveSpec: catalog.liveNote } : {},
1694
+ next: ["prudai products shows which catalogues are available.", `Retry later with --refresh once the ${catalog.product} /v1 spec is served.`]
1695
+ });
1696
+ }
1697
+ function errorDocument(error) {
1698
+ return { error: error.code, message: error.message, exitCode: error.exitCode, ...error instanceof DetailedCliError ? error.details : {} };
1699
+ }
1700
+ function isEnvelopeLike(body) {
1701
+ return isRecord(body) && "data" in body && "context" in body;
1702
+ }
1703
+
1704
+ // src/approvals.ts
1705
+ var APPROVAL_POLL_MS = 5000;
1706
+ var TERMINAL = new Set(["rejected", "expired", "cancelled", "canceled", "executed", "failed"]);
1707
+ function target(ctx) {
1708
+ const word = str(ctx.flags, "product");
1709
+ const candidates = PRODUCTS.filter((entry) => entry.approvalsPath);
1710
+ const info = word ? findProduct(word) : candidates.length === 1 ? candidates[0] : undefined;
1711
+ if (!info)
1712
+ throw new CliError(`Name the product: --product ${candidates.map((entry) => entry.product).join("|")}.`);
1713
+ if (!info.approvalsPath) {
1714
+ throw new NotAvailableError(`${info.product} has no approvals API yet. Approve the request in the ${info.product} app.`, {
1715
+ planned: "GET /v1/approvals/{id} (central approvals on the developer platform)",
1716
+ next: [`Find the request in the ${info.product} app.`]
1717
+ });
1651
1718
  }
1719
+ const origin = resolveOrigin(info.product, ctx);
1652
1720
  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);
1721
+ throw new CliError(`Configure the ${info.product} API origin.`);
1722
+ return { product: info.product, origin: safeApiOrigin(origin), approvalsPath: info.approvalsPath };
1723
+ }
1724
+ async function requireToken(ctx, product) {
1725
+ const token = await credentialFor(product, ctx);
1657
1726
  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.`);
1727
+ throw missingCredential(product);
1728
+ return token;
1729
+ }
1730
+ async function call(ctx, t, method, suffix, body) {
1731
+ requireTrustedOrigin(t.origin, ctx.env);
1732
+ const token = await requireToken(ctx, t.product);
1733
+ const headers = organizationHeaders(t.product, t.organization, ctx);
1734
+ const response = await requestJson(ctx.fetch, `${t.origin}${t.approvalsPath}${suffix}`, { method, headers, token, env: ctx.env, ...body !== undefined ? { body } : {} });
1735
+ assertOrganizationMatches(response.body, ctx.selection.organization, method !== "GET");
1736
+ return response;
1737
+ }
1738
+ function followCommand(ctx, t, action, id) {
1739
+ const org = t.organization && ctx.selection.organization && ctx.selection.organization.source !== "login" ? ` --org ${ctx.selection.organization.id}` : "";
1740
+ return `prudai approvals ${action} ${id} --product ${t.product}${org}`;
1741
+ }
1742
+ function fail(status, body, what) {
1743
+ const error = httpError(status, body);
1744
+ throw new CliError(`${what}: ${error.message}`, error.exitCode, error.code);
1745
+ }
1746
+ var idOf = (value) => {
1747
+ if (!value || !/^[A-Za-z0-9_-]{1,100}$/.test(value))
1748
+ throw new CliError("Give the approval request id (from the 202 answer).");
1749
+ return value;
1750
+ };
1751
+ async function waitForApproval(ctx, opts) {
1752
+ const t = { product: opts.product, origin: opts.origin, approvalsPath: opts.approvalsPath, organization: opts.organization };
1753
+ const deadline = ctx.now() + (opts.timeoutSeconds ?? 600) * 1000;
1754
+ let status = "pending";
1755
+ let last = {};
1756
+ for (;; ) {
1757
+ const response = await call(ctx, t, "GET", `/${encodeURIComponent(opts.id)}/status`);
1758
+ if (response.status !== 200 || !isRecord(response.body))
1759
+ fail(response.status, response.body, "Approval status");
1760
+ last = response.body;
1761
+ status = String(last.status ?? "unknown");
1762
+ if (status !== "pending")
1763
+ break;
1764
+ if (ctx.now() >= deadline) {
1765
+ throw new CliError(`Still pending after ${opts.timeoutSeconds ?? 600}s; nothing was executed. Run ${followCommand(ctx, t, "wait", opts.id)} again later.`, 2, "approval_timeout");
1766
+ }
1767
+ await ctx.sleep(Math.min(APPROVAL_POLL_MS, Math.max(0, deadline - ctx.now())));
1666
1768
  }
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;
1769
+ const summary = { id: opts.id, product: opts.product, status, level: last.level, operation: last.operation, executeUntil: last.executeUntil ?? null };
1770
+ if (status === "approved") {
1771
+ if (!opts.execute) {
1772
+ const next = followCommand(ctx, t, "execute", opts.id);
1773
+ ctx.emit(localEnvelope(summary, { provenance: { kind: "product", product: opts.product }, next: [{ action: next, why: "The server runs exactly the approved call." }] }), `Approved. Run: ${next}`);
1774
+ return 0;
1687
1775
  }
1776
+ return executeApproved(ctx, t, opts.id);
1688
1777
  }
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.`);
1778
+ if (TERMINAL.has(status)) {
1779
+ if (status === "executed") {
1780
+ ctx.emit(localEnvelope(summary, { provenance: { kind: "product", product: opts.product }, notIncluded: ["The result was returned to whoever executed it."] }), "Already executed.");
1781
+ return 0;
1782
+ }
1783
+ throw new CliError(`Approval request ${opts.id} is ${status}; nothing was executed.`, 2, `approval_${status}`);
1692
1784
  }
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 };
1785
+ throw new CliError(`Unexpected approval status "${status}".`, 1, "invalid_response");
1786
+ }
1787
+ async function executeApproved(ctx, t, id) {
1788
+ const response = await call(ctx, t, "POST", `/${encodeURIComponent(id)}/execute`);
1789
+ if (response.status !== 200 || !isRecord(response.body))
1790
+ fail(response.status, response.body, "Execute approved request");
1791
+ const executed = response.body;
1792
+ if (executed.status !== "executed" || typeof executed.resultStatus !== "number")
1793
+ throw new CliError("Unexpected execute response.", 1, "invalid_response");
1794
+ const result = executed.result;
1795
+ assertOrganizationMatches(result, ctx.selection.organization, true);
1796
+ if (executed.resultStatus >= 400)
1797
+ throw new CliError(`The approved call ran and returned HTTP ${executed.resultStatus}.`, executed.resultStatus >= 500 ? 1 : 2, `http_${executed.resultStatus}`);
1798
+ const envelope = isEnvelopeLike(result) ? parseEnvelope(result) : localEnvelope(result ?? null, { provenance: { kind: "product", product: t.product }, context: { approvalRequestId: id, resultStatus: executed.resultStatus } });
1799
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1800
+ return 0;
1801
+ }
1802
+ async function approvalsCommand(words, ctx) {
1803
+ validateFlags(ctx.flags, ["json", "profile", "product", "api-url", "timeout", "execute", "status", "scope", "limit", "help", "org", "spec", "registry", "refresh", "offline"]);
1804
+ const [action, id, ...extra] = words;
1805
+ if (extra.length)
1806
+ throw new CliError("Too many arguments.");
1807
+ if (action === "approve" || action === "reject" || action === "decide") {
1808
+ 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");
1709
1809
  }
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
- `));
1810
+ const t = target(ctx);
1811
+ const catalog = await loadProductCatalog(t.product, ctx.catalog);
1812
+ throwIfUnusable(catalog);
1813
+ t.organization = organizationDeclaration(catalog.spec);
1814
+ organizationHeaders(t.product, t.organization, ctx);
1815
+ if (action === "list") {
1816
+ const status = str(ctx.flags, "status") ?? "pending";
1817
+ if (!["pending", "approved", "all"].includes(status))
1818
+ throw new CliError("--status is pending, approved or all.");
1819
+ const scope = str(ctx.flags, "scope") ?? "mine";
1820
+ if (!["mine", "to-review", "all"].includes(scope))
1821
+ throw new CliError("--scope is mine, to-review or all.");
1822
+ const limit = intFlag(ctx.flags, "limit", 50, 1, 200);
1823
+ const response = await call(ctx, t, "GET", `?scope=${scope}&status=${status}&limit=${limit}`);
1824
+ if (response.status !== 200 || !isRecord(response.body) || !Array.isArray(response.body.items))
1825
+ fail(response.status, response.body, "List approvals");
1826
+ const items = response.body.items;
1827
+ ctx.emit(localEnvelope(items, {
1828
+ provenance: { kind: "product", product: t.product },
1829
+ completeness: { returned: items.length, truncated: items.length >= limit },
1830
+ next: [{ action: followCommand(ctx, t, "wait", "<id>"), why: "Wait for a decision." }]
1831
+ }));
1735
1832
  return 0;
1736
1833
  }
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;
1834
+ if (action === "get" || action === "status") {
1835
+ const response = await call(ctx, t, "GET", `/${encodeURIComponent(idOf(id))}${action === "status" ? "/status" : ""}`);
1836
+ if (response.status !== 200)
1837
+ fail(response.status, response.body, "Approval lookup");
1838
+ const envelope = localEnvelope(response.body, { provenance: { kind: "product", product: t.product } });
1839
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1840
+ return 0;
1774
1841
  }
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);
1842
+ if (action === "wait") {
1843
+ return waitForApproval(ctx, { ...t, id: idOf(id), execute: !!ctx.flags.execute, timeoutSeconds: intFlag(ctx.flags, "timeout", 600, 5, 3600) });
1780
1844
  }
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
- `));
1845
+ if (action === "execute")
1846
+ return executeApproved(ctx, t, idOf(id));
1847
+ if (action === "cancel") {
1848
+ const response = await call(ctx, t, "POST", `/${encodeURIComponent(idOf(id))}/cancel`);
1849
+ if (response.status !== 200)
1850
+ fail(response.status, response.body, "Cancel approval");
1851
+ const envelope = localEnvelope(response.body, { provenance: { kind: "product", product: t.product } });
1852
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1803
1853
  return 0;
1804
1854
  }
1805
- if (!envelope) {
1806
- emit(localEnvelope(null, { context: { status: 204 }, provenance: { kind: "product", product: operation.product } }), "Done (no content).");
1807
- return 0;
1855
+ 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)");
1856
+ }
1857
+
1858
+ // src/transfer.ts
1859
+ import { createHash as createHash2, randomUUID } from "node:crypto";
1860
+ import { accessSync, closeSync, constants, existsSync as existsSync2, fchmodSync, fstatSync, linkSync, lstatSync, openSync, renameSync as renameSync2, statSync, unlinkSync, writeSync } from "node:fs";
1861
+ import { open } from "node:fs/promises";
1862
+ import { basename, dirname as dirname2, extname, join as join2, resolve as resolve2 } from "node:path";
1863
+ var PRIVATE_MODE = 384;
1864
+ var CHUNK = 256 * 1024;
1865
+ var TEMPORARY_OVERHEAD = 1 + 1 + 8 + 5;
1866
+ var CONTENT_TYPES = {
1867
+ ".m4a": "audio/mp4",
1868
+ ".mp4": "audio/mp4",
1869
+ ".webm": "audio/webm",
1870
+ ".mp3": "audio/mpeg",
1871
+ ".wav": "audio/wav",
1872
+ ".ogg": "audio/ogg",
1873
+ ".opus": "audio/opus",
1874
+ ".aac": "audio/aac",
1875
+ ".flac": "audio/flac",
1876
+ ".vtt": "text/vtt",
1877
+ ".srt": "application/x-subrip",
1878
+ ".txt": "text/plain",
1879
+ ".md": "text/markdown",
1880
+ ".pdf": "application/pdf",
1881
+ ".csv": "text/csv",
1882
+ ".json": "application/json",
1883
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1884
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1885
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
1886
+ };
1887
+ var fileError = (message2, code = "invalid_file") => new CliError(message2, 2, code);
1888
+ function inspectUploadFile(raw, field = "file") {
1889
+ if (!raw.trim())
1890
+ throw fileError("Give the path of the file to upload.");
1891
+ const path = resolve2(raw);
1892
+ try {
1893
+ const seen = lstatSync(path);
1894
+ if (seen.isSymbolicLink())
1895
+ throw fileError(`${raw} is a symbolic link; pass the path of the real file. Nothing was sent.`);
1896
+ if (!seen.isFile())
1897
+ throw fileError(`${raw} is not a regular file. Nothing was sent.`);
1898
+ } catch (error) {
1899
+ if (error instanceof CliError)
1900
+ throw error;
1901
+ if (error.code === "ENOENT")
1902
+ throw fileError(`File not found: ${raw}`);
1903
+ }
1904
+ let fd;
1905
+ try {
1906
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1907
+ } catch (error) {
1908
+ const code = error.code;
1909
+ if (code === "ENOENT")
1910
+ throw fileError(`File not found: ${raw}`);
1911
+ if (code === "ELOOP" || code === "EMLINK")
1912
+ throw fileError(`${raw} is a symbolic link; pass the path of the real file. Nothing was sent.`);
1913
+ if (code === "EACCES" || code === "EPERM")
1914
+ throw fileError(`No permission to read ${raw}.`);
1915
+ throw fileError(`Could not open ${raw}.`);
1808
1916
  }
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
1917
  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 } : {} });
1918
+ const stat2 = fstatSync(fd);
1919
+ if (!stat2.isFile())
1920
+ throw fileError(`${raw} is not a regular file. Nothing was sent.`);
1921
+ if (stat2.size === 0)
1922
+ throw fileError(`${raw} is empty. Nothing was sent.`);
1923
+ const filename = basename(path);
1924
+ const file = {
1925
+ path,
1926
+ field,
1927
+ filename,
1928
+ size: stat2.size,
1929
+ dev: stat2.dev,
1930
+ ino: stat2.ino,
1931
+ contentType: CONTENT_TYPES[extname(filename).toLowerCase()] ?? "application/octet-stream",
1932
+ open: () => readFile2(file)
1933
+ };
1934
+ return file;
1819
1935
  } finally {
1820
- await answer.stream.cancel().catch(() => {
1821
- return;
1822
- });
1936
+ closeSync(fd);
1823
1937
  }
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
1938
  }
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;
1939
+ async function* readFile2(file) {
1940
+ let handle;
1941
+ try {
1942
+ handle = await open(file.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1943
+ } catch {
1944
+ throw new CliError("The file could not be opened for uploading; check the state before retrying.", 1, "file_unreadable");
1945
+ }
1946
+ try {
1947
+ const stat2 = await handle.stat();
1948
+ if (!stat2.isFile() || stat2.dev !== file.dev || stat2.ino !== file.ino || stat2.size !== file.size) {
1949
+ throw new CliError("The file changed after it was checked; nothing was sent from it.", 1, "file_changed");
1950
+ }
1951
+ for (;; ) {
1952
+ const buffer = Buffer.allocUnsafe(CHUNK);
1953
+ const { bytesRead } = await handle.read(buffer, 0, CHUNK, null);
1954
+ if (bytesRead === 0)
1955
+ return;
1956
+ yield buffer.subarray(0, bytesRead);
1957
+ }
1958
+ } finally {
1959
+ await handle.close();
1849
1960
  }
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
1961
  }
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;
1962
+ async function sha256File(file) {
1963
+ const hash = createHash2("sha256");
1964
+ let bytes = 0;
1965
+ for await (const chunk of file.open()) {
1966
+ hash.update(chunk);
1967
+ bytes += chunk.length;
1968
+ }
1969
+ if (bytes !== file.size)
1970
+ throw new CliError("The file changed while it was being read.", 1, "file_changed");
1971
+ return hash.digest("hex");
1889
1972
  }
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;
1973
+ function checkOutTarget(raw, force) {
1974
+ if (!raw.trim() || raw === "-")
1975
+ throw fileError("--out takes a file path. Bytes and long text are never written to stdout.", "invalid_out");
1976
+ const path = resolve2(raw);
1977
+ let parentOk = false;
1905
1978
  try {
1906
- decoded = decodeURIComponent(path);
1979
+ parentOk = statSync(dirname2(path)).isDirectory();
1980
+ } catch {}
1981
+ if (!parentOk)
1982
+ throw fileError(`The directory of --out does not exist: ${dirname2(raw)}`, "invalid_out");
1983
+ try {
1984
+ accessSync(dirname2(path), constants.W_OK);
1907
1985
  } 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 });
1986
+ throw fileError(`The directory of --out is not writable: ${dirname2(raw)}`, "invalid_out");
1945
1987
  }
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");
1988
+ if (Buffer.byteLength(basename(path)) + TEMPORARY_OVERHEAD > 255)
1989
+ throw fileError("The file name of --out is too long.", "invalid_out");
1990
+ let existing;
1991
+ try {
1992
+ existing = lstatSync(path);
1993
+ } catch (error) {
1994
+ if (error.code !== "ENOENT")
1995
+ throw fileError(`Could not check ${raw}.`, "invalid_out");
1962
1996
  }
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)`);
1997
+ if (existing?.isDirectory())
1998
+ throw fileError(`${raw} is a directory; give a file path.`, "invalid_out");
1999
+ if (existing && !force)
2000
+ throw fileError(`${raw} already exists. Nothing was overwritten; use --force to replace it, or pick another path.`, "file_exists");
2001
+ return path;
2002
+ }
2003
+ function moveIntoPlace(temporary, target2, raw, force) {
2004
+ const exists = () => fileError(`${raw} appeared while writing; nothing was overwritten. Use --force to replace it.`, "file_exists");
2005
+ if (force) {
2006
+ renameSync2(temporary, target2);
2007
+ return;
1970
2008
  }
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;
2009
+ try {
2010
+ linkSync(temporary, target2);
2011
+ } catch (error) {
2012
+ if (error.code === "EEXIST")
2013
+ throw exists();
2014
+ if (existsSync2(target2))
2015
+ throw exists();
2016
+ renameSync2(temporary, target2);
2017
+ return;
1979
2018
  }
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;
2019
+ unlinkSync(temporary);
1985
2020
  }
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;
2021
+ async function writeChunks(rawOut, chunks, options) {
2022
+ const target2 = checkOutTarget(rawOut, options.force);
2023
+ const temporary = join2(dirname2(target2), `.${basename(target2)}.${randomUUID().slice(0, 8)}.part`);
2024
+ let fd;
2001
2025
  try {
2002
- url = secureUrl(issuer);
2026
+ fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, PRIVATE_MODE);
2003
2027
  } catch {
2004
- throw new CliError("The Keycloak issuer must be an https URL (or localhost), without credentials.", 2, "invalid_issuer");
2028
+ throw fileError(`Cannot create a file next to ${rawOut}; nothing was written.`, "invalid_out");
2029
+ }
2030
+ let closed = false;
2031
+ const onSignal = (signal) => {
2032
+ try {
2033
+ closeSync(fd);
2034
+ } catch {}
2035
+ try {
2036
+ unlinkSync(temporary);
2037
+ } catch {}
2038
+ process.exit(signal === "SIGINT" ? 130 : 143);
2039
+ };
2040
+ process.once("SIGINT", onSignal);
2041
+ process.once("SIGTERM", onSignal);
2042
+ try {
2043
+ fchmodSync(fd, PRIVATE_MODE);
2044
+ const hash = createHash2("sha256");
2045
+ let bytes = 0;
2046
+ for await (const chunk of chunks) {
2047
+ let offset = 0;
2048
+ while (offset < chunk.length)
2049
+ offset += writeSync(fd, chunk, offset, chunk.length - offset);
2050
+ hash.update(chunk);
2051
+ bytes += chunk.length;
2052
+ }
2053
+ if (options.expectedBytes !== undefined && bytes !== options.expectedBytes) {
2054
+ throw new CliError(`The download ended after ${bytes} of ${options.expectedBytes} bytes; nothing was kept.`, 1, "incomplete_download");
2055
+ }
2056
+ closeSync(fd);
2057
+ closed = true;
2058
+ moveIntoPlace(temporary, target2, rawOut, options.force);
2059
+ return { path: target2, bytes, sha256: hash.digest("hex") };
2060
+ } catch (error) {
2061
+ if (!closed)
2062
+ try {
2063
+ closeSync(fd);
2064
+ } catch {}
2065
+ try {
2066
+ unlinkSync(temporary);
2067
+ } catch {}
2068
+ if (error instanceof CliError)
2069
+ throw error;
2070
+ throw new CliError("The file could not be written; nothing was kept.", 1, "write_failed");
2071
+ } finally {
2072
+ process.off("SIGINT", onSignal);
2073
+ process.off("SIGTERM", onSignal);
2005
2074
  }
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
2075
  }
2012
- async function postForm(fetchImpl, url, form) {
2013
- let response;
2076
+ async function* interruptible(source) {
2014
2077
  try {
2015
- response = await fetchImpl(url, { method: "POST", headers: FORM, body: new URLSearchParams(form).toString(), redirect: "error", signal: AbortSignal.timeout(15000) });
2078
+ for await (const chunk of source)
2079
+ yield chunk;
2016
2080
  } catch {
2017
- throw new CliError("Could not reach the login service; check the network and try again.", 1, "network_error");
2081
+ throw new CliError("The download was interrupted; nothing was kept. The file can be downloaded again.", 1, "network_error");
2018
2082
  }
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
2083
  }
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;
2084
+ async function writeStreamToFile(out, stream, options) {
2085
+ return writeChunks(out, interruptible(stream), options);
2032
2086
  }
2033
- function readClaims(token) {
2034
- if (!JWT.test(token))
2087
+ async function writeTextToFile(out, text, force) {
2088
+ return writeChunks(out, async function* () {
2089
+ yield new TextEncoder().encode(text);
2090
+ }(), { force });
2091
+ }
2092
+ function terminalSafe(text) {
2093
+ return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "?");
2094
+ }
2095
+
2096
+ // src/execute.ts
2097
+ function resolveOrigin(product, ctx, spec, useFlag = true) {
2098
+ const profile = ctx.file.profiles[ctx.config.profile];
2099
+ const plugin = ctx.options.plugins?.find((entry) => entry.product === product);
2100
+ const info = findProduct(product);
2101
+ const specOrigin = spec ? serverOrigin(spec) : undefined;
2102
+ 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);
2103
+ }
2104
+ async function credentialFor(product, ctx) {
2105
+ if (!ctx.session.hasLogin)
2035
2106
  return;
2036
- let payload;
2107
+ return ctx.session.productToken(product);
2108
+ }
2109
+ function missingCredential(_product) {
2110
+ return new CliError("Not logged in. Run `prudai login` (device login with your Prudai account).", 2, "not_authenticated");
2111
+ }
2112
+ async function readData(flags) {
2113
+ const data = str(flags, "data");
2114
+ if (data === undefined)
2115
+ return;
2116
+ let text = data;
2117
+ if (data.startsWith("@")) {
2118
+ try {
2119
+ text = await readFile3(data.slice(1), "utf8");
2120
+ } catch {
2121
+ throw new CliError("Could not read --data file.");
2122
+ }
2123
+ }
2037
2124
  try {
2038
- payload = record(JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8")));
2125
+ return JSON.parse(text);
2039
2126
  } catch {
2040
- return;
2127
+ throw new CliError("--data must contain valid JSON.");
2041
2128
  }
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
2129
  }
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");
2130
+ 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.";
2131
+ async function executeOperation(operation, positionals, origin, ctx, extras = {}) {
2132
+ const { flags, env, emit, stderr } = ctx;
2133
+ const allowed = new Set([...GLOBAL_FLAGS, ...extras.consumed ?? []]);
2134
+ for (const parameter of operation.parameters) {
2135
+ if (parameter.in === "header") {
2136
+ if (isSafeHeaderName(parameter.name))
2137
+ allowed.add(parameter.name.toLowerCase());
2138
+ } else if (parameter.in === "path" || parameter.in === "query")
2139
+ allowed.add(parameter.name);
2140
+ }
2141
+ validateFlags(flags, allowed);
2142
+ if (!extras.organizationInPath)
2143
+ organizationHeaders(operation.product, operation.organization, ctx);
2144
+ if (operation.approval === "forbidden_for_agents")
2145
+ throw new CliError("This operation is forbidden for agents; a human does it in the product app.", 2, "forbidden_for_agents");
2146
+ if (operation.multipart && !extras.upload) {
2147
+ 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");
2148
+ }
2149
+ if (!origin)
2150
+ throw new CliError(`Configure the ${operation.product} API origin: prudai profile set productApiUrls.${operation.product} <origin>, or --api-url <origin>.`);
2151
+ const apiUrl = safeApiOrigin(origin);
2152
+ requireTrustedOrigin(apiUrl, env);
2153
+ const token = await credentialFor(operation.product, ctx);
2154
+ if (!token)
2155
+ throw missingCredential(operation.product);
2156
+ const selectedHeaders = extras.organizationInPath ? {} : organizationHeaders(operation.product, operation.organization, ctx);
2157
+ const isGet = operation.method.toUpperCase() === "GET";
2158
+ const writing = !isGet && !operation.readsViaPost;
2159
+ const approvalsPath = extras.approvalsPath ?? findProduct(operation.product)?.approvalsPath;
2160
+ if (flags.wait && writing && !approvalsPath)
2161
+ 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");
2162
+ if (operation.status === "planned") {
2163
+ stderr(`Note: ${operation.method} ${operation.path} comes from a spec that marks it planned; it may not be served yet.`);
2164
+ }
2165
+ if (operation.cost?.startsWith("credits") && writing && flags["no-dry-run"])
2166
+ stderr("Note: this operation spends credits.");
2167
+ if (isGet && (flags.data !== undefined || extras.body))
2168
+ throw new CliError("Read commands do not accept --data.");
2169
+ if (writing && flags["no-dry-run"] && !flags.yes)
2170
+ throw new CliError("Real writes require --no-dry-run --yes.");
2171
+ if (flags.wait && !writing)
2172
+ throw new CliError("--wait belongs to writes that may need approval.");
2173
+ const params = {};
2174
+ const query = {};
2175
+ const headers = {};
2176
+ for (const parameter of operation.parameters) {
2177
+ const value = str(flags, parameter.in === "header" ? parameter.name.toLowerCase() : parameter.name);
2178
+ if (value !== undefined) {
2179
+ if (parameter.in === "path")
2180
+ params[parameter.name] = value;
2181
+ else if (parameter.in === "query")
2182
+ query[parameter.name] = value;
2183
+ else if (parameter.in === "header")
2184
+ headers[parameter.name.toLowerCase()] = value;
2185
+ }
2186
+ }
2187
+ const open2 = operation.positionals.filter((name) => params[name] === undefined && query[name] === undefined);
2188
+ if (positionals.length > open2.length) {
2189
+ throw new CliError(open2.length ? `Too many arguments; ${operation.name} takes ${open2.map((name) => `<${name}>`).join(" ")}.` : `${operation.name} takes no positional arguments.`);
2190
+ }
2191
+ const pathNames = new Set([...operation.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]));
2192
+ positionals.forEach((value, index) => {
2193
+ const name = open2[index];
2194
+ if (pathNames.has(name))
2195
+ params[name] = value;
2196
+ else
2197
+ query[name] = value;
2198
+ });
2199
+ const data = await readData(flags);
2200
+ if (extras.upload && data !== undefined)
2201
+ throw new CliError("--data does not apply to a file upload: the request body is the file.", 2, "validation_error");
2202
+ let body = data;
2203
+ if (extras.body) {
2204
+ if (data !== undefined && !isRecord(data))
2205
+ throw new CliError("--data must be a JSON object here.");
2206
+ body = { ...data, ...extras.body };
2207
+ }
2208
+ extras.checkBody?.(body);
2209
+ const etag = str(flags, "if-match");
2210
+ if (etag)
2211
+ headers["if-match"] = etag;
2212
+ for (const [name, value] of Object.entries(selectedHeaders))
2213
+ headers[name.toLowerCase()] = value;
2214
+ const dryRun = writing && !flags["no-dry-run"];
2215
+ const request = buildOperationRequest(extras.upload && dryRun ? { ...operation, dryRun: true } : operation, { params, query, body, headers, dryRun: !flags["no-dry-run"], idempotencyKey: str(flags, "idempotency-key") });
2216
+ if (extras.upload && dryRun) {
2217
+ const { file } = extras.upload;
2218
+ const shown2 = new URL(request.path, "https://request.invalid");
2219
+ shown2.searchParams.delete("dryRun");
2220
+ const upload = { field: file.field, filename: file.filename, bytes: file.size, sha256: await sha256File(file), contentType: file.contentType };
2221
+ emit({
2222
+ dryRun: true,
2223
+ serverConfirmed: false,
2224
+ request: { method: request.method, path: `${shown2.pathname}${shown2.search}`, upload },
2225
+ ...extras.upload.target ? { target: extras.upload.target } : {},
2226
+ approval: operation.approval,
2227
+ next: "Nothing was sent. Repeat with --no-dry-run --yes to upload this file."
2228
+ }, [
2229
+ `DRY RUN — nothing was sent. Would upload ${file.filename} (${file.size} bytes, sha256 ${upload.sha256}) with ${request.method} ${shown2.pathname}${shown2.search}`,
2230
+ ...extras.upload.target ? [`target: ${JSON.stringify(extras.upload.target)}`] : [],
2231
+ `approval: ${operation.approval}`,
2232
+ "Repeat with --no-dry-run --yes to upload this file."
2233
+ ].join(`
2234
+ `));
2235
+ return 0;
2063
2236
  }
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");
2237
+ const idempotencyKey = request.headers["Idempotency-Key"];
2238
+ if (writing && idempotencyKey && !dryRun)
2239
+ stderr(`Idempotency-Key: ${idempotencyKey} (reuse it with --idempotency-key after an uncertain delivery${operation.idempotencyDeclared ? "" : "; this operation does not declare replay protection"})`);
2240
+ if (extras.irreversible && !dryRun)
2241
+ stderr(`Warning: ${IRREVERSIBLE}`);
2242
+ const target2 = `${apiUrl}${request.path}`;
2243
+ if (writing && !dryRun && operation.dryRun && (operation.organization || extras.organizationInPath) && ctx.selection.organization && ctx.selection.organization.source !== "login" && !extras.upload) {
2244
+ const previewHeaders = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "idempotency-key"));
2245
+ const preview = buildOperationRequest(operation, { params, query, body, headers: previewHeaders, dryRun: true, idempotencyKey: crypto.randomUUID() });
2246
+ const checked = await requestJson(ctx.fetch, `${apiUrl}${preview.path}`, { ...preview, token, env });
2247
+ assertOrganizationMatches(checked.body, ctx.selection.organization, false, operation.path.replace(/\/$/, "") === "/v1/context");
2248
+ if (checked.status >= 400)
2249
+ throw httpError(checked.status, checked.body, operation.product);
2250
+ requireSuccess(checked.status);
2076
2251
  }
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");
2252
+ let result;
2253
+ if (extras.upload) {
2254
+ const sent = await requestMultipart(ctx.fetch, target2, { method: request.method, headers: request.headers, token, env, file: extras.upload.file });
2255
+ if (sent.status >= 200 && sent.status < 300 && sent.status !== 202)
2256
+ stderr(`Uploaded ${sent.sent.bytes} bytes (sha256 ${sent.sent.sha256}).`);
2257
+ result = sent;
2258
+ } else if (extras.download) {
2259
+ const answer = await requestBytes(ctx.fetch, target2, { headers: request.headers, token, env });
2260
+ if (answer.kind === "bytes")
2261
+ return emitDownload(answer, extras.download, operation, ctx);
2262
+ result = answer;
2263
+ } else
2264
+ result = await requestJson(ctx.fetch, target2, { ...request, token, env });
2265
+ assertOrganizationMatches(result.body, ctx.selection.organization, writing && !dryRun, operation.path.replace(/\/$/, "") === "/v1/context");
2266
+ 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;
2267
+ if (accepted)
2268
+ stderr("Note: accepted. The document is processed again in the background (status pending); read its status with the matching get command.");
2269
+ if (result.status === 202 && !accepted) {
2270
+ const pending = approvalResult(result.body, env);
2271
+ if (pending.warning)
2272
+ stderr(`Warning: ${pending.warning}`);
2273
+ const request202 = pending.approvalRequest;
2274
+ const id = typeof request202.approvalRequestId === "string" ? request202.approvalRequestId : typeof request202.id === "string" ? request202.id : undefined;
2275
+ const orgFlag = ctx.selection.organization && ctx.selection.organization.source !== "login" && operation.organization ? ` --org ${ctx.selection.organization.id}` : "";
2276
+ const follow = id && approvalsPath ? `prudai approvals wait ${id} --product ${operation.product}${orgFlag} --execute` : undefined;
2277
+ if (flags.wait && id && approvalsPath) {
2278
+ stderr(`APPROVAL REQUIRED. ${pending.next} Waiting (prudai approvals wait ${id}).`);
2279
+ return waitForApproval(ctx, { product: operation.product, origin: apiUrl, approvalsPath, organization: operation.organization, id, execute: true, timeoutSeconds: intFlag(flags, "timeout", 600, 5, 3600) });
2086
2280
  }
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 {}
2281
+ const out = { ...pending, ...follow ? { follow, next: `${pending.next} Then run: ${follow}` } : {} };
2282
+ emit(out, `APPROVAL REQUIRED. ${out.next}
2283
+ ${JSON.stringify(pending.approvalRequest, null, 2)}`);
2284
+ return 2;
2098
2285
  }
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;
2286
+ if (result.status >= 400) {
2287
+ if (operation.status === "planned" && [400, 404, 405, 501].includes(result.status) && !isEnvelopeLike(result.body)) {
2288
+ 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."] });
2133
2289
  }
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");
2290
+ throw httpError(result.status, result.body, operation.product);
2139
2291
  }
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");
2292
+ requireSuccess(accepted ? 200 : result.status);
2293
+ 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."] });
2294
+ if (extras.text && envelope)
2295
+ return emitText(envelope, extras.text, ctx);
2296
+ if (dryRun) {
2297
+ const shown2 = new URL(request.path, "https://request.invalid");
2298
+ shown2.searchParams.delete("dryRun");
2299
+ const next = `Nothing was executed. Repeat with --no-dry-run --yes to execute this request.${extras.after ? ` Afterwards: ${extras.after.action} (${extras.after.why})` : ""}`;
2300
+ const would = { method: request.method, path: `${shown2.pathname}${shown2.search}`, ...request.body !== undefined ? { body: request.body } : {} };
2301
+ const serverConfirmed = result.headers.get("x-prudai-dry-run") === "true" || envelope?.context.dry_run === true;
2302
+ if (extras.irreversible && !serverConfirmed) {
2303
+ 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");
2304
+ }
2305
+ emit({ dryRun: true, serverConfirmed, request: would, approval: operation.approval, ...extras.irreversible ? { irreversible: true, warning: IRREVERSIBLE } : {}, preview: envelope, next }, [
2306
+ `DRY RUN — nothing was executed. Would send: ${would.method} ${would.path}${request.body !== undefined ? ` ${JSON.stringify(request.body)}` : ""}`,
2307
+ `approval: ${operation.approval}`,
2308
+ ...extras.irreversible ? [`IRREVERSIBLE: ${IRREVERSIBLE}`] : [],
2309
+ ...envelope ? [renderEnvelope(envelope, { list: operation.kind === "list" })] : [],
2310
+ "Repeat with --no-dry-run --yes to execute this request.",
2311
+ ...extras.after ? [`Afterwards: ${extras.after.action} (${extras.after.why})`] : []
2312
+ ].join(`
2313
+ `));
2314
+ return 0;
2149
2315
  }
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");
2316
+ if (!envelope) {
2317
+ emit(localEnvelope(null, { context: { status: 204 }, provenance: { kind: "product", product: operation.product } }), "Done (no content).");
2318
+ return 0;
2173
2319
  }
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;
2320
+ const shown = extras.after ? { ...envelope, next: [...envelope.next, extras.after] } : envelope;
2321
+ emit(shown, renderEnvelope(shown, { list: operation.kind === "list" }));
2322
+ return 0;
2178
2323
  }
2179
- async function exchangeToken(options) {
2180
- const url = exchangeEndpoint(options.url, options.env);
2181
- let response;
2324
+ async function emitDownload(answer, options, operation, ctx) {
2325
+ const length = Number(answer.headers.get("content-length"));
2326
+ const encoded = /\S/.test(answer.headers.get("content-encoding") ?? "") && answer.headers.get("content-encoding").trim().toLowerCase() !== "identity";
2327
+ let written;
2182
2328
  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()
2329
+ written = await writeStreamToFile(options.out, answer.stream, { force: options.force, ...!encoded && answer.headers.has("content-length") && Number.isSafeInteger(length) && length >= 0 ? { expectedBytes: length } : {} });
2330
+ } finally {
2331
+ await answer.stream.cancel().catch(() => {
2332
+ return;
2189
2333
  });
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
2334
  }
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");
2335
+ const contentType = answer.headers.get("content-type")?.split(";")[0]?.trim() || null;
2336
+ const summary = { path: written.path, bytes: written.bytes, sha256: written.sha256, content_type: contentType };
2337
+ ctx.emit(localEnvelope(summary, {
2338
+ provenance: { kind: "product", product: operation.product },
2339
+ notIncluded: ["The file content: it was written to the path above (mode 0600), never to stdout."],
2340
+ next: [{ action: `sha256sum ${written.path}`, why: "Compare with the sha256 above to verify the file." }]
2341
+ }), JSON.stringify(summary, null, 2));
2342
+ return 0;
2343
+ }
2344
+ async function emitText(envelope, options, ctx) {
2345
+ const data = envelope.data;
2346
+ if (!isRecord(data) || typeof data.text !== "string")
2347
+ throw new CliError("The server answered without the text of the document.", 1, "invalid_response");
2348
+ const truncated = envelope.completeness.truncated === true;
2349
+ if (truncated)
2350
+ ctx.stderr(`Note: the text is truncated (${JSON.stringify(envelope.completeness)}). The text below is not the whole document.`);
2351
+ if (options.out !== undefined) {
2352
+ const written = await writeTextToFile(options.out, data.text, options.force);
2353
+ const summary = { path: written.path, bytes: written.bytes, sha256: written.sha256, characters: data.text.length, truncated };
2354
+ ctx.emit(localEnvelope(summary, {
2355
+ provenance: { kind: "product" },
2356
+ completeness: { truncated },
2357
+ notIncluded: ["The text itself: it was written to the path above (mode 0600), never to stdout."]
2358
+ }), JSON.stringify(summary, null, 2));
2359
+ return 0;
2221
2360
  }
2222
- throw new CliError(`The token broker is unavailable (HTTP ${status}); try again in a moment.`, 1, "exchange_unavailable");
2361
+ const plain = data.text.endsWith(`
2362
+ `) ? data.text.slice(0, -1) : data.text;
2363
+ ctx.emit(envelope, process.stdout.isTTY ? terminalSafe(plain) : plain);
2364
+ return 0;
2365
+ }
2366
+ var STATUS_HINT = {
2367
+ 400: "the request was refused as invalid (or this route is not served here yet)",
2368
+ 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)",
2369
+ 402: "a credit or spend limit was reached (prudai credits)",
2370
+ 403: "not allowed: a missing scope, role or product access, or an approval is required",
2371
+ 404: "not found, or not served by this API yet",
2372
+ 409: "conflict with the current state (check it and use --if-match)",
2373
+ 412: "the ETag no longer matches; read the record again",
2374
+ 422: "validation failed",
2375
+ 429: "rate limited; wait and retry reads (never blindly retry a write)"
2376
+ };
2377
+ function httpError(status, body, product) {
2378
+ const code = errorCodeOf(body);
2379
+ 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;
2380
+ const message2 = errorMessageOf(body) ?? STATUS_HINT[status] ?? (status >= 500 ? "server error; check state before retrying a write" : "request failed");
2381
+ return new CliError(`API returned HTTP ${status}${code ? ` (${code})` : ""}: ${message2}.${hint ? ` ${hint}` : ""}`, status >= 500 ? 1 : 2, code ?? `http_${status}`);
2382
+ }
2383
+ function errorCodeOf(body) {
2384
+ if (!isRecord(body))
2385
+ return;
2386
+ const context = isRecord(body.context) && isRecord(body.context.error) ? body.context.error.code : undefined;
2387
+ const nested = isRecord(body.error) ? body.error.code : undefined;
2388
+ 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);
2389
+ }
2390
+ function errorMessageOf(body) {
2391
+ if (!isRecord(body))
2392
+ return;
2393
+ const error = isRecord(body.context) && isRecord(body.context.error) ? body.context.error : isRecord(body.error) ? body.error : typeof body.message === "string" ? body : undefined;
2394
+ if (!error)
2395
+ return;
2396
+ const details = isRecord(error.details) ? error.details : isRecord(body.details) ? body.details : {};
2397
+ 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]}`);
2398
+ const parts = [typeof error.message === "string" ? error.message : undefined, ...extra].filter(Boolean);
2399
+ return parts.length ? parts.join("; ").replace(/prudai_(?:pat|sk_(?:live|test))_[A-Za-z0-9_-]+/g, "[redacted]").slice(0, 400) : undefined;
2223
2400
  }
2224
2401
 
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;
2402
+ // src/api.ts
2403
+ var METHODS2 = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
2404
+ var CLI_FLAG_NAMES = new Set([...BOOLEAN_FLAGS, ...GLOBAL_FLAGS, "product", "org", "registry", "spec"]);
2405
+ var HUMAN_ONLY_PATH = /\/approvals\/[^/]+\/(?:decision|approve|reject)\/?$/i;
2406
+ async function apiCommand(words, ctx) {
2407
+ const [rawMethod, rawPath, ...extra] = words;
2408
+ const method = rawMethod?.toUpperCase();
2409
+ if (!method || !METHODS2.has(method) || !rawPath || extra.length)
2410
+ throw new CliError("Usage: prudai api <GET|POST|PUT|PATCH|DELETE> </v1/path?query> [--product p] [--data json|@file]");
2411
+ if (!rawPath.startsWith("/") || rawPath.startsWith("//") || /(^|\/)\.\.?(\/|$|\?)/.test(rawPath) || /[\s#]/.test(rawPath))
2412
+ throw new CliError("The path must start with / and contain no '..', spaces or fragments.");
2413
+ const parsed = new URL(rawPath, "https://path.invalid");
2414
+ const path = parsed.pathname;
2415
+ let decoded;
2416
+ try {
2417
+ decoded = decodeURIComponent(path);
2418
+ } catch {
2419
+ throw new CliError("The path contains an invalid percent-encoding.");
2261
2420
  }
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
- });
2421
+ if (HUMAN_ONLY_PATH.test(path) || HUMAN_ONLY_PATH.test(decoded))
2422
+ 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");
2423
+ const wanted = str(ctx.flags, "product");
2424
+ if (wanted && !findProduct(wanted))
2425
+ throw new CliError(`Unknown product "${wanted}". Products: ${PRODUCTS.map((p) => p.product).join(", ")}.`);
2426
+ const catalogs = await loadCatalog(ctx.catalog, wanted ? [findProduct(wanted).product] : undefined);
2427
+ const matches = catalogs.flatMap((catalog2) => catalog2.commands.filter((command) => command.method === method && templateMatches(command.path, path)).map((command) => ({ catalog: catalog2, command })));
2428
+ const products = [...new Set(matches.map((entry) => entry.catalog.product))];
2429
+ if (!wanted && products.length > 1)
2430
+ throw new CliError(`${method} ${path} exists in ${products.join(" and ")}; add --product.`);
2431
+ const product = wanted ? findProduct(wanted).product : products[0] ?? PLATFORM_PRODUCT;
2432
+ 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];
2433
+ const catalog = catalogs.find((entry) => entry.product === product);
2434
+ const origin = resolveOrigin(product, ctx, catalog?.spec);
2435
+ if (match) {
2436
+ const templateParts = match.command.path.split("/");
2437
+ const values = path.split("/");
2438
+ const pathValues = templateParts.flatMap((part, index) => /^\{[^}]+\}$/.test(part) ? [decodeURIComponent(values[index])] : []);
2439
+ const declared = new Set(match.command.parameters.filter((p) => p.in === "query").map((p) => p.name));
2440
+ const queryFlags = {};
2441
+ for (const [key, value] of parsed.searchParams) {
2442
+ if (key === "dryRun")
2443
+ throw new CliError("Do not put dryRun in the path; the CLI sets it (use --no-dry-run --yes to execute).");
2444
+ if (CLI_FLAG_NAMES.has(key) || !declared.has(key))
2445
+ 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}.`);
2446
+ if (Object.hasOwn(ctx.flags, key) || Object.hasOwn(queryFlags, key))
2447
+ throw new CliError(`Query parameter ${key} given twice.`);
2448
+ queryFlags[key] = value;
2449
+ }
2450
+ const placeholders = [...match.command.path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
2451
+ const ordered = match.command.positionals.filter((name) => placeholders.includes(name));
2452
+ const positionals = ordered.map((name) => pathValues[placeholders.indexOf(name)]);
2453
+ const flags = { ...ctx.flags, ...queryFlags };
2454
+ delete flags.product;
2455
+ return executeOperation(match.command, positionals, origin, { ...ctx, flags });
2273
2456
  }
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 {}
2457
+ validateFlags(ctx.flags, ["json", "help", "yes", "no-dry-run", "dry-run", "profile", "product", "api-url", "data", "idempotency-key", "refresh", "offline", "org"]);
2458
+ const organization = organizationDeclaration(catalog?.spec);
2459
+ organizationHeaders(product, organization, ctx);
2460
+ if (!origin)
2461
+ throw new CliError(`Configure the ${product} API origin (--api-url).`);
2462
+ if (catalog?.notAvailable)
2463
+ 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).`);
2464
+ const apiUrl = safeApiOrigin(origin);
2465
+ requireTrustedOrigin(apiUrl, ctx.env);
2466
+ const token = await credentialFor(product, ctx);
2467
+ if (!token)
2468
+ throw missingCredential(product);
2469
+ const selectedHeaders = organizationHeaders(product, organization, ctx);
2470
+ const writing = method !== "GET";
2471
+ const body = await readData(ctx.flags);
2472
+ if (!writing && body !== undefined)
2473
+ throw new CliError("GET does not take --data.");
2474
+ if (writing && !(ctx.flags["no-dry-run"] && ctx.flags.yes)) {
2475
+ 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");
2289
2476
  }
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
- });
2477
+ const headers = { ...selectedHeaders };
2478
+ if (writing) {
2479
+ const key = str(ctx.flags, "idempotency-key") ?? crypto.randomUUID();
2480
+ if (!key.trim() || /[^\t\x20-\x7e]/.test(key))
2481
+ throw new CliError("Invalid Idempotency-Key.");
2482
+ headers["Idempotency-Key"] = key;
2483
+ ctx.stderr(`Idempotency-Key: ${key} (reuse it with --idempotency-key after an uncertain delivery)`);
2324
2484
  }
2325
- forget(product) {
2326
- this.products.delete(tokenProductFor(product));
2485
+ ctx.stderr(`Note: ${method} ${path} is not in the ${product} catalogue; sent as-is to ${apiUrl}.`);
2486
+ const result = await requestJson(ctx.fetch, `${apiUrl}${parsed.pathname}${parsed.search}`, { method, token, env: ctx.env, headers, ...body !== undefined ? { body } : {} });
2487
+ assertOrganizationMatches(result.body, ctx.selection.organization, writing, parsed.pathname.replace(/\/$/, "") === "/v1/context");
2488
+ if (result.status === 202) {
2489
+ const pending = approvalResult(result.body, ctx.env);
2490
+ if (pending.warning)
2491
+ ctx.stderr(`Warning: ${pending.warning}`);
2492
+ ctx.emit(pending, `APPROVAL REQUIRED. ${pending.next}`);
2493
+ return 2;
2327
2494
  }
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;
2495
+ if (result.status >= 400)
2496
+ throw httpError(result.status, result.body, product);
2497
+ 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."] });
2498
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
2499
+ return 0;
2335
2500
  }
2336
2501
 
2337
2502
  // src/auth.ts
2503
+ import { hostname } from "node:os";
2338
2504
  var clock = (o) => o.now ?? Date.now;
2339
2505
  var wait = (o) => o.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
2340
2506
  var env = (o) => o.env ?? {};
2507
+ function sessionDuration() {
2508
+ return {
2509
+ kind: "keycloak_offline",
2510
+ validUntil: null,
2511
+ note: "The login session lasts until logout, revocation or the Keycloak offline session policy expires it. Its exact duration is not supplied by the token response; it is not the access token lifetime."
2512
+ };
2513
+ }
2514
+ function accessDuration(validUntil) {
2515
+ return {
2516
+ validUntil: new Date(validUntil).toISOString(),
2517
+ note: "Short-lived access token; refreshed automatically while the login session remains valid. loginValidUntil is a compatibility alias for this access token expiry, not the session expiry."
2518
+ };
2519
+ }
2341
2520
  function identityOf(claims) {
2342
2521
  const name = claims.name ?? claims.username ?? null;
2343
2522
  return {
@@ -2393,6 +2572,8 @@ async function authLogin(options) {
2393
2572
  ...identity,
2394
2573
  device: hostname().slice(0, 60),
2395
2574
  loginValidUntil: new Date(tokens2.accessExpiresAt).toISOString(),
2575
+ accessToken: accessDuration(tokens2.accessExpiresAt),
2576
+ session: sessionDuration(),
2396
2577
  next: "Run `prudai whoami`, then `prudai guide`."
2397
2578
  };
2398
2579
  }
@@ -2414,8 +2595,8 @@ async function authStatus(options, online = false) {
2414
2595
  status: "authenticated",
2415
2596
  profile: config.profile,
2416
2597
  ...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." },
2598
+ login: { issuer: config.issuer, source: config.refreshSource === "env" ? "PRUDAI_REFRESH_TOKEN" : "config file", accessValidUntil: claims?.exp ? new Date(claims.exp * 1000).toISOString() : null, session: sessionDuration(), checkedOnline: online || !loginClaims(session) },
2599
+ access: { kind: "user_rights", note: "You act with your own role and rights in each product; there is no key or scope list. confirm may execute in shadow mode; review waits for a second person or is refused; forbidden_for_agents never executes." },
2419
2600
  products: accessMap(config),
2420
2601
  broker: config.exchangeUrl
2421
2602
  };
@@ -2470,7 +2651,8 @@ function authToken(options) {
2470
2651
  kind: "keycloak_login",
2471
2652
  source: config.refreshSource === "env" ? "environment (PRUDAI_REFRESH_TOKEN)" : "config file",
2472
2653
  issuer: config.issuer,
2473
- ...claims?.exp ? { loginValidUntil: new Date(claims.exp * 1000).toISOString() } : {},
2654
+ ...claims?.exp ? { loginValidUntil: new Date(claims.exp * 1000).toISOString(), accessToken: accessDuration(claims.exp * 1000) } : {},
2655
+ session: sessionDuration(),
2474
2656
  productTokens: { lifetime: "5 minutes, one product each, kept in memory only", products: TOKEN_PRODUCTS },
2475
2657
  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
2658
  };
@@ -2494,7 +2676,7 @@ async function authSet(options) {
2494
2676
  throw new CliError("Expected one Keycloak refresh token on stdin (from `prudai auth export --reveal`).", 2, "invalid_refresh_token");
2495
2677
  const tokens2 = await refreshLogin(config.issuer, refresh, { fetch: options.fetch, env: env(options), now: clock(options) });
2496
2678
  const identity = storeLogin(options, tokens2, before);
2497
- return { status: "stored", profile: config.profile, ...identity, next: "Run `prudai whoami` to check the login." };
2679
+ return { status: "stored", profile: config.profile, ...identity, accessToken: accessDuration(tokens2.accessExpiresAt), session: sessionDuration(), next: "Run `prudai whoami` to check the login." };
2498
2680
  }
2499
2681
  function authExport(options) {
2500
2682
  const refresh = options.session.refreshTokenValue;
@@ -2540,7 +2722,7 @@ function validate(raw) {
2540
2722
  throw new CliError("Invalid identity in configuration.", 2, "invalid_config");
2541
2723
  if (p.products !== undefined && (!Array.isArray(p.products) || p.products.some((v) => typeof v !== "string")))
2542
2724
  throw new CliError("Invalid products in configuration.", 2, "invalid_config");
2543
- for (const key of ["productApiUrls", "specs"]) {
2725
+ for (const key of ["productApiUrls", "specs", "orgs"]) {
2544
2726
  if (p[key] !== undefined && (!object2(p[key]) || Object.values(p[key]).some((v) => typeof v !== "string")))
2545
2727
  throw new CliError("Invalid product configuration.", 2, "invalid_config");
2546
2728
  }
@@ -3214,9 +3396,14 @@ async function platformCommand(words, ctx) {
3214
3396
  if (op.costsMoney)
3215
3397
  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
3398
  if (op.orgScoped) {
3217
- const org = str(ctx.flags, "org") ?? ctx.file.profiles[ctx.config.profile]?.organization?.id ?? undefined;
3399
+ const initial = organizationChoice("platform", ctx);
3400
+ if ((!initial || initial.source === "login") && ctx.config.refreshToken)
3401
+ await ctx.session.loginToken();
3402
+ const choice = organizationChoice("platform", ctx);
3403
+ const org = choice?.id;
3218
3404
  if (!org)
3219
3405
  throw new CliError("Name the organisation: --org <organization id> (prudai whoami shows yours).");
3406
+ ctx.selection.organization = choice;
3220
3407
  positionals = [org, ...positionals];
3221
3408
  }
3222
3409
  const origin = resolveOrigin(PLATFORM_PRODUCT, ctx, platform.spec);
@@ -3234,7 +3421,8 @@ async function platformCommand(words, ctx) {
3234
3421
  if (op.custom === "memos-list")
3235
3422
  return listMemos(access, command, project, ctx);
3236
3423
  const flags = { ...ctx.flags };
3237
- delete flags.org;
3424
+ if (op.orgScoped)
3425
+ delete flags.org;
3238
3426
  for (const entry of op.body ?? [])
3239
3427
  for (const name of [entry.flag, ...entry.aliases ?? []])
3240
3428
  delete flags[name];
@@ -3246,6 +3434,7 @@ async function platformCommand(words, ctx) {
3246
3434
  }
3247
3435
  const target2 = project ? { project: { id: project.id, name: project.name } } : upload && positionals[0] ? { knowledge_base: positionals[0] } : undefined;
3248
3436
  const extras = {
3437
+ ...op.orgScoped ? { organizationInPath: true } : {},
3249
3438
  ...body ? { body } : {},
3250
3439
  consumed: [...op.query ?? [], ...extraFlags.filter((entry) => entry.query).map((entry) => entry.query)],
3251
3440
  ...upload ? { upload: { file: upload, ...target2 ? { target: target2 } : {} } } : {},
@@ -3359,7 +3548,7 @@ function platformHelp() {
3359
3548
  }
3360
3549
 
3361
3550
  // src/version.ts
3362
- var VERSION = "0.1.1";
3551
+ var VERSION = "0.1.2";
3363
3552
 
3364
3553
  // src/discovery.ts
3365
3554
  var CATALOG_FLAGS = ["json", "help", "profile", "refresh", "offline", "spec", "registry", "api-url"];
@@ -3393,6 +3582,8 @@ var ERROR_CODES = {
3393
3582
  invalid_response: "The server answered with something that is not JSON.",
3394
3583
  invalid_envelope: "The server sent a malformed /v1 envelope.",
3395
3584
  invalid_spec: "A spec could not be read or turned into commands.",
3585
+ organization_not_supported: "The product declares no organisation header; omit --org or use a product that declares x-prudai-organization.",
3586
+ organization_mismatch: "The server reported another organization than selected. Its data is hidden; after a real write, check state before retrying.",
3396
3587
  unknown_profile: "The selected profile does not exist; create it or pick another.",
3397
3588
  "<server code>": "Other HTTP errors carry the product's own code (context.error.code), e.g. not_found, conflict.",
3398
3589
  "http_<status>": "An HTTP error without a recognisable code; the message gives a hint per status.",
@@ -3462,7 +3653,12 @@ plus ops search and describe are enough.
3462
3653
  prudai describe <product> <command…> parameters, body schema + example, responses, curl
3463
3654
  prudai describe irma:<operationId> …or by operationId, or: prudai describe GET /v1/risks
3464
3655
  prudai describe keys create platform commands too: route, scope, approval, status
3465
- prudai <product> help every command of one product
3656
+ prudai <product> help object summary; --all lists every command
3657
+ prudai ops search "setup" --product irma
3658
+ NL/EN synonyms also find onboarding, organisations and frameworks
3659
+ IRMA start: prudai irma context read its ordered next steps and follow the startpad/status
3660
+ operation it names. A human loads a normenkader in the app first;
3661
+ agents build concepts/proposals for a human to adopt.
3466
3662
  prudai help --json machine-readable command list
3467
3663
  Products:
3468
3664
  ${products}
@@ -3479,16 +3675,30 @@ ${products}
3479
3675
  or export PRUDAI_REFRESH_TOKEN (the refresh token of such a login). A person can end any session.
3480
3676
  Check: prudai whoami (= auth status: user, organisation; --online proves the session still lives)
3481
3677
  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.
3678
+ belongs to one Keycloak organisation; another login uses another profile.
3679
+ Product environment: organisation selection works only for a product whose spec declares
3680
+ x-prudai-organization. IRMA supports it once that release is live; until then an explicit
3681
+ selection returns organization_not_supported. Explicit priority: --org > PRUDAI_<PRODUCT>_ORG >
3682
+ prudai profile set orgs.<product> <id>. Only a flag, environment or profile choice sends
3683
+ the declared header. Without these, the product uses the login organisation without an
3684
+ organisation header; no mismatch check is made against the login organisation. The output
3685
+ uses the server-reported organisation with source login.
3686
+ With an explicit choice, a different organization id in the server response gives
3687
+ organization_mismatch (exit 2), with no response data shown. Real writes preview first where
3688
+ the operation declares dry run; otherwise a mismatch is detected after the write, which may
3689
+ already have happened elsewhere.
3690
+ whoami shows the product organisation map; whoami --product irma --org <id> checks a selection.
3691
+ Platform commands keep --org as their organisation path id: flag > PRUDAI_PLATFORM_ORG >
3692
+ profile orgs.platform > login organisation.
3483
3693
  Token for another tool, without printing it:
3484
3694
  curl -H "Authorization: Bearer $(prudai auth token --reveal --product irma)" … (never run --reveal bare)
3485
3695
  prudai logout ends the session at Keycloak first. Tokens are only sent to https://*.prudai.com and
3486
3696
  localhost; another origin needs PRUDAI_ALLOW_ORIGIN=<exact origin> in the environment.
3487
3697
 
3488
3698
  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.
3699
+ read scopes never need a person. write and delete operations carry an approval level
3700
+ (confirm, review, …; see 6); this does not mean every write waits for another person.
3701
+ A key needs the scope; the server applies the operation's approval level and product mode per call.
3492
3702
  Wildcard <product>:*:<verb> covers every object of that product and verb, including later
3493
3703
  ones — but never explicit-only objects (licensed text, credit-spending chat/answers, api_keys,
3494
3704
  subscriptions). Invalid: *, *:x:read, p:*:*, p:o:*. prudai keys scopes lists them once the platform serves
@@ -3516,8 +3726,14 @@ ${products}
3516
3726
  --if-match <etag> for optimistic concurrency. Deletes are soft (restore exists).
3517
3727
 
3518
3728
  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).
3729
+ Levels per operation (x-prudai-approval), always subject to the product's permissions:
3730
+ none / instruct: no second-person review; writes still need --no-dry-run --yes.
3731
+ confirm: in shadow mode, --no-dry-run --yes executes directly within the agent's allowed
3732
+ concept/proposal boundary. In enforce mode, follow the server's approval response.
3733
+ review: waits for a second person where supported; it can instead be refused with
3734
+ approval_requires_enforce in shadow mode. A product administrator enables enforce;
3735
+ use the product app for the human action meanwhile. Do not bypass a refusal.
3736
+ forbidden_for_agents: never allowed for an agent (refused locally); a human acts in the app.
3521
3737
  HTTP 202 = approval_required, exit 2, NOT success. The answer shows the approval link (only
3522
3738
  for trusted Prudai origins) and: prudai approvals wait <id> --product <p> --execute
3523
3739
  which waits for the human decision and then lets the server run exactly the approved call.
@@ -3634,7 +3850,10 @@ var HELP = {
3634
3850
  "--refresh",
3635
3851
  "--offline",
3636
3852
  "--out <path> [--force]",
3637
- "--project <id|name>"
3853
+ "--project <id|name>",
3854
+ "--org <id>",
3855
+ "--all",
3856
+ "--version / -v"
3638
3857
  ],
3639
3858
  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
3859
  exitCodes: EXIT_CODES,
@@ -3789,11 +4008,45 @@ function param(parameter) {
3789
4008
  `)[0].slice(0, 200) } : {}
3790
4009
  };
3791
4010
  }
4011
+ function bodySchemaLines(schema, prefix = "", depth = 0) {
4012
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
4013
+ return [` ${prefix || "body"} | ${String(schema)} | — | — | —`];
4014
+ const node = schema;
4015
+ if (depth > 12)
4016
+ return [` ${prefix || "body"} | nested schema; use --json | — | — | —`];
4017
+ const required = Array.isArray(node.required) ? node.required : [];
4018
+ const lines = [];
4019
+ if (node.properties && typeof node.properties === "object" && !Array.isArray(node.properties)) {
4020
+ for (const [name, value] of Object.entries(node.properties)) {
4021
+ const field = value && typeof value === "object" && !Array.isArray(value) ? value : {};
4022
+ const path = prefix ? `${prefix}.${name}` : name;
4023
+ const type = Array.isArray(field.type) ? field.type.join(" | ") : field.type ?? (field.properties ? "object" : field.items ? "array" : field.oneOf ? "oneOf" : field.anyOf ? "anyOf" : field.allOf ? "allOf" : "any");
4024
+ lines.push(` ${path} | ${type}${field.nullable ? " | null" : ""}${field.format ? ` (${field.format})` : ""} | ${required.includes(name) ? "required" : "optional"} | ${Array.isArray(field.enum) ? field.enum.map((v) => JSON.stringify(v)).join(", ") : field.const !== undefined ? JSON.stringify(field.const) : "—"} | ${typeof field.description === "string" ? field.description.replace(/\s+/g, " ").trim() : "—"}`);
4025
+ if (field.properties || field.allOf || field.anyOf || field.oneOf)
4026
+ lines.push(...bodySchemaLines(field, path, depth + 1));
4027
+ if (field.items)
4028
+ lines.push(...bodySchemaLines(field.items, `${path}[]`, depth + 1));
4029
+ }
4030
+ }
4031
+ for (const key of ["allOf", "oneOf", "anyOf"]) {
4032
+ if (Array.isArray(node[key]))
4033
+ for (const [index, variant] of node[key].entries()) {
4034
+ lines.push(...bodySchemaLines(variant, key === "allOf" ? prefix : `${prefix || "body"}[${key} ${index + 1}]`, depth + 1));
4035
+ }
4036
+ }
4037
+ if (!lines.length) {
4038
+ const type = Array.isArray(node.type) ? node.type.join(" | ") : node.type ?? (node.items ? "array" : "any");
4039
+ lines.push(` ${prefix || "body"} | ${type} | — | ${Array.isArray(node.enum) ? node.enum.map((v) => JSON.stringify(v)).join(", ") : "—"} | ${typeof node.description === "string" ? node.description.replace(/\s+/g, " ").trim() : "—"}`);
4040
+ if (node.items)
4041
+ lines.push(...bodySchemaLines(node.items, `${prefix || "body"}[]`, depth + 1));
4042
+ }
4043
+ return lines;
4044
+ }
3792
4045
  function describeCommand(command, catalog) {
3793
4046
  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
4047
  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
4048
  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;
4049
+ const body = command.inputSchema !== undefined ? { required: command.bodyRequired === true, schema: command.inputSchema, example: exampleFrom(command.inputSchema, "body") } : undefined;
3797
4050
  const base = ["prudai", command.product, command.name, ...command.positionals.map((name) => `<${name}>`)].join(" ");
3798
4051
  const dataArg = body ? ` --data '${JSON.stringify(body.example)}'` : "";
3799
4052
  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("] [")}]` : ""}`];
@@ -3868,7 +4121,8 @@ async function describePlatform(op, ctx) {
3868
4121
  `${doc.command}`,
3869
4122
  `${op.method} ${op.path} — ${op.summary}`,
3870
4123
  `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}` : ""}`)] : []
4124
+ ...flags.length ? ["flags:", ...flags.map((f) => ` ${f.flag}${"field" in f ? ` → ${f.field}` : ""}`)] : [],
4125
+ ...doc.operation?.body ? [`body${doc.operation.body.required ? " (required)" : ""}:`, " field | type | presence | enum | description", ...bodySchemaLines(doc.operation.body.schema), `example: ${JSON.stringify(doc.operation.body.example)}`] : []
3872
4126
  ].join(`
3873
4127
  `));
3874
4128
  return 0;
@@ -3896,7 +4150,7 @@ async function describeOperationCommand(words, ctx) {
3896
4150
  const doc = describeCommand(found.command, found.catalog);
3897
4151
  ctx.emit(localEnvelope(doc, {
3898
4152
  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."],
4153
+ notIncluded: ["Parameter descriptions are compacted; --json includes the complete resolved body schema."],
3900
4154
  next: [{ action: doc.examples.cli[0].replace(/\s+#.*$/, ""), why: found.command.method === "GET" ? "Run it." : "Preview it first." }]
3901
4155
  }), [
3902
4156
  `${doc.command}`,
@@ -3909,7 +4163,7 @@ ${doc.description}
3909
4163
  ...doc.idempotency ? [`idempotency: key always sent; replay protection ${doc.idempotency.declared ? "declared" : "not declared"}`] : [],
3910
4164
  ...doc.positionals.length ? ["positionals:", ...doc.positionals.map((p) => ` <${p.name}> (${p.in}${p.required ? ", required" : ""}) ${p.type ?? ""} ${p.description ?? ""}`)] : [],
3911
4165
  ...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)}`] : [],
4166
+ ...doc.body ? [`body${doc.body.required ? " (required)" : ""}:`, " field | type | presence | enum | description", ...bodySchemaLines(doc.body.schema), `example: ${JSON.stringify(doc.body.example)}`] : [],
3913
4167
  `responses: ${doc.responses.map((r) => `${r.status}${r.description ? ` ${r.description}` : ""}`).join("; ")}`,
3914
4168
  "examples:",
3915
4169
  ...doc.examples.cli.map((line) => ` ${line}`),
@@ -3939,11 +4193,30 @@ description: Use the Prudai CLI (\`prudai\`) for anything with Prudai — LEO, I
3939
4193
  \`prudai\` is the complete interface to Prudai for people and agents. Do not guess routes or
3940
4194
  scopes: discover them.
3941
4195
 
4196
+ Organisation selection works only for a product whose spec declares \`x-prudai-organization\`.
4197
+ IRMA supports it once that release is live; until then an explicit selection returns
4198
+ \`organization_not_supported\`. Explicit priority: \`--org <id>\` > \`PRUDAI_<PRODUCT>_ORG\` >
4199
+ \`profile set orgs.<product> <id>\`. Only a flag, environment or profile choice sends the declared
4200
+ header. Without these, the product uses the login organisation without an organisation header;
4201
+ no mismatch check is made against the login organisation. The output uses the server-reported
4202
+ organisation with source login. The server checks your access.
4203
+ \`whoami --product irma --org <id>\` shows the effective choice; plain \`whoami\` shows configured
4204
+ product choices. Platform commands place the organisation id in the route, with priority flag >
4205
+ \`PRUDAI_PLATFORM_ORG\` > \`profile orgs.platform\` > login. Begin IRMA work with \`prudai irma context\`
4206
+ and follow \`next\`: a missing framework must first be loaded by a person in the app.
4207
+ Use \`--help\` after any command; \`prudai irma help\` summarises objects and \`--all\` lists
4208
+ all operations. Search accepts NL/EN synonyms for setup, onboarding, organisations and frameworks.
4209
+ Without \`--json\`, lists show a table followed by completeness and next steps; \`describe\`
4210
+ shows body fields with type, required, enum and description. \`--json\` keeps one JSON document
4211
+ with the raw schema. \`prudai --version\` (or \`-v\`) prints the CLI version.
4212
+
3942
4213
  1. \`prudai ops search "<what you want>"\` — operations across all products, with the exact
3943
4214
  command, scope, approval level (HITL) and cost.
3944
4215
  2. \`prudai describe <product> <command…>\` — parameters, body schema, an example and curl.
3945
4216
  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:
4217
+ \`--no-dry-run --yes\` to request execution. \`confirm\` may execute directly in shadow;
4218
+ \`review\` waits for a second person or is refused; \`forbidden_for_agents\` never runs.
4219
+ HTTP 202 = a human must approve:
3947
4220
  \`prudai approvals wait <id> --product <p> --execute\`.
3948
4221
  4. Exit codes: 0 done · 1 network/server (check state before retrying a write) · 2 you must act.
3949
4222
  "not available yet" (error not_available) means the platform has not built it: say so,
@@ -3958,8 +4231,14 @@ service runs them the answer is 403 \`approval_required\` and nothing happened;
3958
4231
 
3959
4232
  Never pass credentials as flags, never print a token (\`auth token --reveal\` only inside
3960
4233
  \`$(…)\`), 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.
4234
+ or \`PRUDAI_REFRESH_TOKEN\` on a runner that logged in once. Login output separates the
4235
+ short-lived access token expiry from the offline login session, whose duration is governed by
4236
+ Keycloak policy; \`loginValidUntil\` is only the compatibility alias for access token expiry.
3962
4237
  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.
4238
+ For an explicit flag, environment or profile choice, organization_mismatch (exit 2) hides the response
4239
+ data: the server reported another organization than selected.
4240
+ Real writes preview first where declared; without a declared dry run a mismatch can be detected only
4241
+ after the write, so check the other organization's state before retrying.
3963
4242
 
3964
4243
  | Product | What | Operations | Catalogue |
3965
4244
  | --- | --- | --- | --- |
@@ -4083,11 +4362,11 @@ function matchCommand(commands, rest) {
4083
4362
  }
4084
4363
  return;
4085
4364
  }
4086
- var PROFILE_KEYS = /^(?:(productApiUrls|specs)\.([a-z][a-z0-9-]{0,63})|(registryUrl))$/;
4365
+ var PROFILE_KEYS = /^(?:(productApiUrls|specs|orgs)\.([a-z][a-z0-9-]{0,63})|(registryUrl))$/;
4087
4366
  function setProfileValue(profile, key, value, env2, stderr) {
4088
4367
  const match2 = PROFILE_KEYS.exec(key);
4089
4368
  if (!match2)
4090
- throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, registryUrl.");
4369
+ throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, orgs.<product>, registryUrl.");
4091
4370
  const next = { ...profile };
4092
4371
  if (match2[3]) {
4093
4372
  if (value === undefined) {
@@ -4109,6 +4388,10 @@ function setProfileValue(profile, key, value, env2, stderr) {
4109
4388
  map[product] = safeApiOrigin(value);
4110
4389
  if (!isTrustedOrigin(map[product], env2))
4111
4390
  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.`);
4391
+ } else if (field === "orgs") {
4392
+ if (!value.trim() || /[^\x21-\x7e]/.test(value))
4393
+ throw new CliError("Organization id must be a non-empty value without spaces or control characters.");
4394
+ map[product] = value;
4112
4395
  } else {
4113
4396
  if (!value.trim())
4114
4397
  throw new CliError("A spec source must be a path or URL.");
@@ -4240,7 +4523,7 @@ var BUILTINS = new Set([
4240
4523
  var ALIASES = { login: ["auth", "login"], logout: ["auth", "logout"], whoami: ["auth", "status"] };
4241
4524
  async function authCommand(words, ctx, options) {
4242
4525
  const { flags, env: env2, config, file } = ctx;
4243
- validateFlags(flags, new Set(["json", "profile", "no-browser", "stdin", "reveal", "online", "product", "device-name"]));
4526
+ validateFlags(flags, new Set(["json", "profile", "no-browser", "stdin", "reveal", "online", "product", "device-name", "org", "spec", "registry", "api-url", "refresh", "offline"]));
4244
4527
  const action = words[1];
4245
4528
  if (action === "switch-org")
4246
4529
  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");
@@ -4254,8 +4537,18 @@ async function authCommand(words, ctx, options) {
4254
4537
  throw new CliError("--reveal belongs to prudai auth token and prudai auth export.");
4255
4538
  if (flags.online && action !== "status")
4256
4539
  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.");
4540
+ if (flags.product && action !== "token" && action !== "status")
4541
+ throw new CliError("--product belongs to prudai auth token or status.");
4542
+ if (flags.org && (action !== "status" || !flags.product))
4543
+ throw new CliError("Use prudai whoami --product <product> --org <id> to inspect an environment selection.");
4544
+ let statusCatalog;
4545
+ if (action === "status" && flags.product) {
4546
+ const product = findProduct(str(flags, "product"))?.product ?? str(flags, "product");
4547
+ const catalog = await loadProductCatalog(product, ctx.catalog);
4548
+ throwIfUnusable(catalog);
4549
+ statusCatalog = catalog;
4550
+ organizationHeaders(product, organizationDeclaration(catalog.spec), ctx);
4551
+ }
4259
4552
  const save = options.saveConfig ?? ((cfg) => writeConfig(configPath(env2), cfg));
4260
4553
  const authOptions = {
4261
4554
  config,
@@ -4288,9 +4581,19 @@ async function authCommand(words, ctx, options) {
4288
4581
  ctx.emit(localEnvelope(meta, { provenance: { kind: "local" }, notIncluded: ["The secret itself; use --reveal only inside $(…)."] }), JSON.stringify(meta, null, 2));
4289
4582
  return 0;
4290
4583
  }
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) : (() => {
4584
+ let result = action === "login" ? await authLogin(authOptions) : action === "status" ? await authStatus(authOptions, !!flags.online) : action === "logout" ? await authLogout(authOptions) : action === "set" ? await authSet(authOptions) : (() => {
4292
4585
  throw new CliError("Unknown auth command. Use login, status, logout, token, export or set --stdin.");
4293
4586
  })();
4587
+ if (action === "status" && isRecord(result)) {
4588
+ if (statusCatalog)
4589
+ organizationHeaders(statusCatalog.product, organizationDeclaration(statusCatalog.spec), ctx);
4590
+ const products = new Set([...Object.keys(config.orgs ?? {}), ...Object.keys(env2).flatMap((key) => /^PRUDAI_([A-Z0-9_]+)_ORG$/.exec(key)?.[1]?.toLowerCase().replaceAll("_", "-") ?? [])]);
4591
+ result = {
4592
+ ...result,
4593
+ selectedOrganizations: Object.fromEntries([...products].map((product) => [product, organizationChoice(product, ctx, false)])),
4594
+ ...ctx.selection.organization ? { selectedOrganization: ctx.selection.organization } : {}
4595
+ };
4596
+ }
4294
4597
  const message2 = result.message;
4295
4598
  ctx.emit(localEnvelope(result, { provenance: { kind: "auth", origin: config.issuer } }), typeof message2 === "string" ? `${message2}
4296
4599
  ${JSON.stringify(result, null, 2)}` : JSON.stringify(result, null, 2));
@@ -4307,8 +4610,35 @@ async function productCommand(words, ctx) {
4307
4610
  for (const warning of catalog.warnings)
4308
4611
  ctx.stderr(`Warning: ${warning}`);
4309
4612
  const product = catalog.product;
4613
+ organizationHeaders(product, organizationDeclaration(catalog.spec), ctx);
4614
+ if (ctx.flags.help && words.length > 1 && words[1] !== "help") {
4615
+ const matched2 = matchCommand(catalog.commands, words.slice(1));
4616
+ if (matched2) {
4617
+ const flags = Object.fromEntries(Object.entries(ctx.flags).filter(([name]) => ["json", "help", "profile", "spec", "registry", "api-url", "refresh", "offline"].includes(name)));
4618
+ return describeOperationCommand([product, ...matched2.operation.words], { ...ctx, flags });
4619
+ }
4620
+ const scoped = catalog.commands.filter((entry) => entry.resource === words.slice(1).join(" "));
4621
+ if (!scoped.length)
4622
+ throw new CliError(`Unknown ${product} command. Run prudai ${product} help.`);
4623
+ ctx.emit(localEnvelope(scoped), scoped.map((entry) => `prudai ${product} ${entry.name} ${entry.summary}`).join(`
4624
+ `));
4625
+ return 0;
4626
+ }
4310
4627
  if (words[1] === "help" || ctx.flags.help || words.length === 1) {
4311
- validateFlags(ctx.flags, GLOBAL_FLAGS);
4628
+ validateFlags(ctx.flags, [...GLOBAL_FLAGS, "all"]);
4629
+ const groups = new Map;
4630
+ for (const entry of catalog.commands)
4631
+ groups.set(entry.resource, [...groups.get(entry.resource) ?? [], entry]);
4632
+ const objects = [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([object3, entries]) => ({
4633
+ object: object3,
4634
+ operations: entries.length,
4635
+ description: (entries.find((entry) => entry.kind === "list") ?? entries[0]).summary
4636
+ }));
4637
+ const lines = ctx.flags.all ? [...groups].sort(([a], [b]) => a.localeCompare(b)).flatMap(([object3, entries]) => [
4638
+ `
4639
+ ${object3} (${entries.length})`,
4640
+ ...entries.map((entry) => ` ${[entry.name, ...entry.positionals.map((name) => `<${name}>`)].join(" ").padEnd(48)} ${entry.method} ${entry.path} approval: ${entry.approval}`)
4641
+ ]) : objects.map((entry) => ` ${entry.object.padEnd(36)} ${String(entry.operations).padStart(3)} ${entry.description}`);
4312
4642
  ctx.emit(localEnvelope(catalog.commands, {
4313
4643
  context: { product, origin: catalog.origin || null },
4314
4644
  provenance: { kind: "catalog", source: catalog.source ?? null },
@@ -4316,7 +4646,8 @@ async function productCommand(words, ctx) {
4316
4646
  next: [{ action: `prudai describe ${product} <command>`, why: "Parameters, body and examples." }]
4317
4647
  }), [
4318
4648
  `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}`)
4649
+ `${objects.length} objects. Use prudai ${product} help --all for every operation, or prudai ${product} <object> --help.`,
4650
+ ...lines
4320
4651
  ].join(`
4321
4652
  `));
4322
4653
  return 0;
@@ -4331,6 +4662,8 @@ async function runCli(args, options = {}) {
4331
4662
  const stderr = options.stderr ?? ((text) => console.error(text));
4332
4663
  const json = args.includes("--json");
4333
4664
  const secrets = new Set;
4665
+ const selection = {};
4666
+ let platformOutput = false;
4334
4667
  let revealing = false;
4335
4668
  const redact = (text) => {
4336
4669
  if (revealing)
@@ -4341,7 +4674,22 @@ async function runCli(args, options = {}) {
4341
4674
  out = out.split(secret).join("[redacted]");
4342
4675
  return out;
4343
4676
  };
4344
- const emit = (value, human) => stdout(redact(json ? JSON.stringify(value) : human ?? JSON.stringify(value, null, 2)));
4677
+ const emit = (value, human) => {
4678
+ if (selection.organization && isRecord(value)) {
4679
+ const context = isRecord(value.context) ? value.context : {};
4680
+ const serverOrganization = isRecord(context.organization) ? context.organization : {};
4681
+ const selected = {
4682
+ ...selection.organization,
4683
+ ...platformOutput ? { product: "platform" } : {},
4684
+ ...selection.organization.source === "login" && typeof serverOrganization.id === "string" ? { id: serverOrganization.id } : {}
4685
+ };
4686
+ value = { ...value, context: { ...context, organization: { ...serverOrganization, ...selected } } };
4687
+ if (human !== undefined)
4688
+ human += `
4689
+ organization: ${selected.id} (${selected.product}; ${selected.source})`;
4690
+ }
4691
+ stdout(redact(json ? JSON.stringify(value) : human ?? (isEnvelopeLike(value) ? renderEnvelope(value) : JSON.stringify(value, null, 2))));
4692
+ };
4345
4693
  const errOut = (text) => stderr(redact(text));
4346
4694
  try {
4347
4695
  const first = args.findIndex((arg) => !arg.startsWith("-"));
@@ -4355,6 +4703,23 @@ async function runCli(args, options = {}) {
4355
4703
  const parsed = parseArgs(args);
4356
4704
  const flags = parsed.flags;
4357
4705
  let words = parsed.words;
4706
+ if (flags.version === true) {
4707
+ validateFlags(flags, ["json", "version"]);
4708
+ if (words.length)
4709
+ throw new CliError("Usage: prudai --version | -v | version");
4710
+ emit(localEnvelope({ name: "prudai", version: VERSION }), VERSION);
4711
+ return 0;
4712
+ }
4713
+ if (flags.help && words.length && words[0] !== "help" && BUILTINS.has(words[0])) {
4714
+ const requested = words.join(" ");
4715
+ const alias = ALIASES[words[0]];
4716
+ const group = alias?.[0] ?? words[0];
4717
+ const commands = HELP.commands.filter((line) => line === group || line.startsWith(`${group} `));
4718
+ const data = { command: requested, usage: commands.map((line) => `prudai ${line}`), flags: HELP.flags };
4719
+ emit(localEnvelope(data), [`Help: prudai ${requested}`, ...data.usage, `Flags: ${HELP.flags.join(" ")}`].join(`
4720
+ `));
4721
+ return 0;
4722
+ }
4358
4723
  if (words[0] && ALIASES[words[0]])
4359
4724
  words = [...ALIASES[words[0]], ...words.slice(1)];
4360
4725
  const command = words[0];
@@ -4396,7 +4761,7 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4396
4761
  const now = options.now ?? Date.now;
4397
4762
  const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
4398
4763
  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;
4764
+ const productWord = command === "describe" ? words[1] : command === "ops" || command === "api" || command === "approvals" || command === "auth" ? str(flags, "product") : command;
4400
4765
  const named = productWord ? findProduct(productWord)?.product ?? productWord : undefined;
4401
4766
  const catalog = {
4402
4767
  env: env2,
@@ -4418,7 +4783,7 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4418
4783
  revealing = true;
4419
4784
  };
4420
4785
  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 };
4786
+ const ctx = { options, env: env2, file, config, flags, json, emit, stderr: errOut, fetch: fetchImpl, now, sleep, catalog, reveal, session, selection };
4422
4787
  if (command === "auth")
4423
4788
  return await authCommand(words, ctx, options);
4424
4789
  if (command === "guide")
@@ -4437,8 +4802,10 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4437
4802
  return await skillCommand(words.slice(1), ctx);
4438
4803
  if (command === "mcp" && words[1] !== "connections")
4439
4804
  return await mcpCommand(words.slice(1), ctx);
4440
- if (command === "mcp" || PLATFORM_GROUPS.has(command))
4805
+ if (command === "mcp" || PLATFORM_GROUPS.has(command)) {
4806
+ platformOutput = true;
4441
4807
  return await platformCommand(words, ctx);
4808
+ }
4442
4809
  return await productCommand(words, ctx);
4443
4810
  } catch (error) {
4444
4811
  const failure = error instanceof CliError ? error : new CliError("Unexpected local or server failure.", 1, "unexpected_error");