@prudai/cli 0.1.0 → 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/index.js CHANGED
@@ -222,9 +222,61 @@ function parseEnvelope(body) {
222
222
  }
223
223
  return body;
224
224
  }
225
- function renderEnvelope(body) {
225
+ function envelopeRows(data) {
226
+ if (Array.isArray(data))
227
+ return { rows: data };
228
+ if (!isRecord(data))
229
+ return;
230
+ if (Object.hasOwn(data, "id") && (data.id === null || typeof data.id !== "object"))
231
+ return;
232
+ const arrays = Object.entries(data).filter(([, value]) => Array.isArray(value));
233
+ if (arrays.length !== 1)
234
+ return;
235
+ const [key, rows] = arrays[0];
236
+ if (!Array.isArray(rows) || !rows.every(isRecord))
237
+ return;
238
+ const { [key]: _rows, ...metadata } = data;
239
+ return { rows, ...Object.keys(metadata).length ? { metadata } : {} };
240
+ }
241
+ function renderTable(rows) {
242
+ if (!rows.length)
243
+ return "No items.";
244
+ const records = rows.map((row) => isRecord(row) ? row : { value: row });
245
+ const fields = [...new Set(records.flatMap((row) => Object.keys(row)))];
246
+ const priority = ["id", "name", "title", "label", "filename", "file_name", "email", "status", "state", "kind", "type", "code", "reference", "role", "summary", "created_at", "createdAt", "updated_at", "updatedAt"];
247
+ const columns = [...priority.filter((key) => fields.includes(key)), ...fields.filter((key) => !priority.includes(key))].slice(0, 6);
248
+ if (!columns.length)
249
+ return `${rows.length} empty records.`;
250
+ let shortened = fields.length > columns.length;
251
+ const cell = (value) => {
252
+ const text = (value === undefined || value === null ? "-" : typeof value === "string" ? value : JSON.stringify(value)).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
253
+ if (text.length <= 64)
254
+ return text;
255
+ shortened = true;
256
+ return `${text.slice(0, 63)}…`;
257
+ };
258
+ const headings = columns.map((key) => key.replaceAll("_", " ").toUpperCase());
259
+ const cells = records.map((row) => columns.map((key) => cell(row[key])));
260
+ const widths = headings.map((heading) => heading.length);
261
+ for (const row of cells)
262
+ row.forEach((value, index) => {
263
+ widths[index] = Math.max(widths[index], value.length);
264
+ });
265
+ const line = (values) => values.map((value, index) => value.padEnd(widths[index])).join(" ").trimEnd();
266
+ return [
267
+ line(headings),
268
+ line(widths.map((width) => "-".repeat(width))),
269
+ ...cells.map(line),
270
+ ...shortened ? ["Table shows core fields or shortened values; use --json for the full data."] : []
271
+ ].join(`
272
+ `);
273
+ }
274
+ function renderEnvelope(body, options = {}) {
275
+ const collection = options.list === false ? undefined : envelopeRows(body.data);
226
276
  return [
227
- JSON.stringify(body.data, null, 2),
277
+ collection ? renderTable(collection.rows) : JSON.stringify(body.data, null, 2),
278
+ ...collection?.metadata ? [`Data metadata: ${JSON.stringify(collection.metadata)}`] : [],
279
+ ...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"}`] : [],
228
280
  `Context: ${JSON.stringify(body.context)}`,
229
281
  `Completeness: ${JSON.stringify(body.completeness)}`,
230
282
  `Not included: ${JSON.stringify(body.notIncluded)}`,
@@ -303,7 +355,7 @@ function validate(raw) {
303
355
  throw new CliError("Invalid identity in configuration.", 2, "invalid_config");
304
356
  if (p.products !== undefined && (!Array.isArray(p.products) || p.products.some((v) => typeof v !== "string")))
305
357
  throw new CliError("Invalid products in configuration.", 2, "invalid_config");
306
- for (const key of ["productApiUrls", "specs"]) {
358
+ for (const key of ["productApiUrls", "specs", "orgs"]) {
307
359
  if (p[key] !== undefined && (!object(p[key]) || Object.values(p[key]).some((v) => typeof v !== "string")))
308
360
  throw new CliError("Invalid product configuration.", 2, "invalid_config");
309
361
  }
@@ -738,6 +790,19 @@ function loginClaims(session) {
738
790
  var clock = (o) => o.now ?? Date.now;
739
791
  var wait = (o) => o.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
740
792
  var env = (o) => o.env ?? {};
793
+ function sessionDuration() {
794
+ return {
795
+ kind: "keycloak_offline",
796
+ validUntil: null,
797
+ 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."
798
+ };
799
+ }
800
+ function accessDuration(validUntil) {
801
+ return {
802
+ validUntil: new Date(validUntil).toISOString(),
803
+ 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."
804
+ };
805
+ }
741
806
  function identityOf(claims) {
742
807
  const name = claims.name ?? claims.username ?? null;
743
808
  return {
@@ -793,6 +858,8 @@ async function authLogin(options) {
793
858
  ...identity,
794
859
  device: hostname().slice(0, 60),
795
860
  loginValidUntil: new Date(tokens.accessExpiresAt).toISOString(),
861
+ accessToken: accessDuration(tokens.accessExpiresAt),
862
+ session: sessionDuration(),
796
863
  next: "Run `prudai whoami`, then `prudai guide`."
797
864
  };
798
865
  }
@@ -814,8 +881,8 @@ async function authStatus(options, online = false) {
814
881
  status: "authenticated",
815
882
  profile: config.profile,
816
883
  ...identity,
817
- 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) },
818
- 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." },
884
+ 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) },
885
+ 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." },
819
886
  products: accessMap(config),
820
887
  broker: config.exchangeUrl
821
888
  };
@@ -870,7 +937,8 @@ function authToken(options) {
870
937
  kind: "keycloak_login",
871
938
  source: config.refreshSource === "env" ? "environment (PRUDAI_REFRESH_TOKEN)" : "config file",
872
939
  issuer: config.issuer,
873
- ...claims?.exp ? { loginValidUntil: new Date(claims.exp * 1000).toISOString() } : {},
940
+ ...claims?.exp ? { loginValidUntil: new Date(claims.exp * 1000).toISOString(), accessToken: accessDuration(claims.exp * 1000) } : {},
941
+ session: sessionDuration(),
874
942
  productTokens: { lifetime: "5 minutes, one product each, kept in memory only", products: TOKEN_PRODUCTS },
875
943
  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.'
876
944
  };
@@ -894,7 +962,7 @@ async function authSet(options) {
894
962
  throw new CliError("Expected one Keycloak refresh token on stdin (from `prudai auth export --reveal`).", 2, "invalid_refresh_token");
895
963
  const tokens = await refreshLogin(config.issuer, refresh, { fetch: options.fetch, env: env(options), now: clock(options) });
896
964
  const identity = storeLogin(options, tokens, before);
897
- return { status: "stored", profile: config.profile, ...identity, next: "Run `prudai whoami` to check the login." };
965
+ return { status: "stored", profile: config.profile, ...identity, accessToken: accessDuration(tokens.accessExpiresAt), session: sessionDuration(), next: "Run `prudai whoami` to check the login." };
898
966
  }
899
967
  function authExport(options) {
900
968
  const refresh = options.session.refreshTokenValue;
@@ -905,6 +973,173 @@ function authExport(options) {
905
973
  // src/openapi.ts
906
974
  import { readFile, stat } from "node:fs/promises";
907
975
  import { parse as parseYaml } from "yaml";
976
+
977
+ // src/args.ts
978
+ var BOOLEAN_FLAGS = new Set([
979
+ "json",
980
+ "help",
981
+ "yes",
982
+ "dry-run",
983
+ "no-dry-run",
984
+ "no-browser",
985
+ "stdin",
986
+ "online",
987
+ "refresh",
988
+ "offline",
989
+ "reveal",
990
+ "force",
991
+ "execute",
992
+ "print",
993
+ "wait",
994
+ "no-wait",
995
+ "check",
996
+ "all",
997
+ "include-archived",
998
+ "trash"
999
+ ]);
1000
+ var GLOBAL_FLAGS = new Set([
1001
+ "json",
1002
+ "help",
1003
+ "yes",
1004
+ "dry-run",
1005
+ "no-dry-run",
1006
+ "refresh",
1007
+ "offline",
1008
+ "wait",
1009
+ "timeout",
1010
+ "profile",
1011
+ "spec",
1012
+ "registry",
1013
+ "api-url",
1014
+ "data",
1015
+ "idempotency-key",
1016
+ "if-match",
1017
+ "org"
1018
+ ]);
1019
+ function parseArgs(args) {
1020
+ const words = [];
1021
+ const flags = {};
1022
+ for (let index = 0;index < args.length; index++) {
1023
+ const arg = args[index];
1024
+ if (arg === "-h") {
1025
+ flags.help = true;
1026
+ continue;
1027
+ }
1028
+ if (arg === "-v") {
1029
+ flags.version = true;
1030
+ continue;
1031
+ }
1032
+ if (arg === "--version" && words.length === 0) {
1033
+ flags.version = true;
1034
+ continue;
1035
+ }
1036
+ if (arg === "-y") {
1037
+ flags.yes = true;
1038
+ continue;
1039
+ }
1040
+ if (!arg.startsWith("--")) {
1041
+ words.push(arg);
1042
+ continue;
1043
+ }
1044
+ const equals = arg.indexOf("=");
1045
+ const name = arg.slice(2, equals === -1 ? undefined : equals);
1046
+ if (/(token|secret|password|credential|authorization|api[-_]?key)/i.test(name)) {
1047
+ throw new CliError("Credentials must come from the environment or the protected config file; credential flags are forbidden.");
1048
+ }
1049
+ if (!name || Object.hasOwn(flags, name))
1050
+ throw new CliError("Empty or duplicate flag.");
1051
+ if (BOOLEAN_FLAGS.has(name)) {
1052
+ if (equals !== -1)
1053
+ throw new CliError(`--${name} does not accept a value.`);
1054
+ flags[name] = true;
1055
+ } else {
1056
+ const value = equals !== -1 ? arg.slice(equals + 1) : args[++index];
1057
+ if (value === undefined || value.startsWith("--"))
1058
+ throw new CliError(`--${name} requires a value.`);
1059
+ flags[name] = value;
1060
+ }
1061
+ }
1062
+ if (flags["dry-run"] && flags["no-dry-run"])
1063
+ throw new CliError("Conflicting dry-run flags.");
1064
+ if (flags.wait && flags["no-wait"])
1065
+ throw new CliError("Conflicting wait flags.");
1066
+ return { words, flags };
1067
+ }
1068
+ function str(flags, key) {
1069
+ return typeof flags[key] === "string" ? flags[key] : undefined;
1070
+ }
1071
+ function validateFlags(flags, allowed) {
1072
+ const set = new Set(allowed);
1073
+ for (const name of Object.keys(flags))
1074
+ if (!set.has(name))
1075
+ throw new CliError(`Unknown flag --${name}.`);
1076
+ }
1077
+ function safeApiOrigin(raw) {
1078
+ const url = secureUrl(raw);
1079
+ if (url.pathname !== "/" || url.search)
1080
+ throw new CliError("API URL must be an origin without a path or query.");
1081
+ return url.origin;
1082
+ }
1083
+ function intFlag(flags, key, fallback, min, max) {
1084
+ const raw = str(flags, key);
1085
+ if (raw === undefined)
1086
+ return fallback;
1087
+ const value = Number(raw);
1088
+ if (!Number.isInteger(value) || value < min || value > max)
1089
+ throw new CliError(`--${key} must be a whole number from ${min} to ${max}.`);
1090
+ return value;
1091
+ }
1092
+
1093
+ // src/organization.ts
1094
+ function organizationDeclaration(spec) {
1095
+ const raw = isRecord(spec) ? spec["x-prudai-organization"] : undefined;
1096
+ if (raw === undefined)
1097
+ return;
1098
+ 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") {
1099
+ 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");
1100
+ }
1101
+ return { header: raw.header, ...typeof raw.description === "string" ? { description: raw.description } : {} };
1102
+ }
1103
+ function organizationChoice(product, ctx, useFlag = true) {
1104
+ const flag = useFlag ? str(ctx.flags, "org") : undefined;
1105
+ const environment = ctx.env[`PRUDAI_${product.toUpperCase().replaceAll("-", "_")}_ORG`];
1106
+ const profile = ctx.config.orgs?.[product];
1107
+ const login = (ctx.session ? loginClaims(ctx.session)?.organizationId : undefined) ?? (ctx.config.refreshSource !== "env" ? ctx.config.organization?.id ?? undefined : undefined);
1108
+ const id = flag ?? environment ?? profile ?? login;
1109
+ if (id === undefined)
1110
+ return;
1111
+ if (!id.trim() || /[^\x21-\x7e]/.test(id))
1112
+ throw new CliError("Organization id must be a non-empty value without spaces or control characters.", 2, "invalid_parameter");
1113
+ return { id, product, source: flag !== undefined ? "flag" : environment !== undefined ? "environment" : profile !== undefined ? "profile" : "login" };
1114
+ }
1115
+ function organizationHeaders(product, declaration, ctx) {
1116
+ const choice = organizationChoice(product, ctx);
1117
+ if (!declaration && choice && choice.source !== "login") {
1118
+ 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");
1119
+ }
1120
+ if (choice)
1121
+ ctx.selection.organization = choice;
1122
+ return declaration && choice && choice.source !== "login" ? { [declaration.header]: choice.id } : {};
1123
+ }
1124
+ function assertOrganizationMatches(body, selected, mayHaveWritten = false, contextOperation = false) {
1125
+ if (!selected || !isRecord(body))
1126
+ return;
1127
+ const contextOrg = isRecord(body.context) && isRecord(body.context.organization) ? body.context.organization.id : undefined;
1128
+ const dataOrg = contextOperation && isRecord(body.data) && isRecord(body.data.organization) ? body.data.organization.id : undefined;
1129
+ if (selected.source === "login") {
1130
+ const actual = typeof contextOrg === "string" ? contextOrg : dataOrg;
1131
+ if (typeof actual === "string")
1132
+ selected.id = actual;
1133
+ return;
1134
+ }
1135
+ for (const received of [contextOrg, dataOrg]) {
1136
+ if (typeof received !== "string" || received === selected.id)
1137
+ continue;
1138
+ 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");
1139
+ }
1140
+ }
1141
+
1142
+ // src/openapi.ts
908
1143
  function object2(value, label) {
909
1144
  if (!value || typeof value !== "object" || Array.isArray(value)) {
910
1145
  throw new CliError(`Invalid OpenAPI ${label}`, 2, "invalid_spec");
@@ -977,6 +1212,7 @@ function generateCommands(product, spec, options = {}) {
977
1212
  if (!/^[a-z][a-z0-9-]*$/.test(product))
978
1213
  throw new CliError("Invalid product name", 2, "invalid_spec");
979
1214
  const doc = object2(spec, "document");
1215
+ const organization = organizationDeclaration(doc);
980
1216
  if (typeof doc.openapi !== "string" || !/^3\.1\./.test(doc.openapi)) {
981
1217
  throw new CliError("Expected an OpenAPI 3.1 specification", 2, "invalid_spec");
982
1218
  }
@@ -989,6 +1225,7 @@ function generateCommands(product, spec, options = {}) {
989
1225
  items.set(path, object2(resolve(doc, item), `path ${specPath}`));
990
1226
  }
991
1227
  const hasItemChild = (path) => [...items.keys()].some((other) => other.startsWith(`${path}/{`));
1228
+ const itemHasPatch = (path) => [...items].some(([other, item]) => other.startsWith(`${path}/{`) && !other.slice(path.length + 1).includes("/") && ("patch" in item));
992
1229
  const drafts = [];
993
1230
  for (const [path, pathItem] of items) {
994
1231
  const segments = path.slice(4).split("/");
@@ -1058,7 +1295,7 @@ function generateCommands(product, spec, options = {}) {
1058
1295
  } else if (method === "delete") {
1059
1296
  kind = "delete";
1060
1297
  preferred = fallback = [all, "delete"];
1061
- } else if (method === "put" && "patch" in pathItem) {
1298
+ } else if (method === "put" && (("patch" in pathItem) || !endsWithParam && itemHasPatch(path))) {
1062
1299
  kind = "replace";
1063
1300
  preferred = fallback = [all, "replace"];
1064
1301
  } else {
@@ -1087,6 +1324,7 @@ function generateCommands(product, spec, options = {}) {
1087
1324
  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;
1088
1325
  drafts.push({ preferred, fallback, pinned: !!pinned, command: {
1089
1326
  product,
1327
+ ...organization ? { organization } : {},
1090
1328
  kind,
1091
1329
  method: method.toUpperCase(),
1092
1330
  path,
@@ -1110,14 +1348,22 @@ function generateCommands(product, spec, options = {}) {
1110
1348
  const count = new Map;
1111
1349
  for (const draft of drafts)
1112
1350
  count.set(draft.preferred.join(" "), (count.get(draft.preferred.join(" ")) ?? 0) + 1);
1113
- const commands = [];
1114
- const names2 = new Set;
1115
- for (const draft of drafts) {
1351
+ const named = drafts.map((draft) => {
1116
1352
  const words = !draft.pinned && count.get(draft.preferred.join(" ")) > 1 ? draft.fallback : draft.preferred;
1117
- const name = words.join(" ");
1118
- if (names2.has(name))
1119
- throw new CliError(`Ambiguous generated command: ${product} ${name}. Pin names with x-prudai-cli.`, 2, "invalid_spec");
1120
- names2.add(name);
1353
+ return { draft, words, name: words.join(" ") };
1354
+ });
1355
+ const byName = new Map;
1356
+ for (const entry of named)
1357
+ byName.set(entry.name, [...byName.get(entry.name) ?? [], entry]);
1358
+ const commands = [];
1359
+ for (const [name, entries] of byName) {
1360
+ if (entries.length > 1) {
1361
+ if (!options.onAmbiguous)
1362
+ throw new CliError(`Ambiguous generated command: ${product} ${name}. Pin names with x-prudai-cli.`, 2, "invalid_spec");
1363
+ options.onAmbiguous(name, entries.map(({ draft: draft2 }) => `${draft2.command.method} ${draft2.command.path}`));
1364
+ continue;
1365
+ }
1366
+ const { draft, words } = entries[0];
1121
1367
  commands.push({ ...draft.command, name, words, resource: words.length === 1 ? words[0] : words.slice(0, -1).join(" "), action: words.length === 1 ? "" : words.at(-1) });
1122
1368
  }
1123
1369
  return commands;
@@ -1298,9 +1544,10 @@ function buildOperationRequest(command, args = {}) {
1298
1544
  const suppliedHeaders = new Map;
1299
1545
  for (const [name, value] of Object.entries(args.headers ?? {})) {
1300
1546
  const normalized = name.toLowerCase();
1301
- if (!isSafeHeaderName(name))
1547
+ const organizationHeader = command.organization?.header.toLowerCase() === normalized;
1548
+ if (!organizationHeader && !isSafeHeaderName(name))
1302
1549
  throw new CliError(`Header cannot be supplied as input: ${name}`, 2, "invalid_parameter");
1303
- if (!declaredHeaders.has(normalized) && normalized !== "if-match" && normalized !== "idempotency-key")
1550
+ if (!organizationHeader && !declaredHeaders.has(normalized) && normalized !== "if-match" && normalized !== "idempotency-key")
1304
1551
  throw new CliError(`Undeclared header parameter: ${name}`, 2, "invalid_parameter");
1305
1552
  if (typeof value !== "string" || /[^\t\x20-\x7e\x80-\xff]/.test(value))
1306
1553
  throw new CliError(`Invalid header parameter: ${name}`, 2, "invalid_parameter");
@@ -1347,113 +1594,6 @@ function buildOperationRequest(command, args = {}) {
1347
1594
  // src/cli.ts
1348
1595
  import { resolve as resolvePath } from "node:path";
1349
1596
 
1350
- // src/args.ts
1351
- var BOOLEAN_FLAGS = new Set([
1352
- "json",
1353
- "help",
1354
- "yes",
1355
- "dry-run",
1356
- "no-dry-run",
1357
- "no-browser",
1358
- "stdin",
1359
- "online",
1360
- "refresh",
1361
- "offline",
1362
- "reveal",
1363
- "force",
1364
- "execute",
1365
- "print",
1366
- "wait",
1367
- "no-wait",
1368
- "check",
1369
- "all",
1370
- "include-archived",
1371
- "trash"
1372
- ]);
1373
- var GLOBAL_FLAGS = new Set([
1374
- "json",
1375
- "help",
1376
- "yes",
1377
- "dry-run",
1378
- "no-dry-run",
1379
- "refresh",
1380
- "offline",
1381
- "wait",
1382
- "timeout",
1383
- "profile",
1384
- "spec",
1385
- "registry",
1386
- "api-url",
1387
- "data",
1388
- "idempotency-key",
1389
- "if-match"
1390
- ]);
1391
- function parseArgs(args) {
1392
- const words = [];
1393
- const flags = {};
1394
- for (let index = 0;index < args.length; index++) {
1395
- const arg = args[index];
1396
- if (arg === "-h") {
1397
- flags.help = true;
1398
- continue;
1399
- }
1400
- if (arg === "-y") {
1401
- flags.yes = true;
1402
- continue;
1403
- }
1404
- if (!arg.startsWith("--")) {
1405
- words.push(arg);
1406
- continue;
1407
- }
1408
- const equals = arg.indexOf("=");
1409
- const name = arg.slice(2, equals === -1 ? undefined : equals);
1410
- if (/(token|secret|password|credential|authorization|api[-_]?key)/i.test(name)) {
1411
- throw new CliError("Credentials must come from the environment or the protected config file; credential flags are forbidden.");
1412
- }
1413
- if (!name || Object.hasOwn(flags, name))
1414
- throw new CliError("Empty or duplicate flag.");
1415
- if (BOOLEAN_FLAGS.has(name)) {
1416
- if (equals !== -1)
1417
- throw new CliError(`--${name} does not accept a value.`);
1418
- flags[name] = true;
1419
- } else {
1420
- const value = equals !== -1 ? arg.slice(equals + 1) : args[++index];
1421
- if (value === undefined || value.startsWith("--"))
1422
- throw new CliError(`--${name} requires a value.`);
1423
- flags[name] = value;
1424
- }
1425
- }
1426
- if (flags["dry-run"] && flags["no-dry-run"])
1427
- throw new CliError("Conflicting dry-run flags.");
1428
- if (flags.wait && flags["no-wait"])
1429
- throw new CliError("Conflicting wait flags.");
1430
- return { words, flags };
1431
- }
1432
- function str(flags, key) {
1433
- return typeof flags[key] === "string" ? flags[key] : undefined;
1434
- }
1435
- function validateFlags(flags, allowed) {
1436
- const set = new Set(allowed);
1437
- for (const name of Object.keys(flags))
1438
- if (!set.has(name))
1439
- throw new CliError(`Unknown flag --${name}.`);
1440
- }
1441
- function safeApiOrigin(raw) {
1442
- const url = secureUrl(raw);
1443
- if (url.pathname !== "/" || url.search)
1444
- throw new CliError("API URL must be an origin without a path or query.");
1445
- return url.origin;
1446
- }
1447
- function intFlag(flags, key, fallback, min, max) {
1448
- const raw = str(flags, key);
1449
- if (raw === undefined)
1450
- return fallback;
1451
- const value = Number(raw);
1452
- if (!Number.isInteger(value) || value < min || value > max)
1453
- throw new CliError(`--${key} must be a whole number from ${min} to ${max}.`);
1454
- return value;
1455
- }
1456
-
1457
1597
  // src/catalog.ts
1458
1598
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
1459
1599
  import { dirname as dirname2, join as join2 } from "node:path";
@@ -1669,7 +1809,11 @@ async function loadProductCatalog(word, ctx) {
1669
1809
  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.` };
1670
1810
  }
1671
1811
  try {
1672
- const commands = generateCommands(product, spec, { lenientApproval: source?.kind !== "explicit" && source?.kind !== "plugin" });
1812
+ const lenient = source?.kind !== "explicit" && source?.kind !== "plugin";
1813
+ const commands = generateCommands(product, spec, {
1814
+ lenientApproval: lenient,
1815
+ ...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.`) } : {}
1816
+ });
1673
1817
  const defaulted = commands.filter((command) => command.approvalSource === "default").length;
1674
1818
  if (defaulted)
1675
1819
  base.warnings.push(`${defaulted} write operation(s) declare no x-prudai-approval; the CLI assumes the default level (confirm, delete: review).`);
@@ -1689,9 +1833,18 @@ async function loadCatalog(ctx, only) {
1689
1833
  function commandLine(command) {
1690
1834
  return [command.commandLine ?? `prudai ${command.product} ${command.name}`, ...command.positionals.map((name) => `<${name}>`)].join(" ");
1691
1835
  }
1692
- var tokens = (text) => text.toLowerCase().split(/[^a-z0-9à-ÿ]+/i).filter((token) => token.length > 1 || /\d/.test(token));
1836
+ var tokens = (text) => text.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9à-ÿ]+/i).filter(Boolean);
1837
+ var SEARCH_SYNONYMS = [
1838
+ ["setup", "onboarding", "inrichten", "inrichting", "start", "startpad", "context", "initialization"],
1839
+ ["tenant", "omgeving", "organisatie", "organization", "organisation", "org", "context"],
1840
+ ["bibliotheek", "bibliotheken", "library", "libraries", "normenkader", "normenkaders", "framework", "frameworks"],
1841
+ ["eis", "eisen", "requirement", "requirements"],
1842
+ ["dekken", "gedekt", "dekking", "coverage", "cover"]
1843
+ ];
1844
+ var wordMatches = (word, term) => word === term || term.length > 2 && (word === `${term}s` || term === `${word}s`);
1693
1845
  function searchOperations(catalogs, query, filters = {}) {
1694
1846
  const terms = tokens(query);
1847
+ const concepts = terms.map((term) => ({ term, alternatives: new Set([term, ...SEARCH_SYNONYMS.filter((group) => group.includes(term)).flat()]) }));
1695
1848
  const hits = [];
1696
1849
  for (const catalog of catalogs) {
1697
1850
  if (filters.product && catalog.product !== (findProduct(filters.product)?.product ?? filters.product))
@@ -1702,29 +1855,38 @@ function searchOperations(catalogs, query, filters = {}) {
1702
1855
  if (filters.method && command.method !== filters.method.toUpperCase())
1703
1856
  continue;
1704
1857
  const fields = [
1705
- [`${command.commandLine ?? `${command.product} ${command.name}`}`, 5],
1706
- [command.path, 3],
1707
- [command.summary, 3],
1708
- [command.operationId, 2],
1709
- [(command.tags ?? []).join(" "), 2],
1710
- [(command.scopes ?? []).join(" "), 2],
1711
- [(command.description ?? "").replace(/idempotency-key/gi, ""), 1]
1858
+ [tokens(command.commandLine ?? `${command.product} ${command.name}`), 8],
1859
+ [tokens(command.summary), 7],
1860
+ [tokens(command.path), 5],
1861
+ [tokens(command.operationId), 4],
1862
+ [tokens((command.tags ?? []).join(" ")), 3],
1863
+ [tokens((command.scopes ?? []).join(" ")), 2],
1864
+ [tokens((command.description ?? "").replace(/idempotency-key/gi, "")), 1]
1712
1865
  ];
1713
1866
  let score = 0;
1714
1867
  let matched = 0;
1715
- for (const term of terms) {
1868
+ let directPrimary = 0;
1869
+ for (const { term, alternatives } of concepts) {
1716
1870
  let best = 0;
1717
- for (const [text, weight] of fields)
1718
- if (text.toLowerCase().includes(term))
1871
+ for (const [words, weight] of fields) {
1872
+ const direct = words.some((word) => wordMatches(word, term));
1873
+ if (direct && weight >= 7)
1874
+ directPrimary++;
1875
+ if (direct)
1876
+ best = Math.max(best, weight * 2);
1877
+ else if (words.some((word) => [...alternatives].some((alias) => wordMatches(word, alias))))
1719
1878
  best = Math.max(best, weight);
1879
+ }
1720
1880
  if (best) {
1721
1881
  matched++;
1722
1882
  score += best;
1723
1883
  }
1724
1884
  }
1725
- if (terms.length && !matched)
1885
+ if (terms.length && matched !== terms.length)
1726
1886
  continue;
1727
- score += matched * 10;
1887
+ score += directPrimary * 100;
1888
+ if (concepts.length === 1 && concepts[0].alternatives.has(command.name.toLowerCase()))
1889
+ score += 30;
1728
1890
  hits.push({
1729
1891
  command: commandLine(command),
1730
1892
  product: command.product,
@@ -1868,7 +2030,15 @@ async function requireToken(ctx, product) {
1868
2030
  }
1869
2031
  async function call(ctx, t, method, suffix, body) {
1870
2032
  requireTrustedOrigin(t.origin, ctx.env);
1871
- return requestJson(ctx.fetch, `${t.origin}${t.approvalsPath}${suffix}`, { method, token: await requireToken(ctx, t.product), env: ctx.env, ...body !== undefined ? { body } : {} });
2033
+ const token = await requireToken(ctx, t.product);
2034
+ const headers = organizationHeaders(t.product, t.organization, ctx);
2035
+ const response = await requestJson(ctx.fetch, `${t.origin}${t.approvalsPath}${suffix}`, { method, headers, token, env: ctx.env, ...body !== undefined ? { body } : {} });
2036
+ assertOrganizationMatches(response.body, ctx.selection.organization, method !== "GET");
2037
+ return response;
2038
+ }
2039
+ function followCommand(ctx, t, action, id) {
2040
+ const org = t.organization && ctx.selection.organization && ctx.selection.organization.source !== "login" ? ` --org ${ctx.selection.organization.id}` : "";
2041
+ return `prudai approvals ${action} ${id} --product ${t.product}${org}`;
1872
2042
  }
1873
2043
  function fail(status, body, what) {
1874
2044
  const error = httpError(status, body);
@@ -1880,7 +2050,7 @@ var idOf = (value) => {
1880
2050
  return value;
1881
2051
  };
1882
2052
  async function waitForApproval(ctx, opts) {
1883
- const t = { product: opts.product, origin: opts.origin, approvalsPath: opts.approvalsPath };
2053
+ const t = { product: opts.product, origin: opts.origin, approvalsPath: opts.approvalsPath, organization: opts.organization };
1884
2054
  const deadline = ctx.now() + (opts.timeoutSeconds ?? 600) * 1000;
1885
2055
  let status = "pending";
1886
2056
  let last = {};
@@ -1893,14 +2063,14 @@ async function waitForApproval(ctx, opts) {
1893
2063
  if (status !== "pending")
1894
2064
  break;
1895
2065
  if (ctx.now() >= deadline) {
1896
- 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");
2066
+ 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");
1897
2067
  }
1898
2068
  await ctx.sleep(Math.min(APPROVAL_POLL_MS, Math.max(0, deadline - ctx.now())));
1899
2069
  }
1900
2070
  const summary = { id: opts.id, product: opts.product, status, level: last.level, operation: last.operation, executeUntil: last.executeUntil ?? null };
1901
2071
  if (status === "approved") {
1902
2072
  if (!opts.execute) {
1903
- const next = `prudai approvals execute ${opts.id} --product ${opts.product}`;
2073
+ const next = followCommand(ctx, t, "execute", opts.id);
1904
2074
  ctx.emit(localEnvelope(summary, { provenance: { kind: "product", product: opts.product }, next: [{ action: next, why: "The server runs exactly the approved call." }] }), `Approved. Run: ${next}`);
1905
2075
  return 0;
1906
2076
  }
@@ -1923,14 +2093,15 @@ async function executeApproved(ctx, t, id) {
1923
2093
  if (executed.status !== "executed" || typeof executed.resultStatus !== "number")
1924
2094
  throw new CliError("Unexpected execute response.", 1, "invalid_response");
1925
2095
  const result = executed.result;
2096
+ assertOrganizationMatches(result, ctx.selection.organization, true);
1926
2097
  if (executed.resultStatus >= 400)
1927
2098
  throw new CliError(`The approved call ran and returned HTTP ${executed.resultStatus}.`, executed.resultStatus >= 500 ? 1 : 2, `http_${executed.resultStatus}`);
1928
2099
  const envelope = isEnvelopeLike(result) ? parseEnvelope(result) : localEnvelope(result ?? null, { provenance: { kind: "product", product: t.product }, context: { approvalRequestId: id, resultStatus: executed.resultStatus } });
1929
- ctx.emit(envelope, renderEnvelope(envelope));
2100
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1930
2101
  return 0;
1931
2102
  }
1932
2103
  async function approvalsCommand(words, ctx) {
1933
- validateFlags(ctx.flags, ["json", "profile", "product", "api-url", "timeout", "execute", "status", "scope", "limit", "help"]);
2104
+ validateFlags(ctx.flags, ["json", "profile", "product", "api-url", "timeout", "execute", "status", "scope", "limit", "help", "org", "spec", "registry", "refresh", "offline"]);
1934
2105
  const [action, id, ...extra] = words;
1935
2106
  if (extra.length)
1936
2107
  throw new CliError("Too many arguments.");
@@ -1938,6 +2109,10 @@ async function approvalsCommand(words, ctx) {
1938
2109
  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");
1939
2110
  }
1940
2111
  const t = target(ctx);
2112
+ const catalog = await loadProductCatalog(t.product, ctx.catalog);
2113
+ throwIfUnusable(catalog);
2114
+ t.organization = organizationDeclaration(catalog.spec);
2115
+ organizationHeaders(t.product, t.organization, ctx);
1941
2116
  if (action === "list") {
1942
2117
  const status = str(ctx.flags, "status") ?? "pending";
1943
2118
  if (!["pending", "approved", "all"].includes(status))
@@ -1953,7 +2128,7 @@ async function approvalsCommand(words, ctx) {
1953
2128
  ctx.emit(localEnvelope(items, {
1954
2129
  provenance: { kind: "product", product: t.product },
1955
2130
  completeness: { returned: items.length, truncated: items.length >= limit },
1956
- next: [{ action: `prudai approvals wait <id> --product ${t.product}`, why: "Wait for a decision." }]
2131
+ next: [{ action: followCommand(ctx, t, "wait", "<id>"), why: "Wait for a decision." }]
1957
2132
  }));
1958
2133
  return 0;
1959
2134
  }
@@ -1961,7 +2136,8 @@ async function approvalsCommand(words, ctx) {
1961
2136
  const response = await call(ctx, t, "GET", `/${encodeURIComponent(idOf(id))}${action === "status" ? "/status" : ""}`);
1962
2137
  if (response.status !== 200)
1963
2138
  fail(response.status, response.body, "Approval lookup");
1964
- ctx.emit(localEnvelope(response.body, { provenance: { kind: "product", product: t.product } }));
2139
+ const envelope = localEnvelope(response.body, { provenance: { kind: "product", product: t.product } });
2140
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1965
2141
  return 0;
1966
2142
  }
1967
2143
  if (action === "wait") {
@@ -1973,7 +2149,8 @@ async function approvalsCommand(words, ctx) {
1973
2149
  const response = await call(ctx, t, "POST", `/${encodeURIComponent(idOf(id))}/cancel`);
1974
2150
  if (response.status !== 200)
1975
2151
  fail(response.status, response.body, "Cancel approval");
1976
- ctx.emit(localEnvelope(response.body, { provenance: { kind: "product", product: t.product } }));
2152
+ const envelope = localEnvelope(response.body, { provenance: { kind: "product", product: t.product } });
2153
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1977
2154
  return 0;
1978
2155
  }
1979
2156
  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)");
@@ -2263,6 +2440,8 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2263
2440
  allowed.add(parameter.name);
2264
2441
  }
2265
2442
  validateFlags(flags, allowed);
2443
+ if (!extras.organizationInPath)
2444
+ organizationHeaders(operation.product, operation.organization, ctx);
2266
2445
  if (operation.approval === "forbidden_for_agents")
2267
2446
  throw new CliError("This operation is forbidden for agents; a human does it in the product app.", 2, "forbidden_for_agents");
2268
2447
  if (operation.multipart && !extras.upload) {
@@ -2275,6 +2454,7 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2275
2454
  const token = await credentialFor(operation.product, ctx);
2276
2455
  if (!token)
2277
2456
  throw missingCredential(operation.product);
2457
+ const selectedHeaders = extras.organizationInPath ? {} : organizationHeaders(operation.product, operation.organization, ctx);
2278
2458
  const isGet = operation.method.toUpperCase() === "GET";
2279
2459
  const writing = !isGet && !operation.readsViaPost;
2280
2460
  const approvalsPath = extras.approvalsPath ?? findProduct(operation.product)?.approvalsPath;
@@ -2330,6 +2510,8 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2330
2510
  const etag = str(flags, "if-match");
2331
2511
  if (etag)
2332
2512
  headers["if-match"] = etag;
2513
+ for (const [name, value] of Object.entries(selectedHeaders))
2514
+ headers[name.toLowerCase()] = value;
2333
2515
  const dryRun = writing && !flags["no-dry-run"];
2334
2516
  const request = buildOperationRequest(extras.upload && dryRun ? { ...operation, dryRun: true } : operation, { params, query, body, headers, dryRun: !flags["no-dry-run"], idempotencyKey: str(flags, "idempotency-key") });
2335
2517
  if (extras.upload && dryRun) {
@@ -2359,6 +2541,15 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2359
2541
  if (extras.irreversible && !dryRun)
2360
2542
  stderr(`Warning: ${IRREVERSIBLE}`);
2361
2543
  const target2 = `${apiUrl}${request.path}`;
2544
+ if (writing && !dryRun && operation.dryRun && (operation.organization || extras.organizationInPath) && ctx.selection.organization && ctx.selection.organization.source !== "login" && !extras.upload) {
2545
+ const previewHeaders = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "idempotency-key"));
2546
+ const preview = buildOperationRequest(operation, { params, query, body, headers: previewHeaders, dryRun: true, idempotencyKey: crypto.randomUUID() });
2547
+ const checked = await requestJson(ctx.fetch, `${apiUrl}${preview.path}`, { ...preview, token, env: env2 });
2548
+ assertOrganizationMatches(checked.body, ctx.selection.organization, false, operation.path.replace(/\/$/, "") === "/v1/context");
2549
+ if (checked.status >= 400)
2550
+ throw httpError(checked.status, checked.body, operation.product);
2551
+ requireSuccess(checked.status);
2552
+ }
2362
2553
  let result;
2363
2554
  if (extras.upload) {
2364
2555
  const sent = await requestMultipart(ctx.fetch, target2, { method: request.method, headers: request.headers, token, env: env2, file: extras.upload.file });
@@ -2372,6 +2563,7 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2372
2563
  result = answer;
2373
2564
  } else
2374
2565
  result = await requestJson(ctx.fetch, target2, { ...request, token, env: env2 });
2566
+ assertOrganizationMatches(result.body, ctx.selection.organization, writing && !dryRun, operation.path.replace(/\/$/, "") === "/v1/context");
2375
2567
  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;
2376
2568
  if (accepted)
2377
2569
  stderr("Note: accepted. The document is processed again in the background (status pending); read its status with the matching get command.");
@@ -2381,10 +2573,11 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2381
2573
  stderr(`Warning: ${pending.warning}`);
2382
2574
  const request202 = pending.approvalRequest;
2383
2575
  const id = typeof request202.approvalRequestId === "string" ? request202.approvalRequestId : typeof request202.id === "string" ? request202.id : undefined;
2384
- const follow = id && approvalsPath ? `prudai approvals wait ${id} --product ${operation.product} --execute` : undefined;
2576
+ const orgFlag = ctx.selection.organization && ctx.selection.organization.source !== "login" && operation.organization ? ` --org ${ctx.selection.organization.id}` : "";
2577
+ const follow = id && approvalsPath ? `prudai approvals wait ${id} --product ${operation.product}${orgFlag} --execute` : undefined;
2385
2578
  if (flags.wait && id && approvalsPath) {
2386
2579
  stderr(`APPROVAL REQUIRED. ${pending.next} Waiting (prudai approvals wait ${id}).`);
2387
- return waitForApproval(ctx, { product: operation.product, origin: apiUrl, approvalsPath, id, execute: true, timeoutSeconds: intFlag(flags, "timeout", 600, 5, 3600) });
2580
+ return waitForApproval(ctx, { product: operation.product, origin: apiUrl, approvalsPath, organization: operation.organization, id, execute: true, timeoutSeconds: intFlag(flags, "timeout", 600, 5, 3600) });
2388
2581
  }
2389
2582
  const out = { ...pending, ...follow ? { follow, next: `${pending.next} Then run: ${follow}` } : {} };
2390
2583
  emit(out, `APPROVAL REQUIRED. ${out.next}
@@ -2414,7 +2607,7 @@ ${JSON.stringify(pending.approvalRequest, null, 2)}`);
2414
2607
  `DRY RUN — nothing was executed. Would send: ${would.method} ${would.path}${request.body !== undefined ? ` ${JSON.stringify(request.body)}` : ""}`,
2415
2608
  `approval: ${operation.approval}`,
2416
2609
  ...extras.irreversible ? [`IRREVERSIBLE: ${IRREVERSIBLE}`] : [],
2417
- ...envelope ? [renderEnvelope(envelope)] : [],
2610
+ ...envelope ? [renderEnvelope(envelope, { list: operation.kind === "list" })] : [],
2418
2611
  "Repeat with --no-dry-run --yes to execute this request.",
2419
2612
  ...extras.after ? [`Afterwards: ${extras.after.action} (${extras.after.why})`] : []
2420
2613
  ].join(`
@@ -2426,7 +2619,7 @@ ${JSON.stringify(pending.approvalRequest, null, 2)}`);
2426
2619
  return 0;
2427
2620
  }
2428
2621
  const shown = extras.after ? { ...envelope, next: [...envelope.next, extras.after] } : envelope;
2429
- emit(shown, renderEnvelope(shown));
2622
+ emit(shown, renderEnvelope(shown, { list: operation.kind === "list" }));
2430
2623
  return 0;
2431
2624
  }
2432
2625
  async function emitDownload(answer, options, operation, ctx) {
@@ -2562,7 +2755,9 @@ async function apiCommand(words, ctx) {
2562
2755
  delete flags.product;
2563
2756
  return executeOperation(match.command, positionals, origin, { ...ctx, flags });
2564
2757
  }
2565
- validateFlags(ctx.flags, ["json", "help", "yes", "no-dry-run", "dry-run", "profile", "product", "api-url", "data", "idempotency-key", "refresh", "offline"]);
2758
+ validateFlags(ctx.flags, ["json", "help", "yes", "no-dry-run", "dry-run", "profile", "product", "api-url", "data", "idempotency-key", "refresh", "offline", "org"]);
2759
+ const organization = organizationDeclaration(catalog?.spec);
2760
+ organizationHeaders(product, organization, ctx);
2566
2761
  if (!origin)
2567
2762
  throw new CliError(`Configure the ${product} API origin (--api-url).`);
2568
2763
  if (catalog?.notAvailable)
@@ -2572,6 +2767,7 @@ async function apiCommand(words, ctx) {
2572
2767
  const token = await credentialFor(product, ctx);
2573
2768
  if (!token)
2574
2769
  throw missingCredential(product);
2770
+ const selectedHeaders = organizationHeaders(product, organization, ctx);
2575
2771
  const writing = method !== "GET";
2576
2772
  const body = await readData(ctx.flags);
2577
2773
  if (!writing && body !== undefined)
@@ -2579,7 +2775,7 @@ async function apiCommand(words, ctx) {
2579
2775
  if (writing && !(ctx.flags["no-dry-run"] && ctx.flags.yes)) {
2580
2776
  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");
2581
2777
  }
2582
- const headers = {};
2778
+ const headers = { ...selectedHeaders };
2583
2779
  if (writing) {
2584
2780
  const key = str(ctx.flags, "idempotency-key") ?? crypto.randomUUID();
2585
2781
  if (!key.trim() || /[^\t\x20-\x7e]/.test(key))
@@ -2589,6 +2785,7 @@ async function apiCommand(words, ctx) {
2589
2785
  }
2590
2786
  ctx.stderr(`Note: ${method} ${path} is not in the ${product} catalogue; sent as-is to ${apiUrl}.`);
2591
2787
  const result = await requestJson(ctx.fetch, `${apiUrl}${parsed.pathname}${parsed.search}`, { method, token, env: ctx.env, headers, ...body !== undefined ? { body } : {} });
2788
+ assertOrganizationMatches(result.body, ctx.selection.organization, writing, parsed.pathname.replace(/\/$/, "") === "/v1/context");
2592
2789
  if (result.status === 202) {
2593
2790
  const pending = approvalResult(result.body, ctx.env);
2594
2791
  if (pending.warning)
@@ -2599,7 +2796,7 @@ async function apiCommand(words, ctx) {
2599
2796
  if (result.status >= 400)
2600
2797
  throw httpError(result.status, result.body, product);
2601
2798
  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."] });
2602
- ctx.emit(envelope, renderEnvelope(envelope));
2799
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
2603
2800
  return 0;
2604
2801
  }
2605
2802
 
@@ -3195,9 +3392,14 @@ async function platformCommand(words, ctx) {
3195
3392
  if (op.costsMoney)
3196
3393
  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.");
3197
3394
  if (op.orgScoped) {
3198
- const org = str(ctx.flags, "org") ?? ctx.file.profiles[ctx.config.profile]?.organization?.id ?? undefined;
3395
+ const initial = organizationChoice("platform", ctx);
3396
+ if ((!initial || initial.source === "login") && ctx.config.refreshToken)
3397
+ await ctx.session.loginToken();
3398
+ const choice = organizationChoice("platform", ctx);
3399
+ const org = choice?.id;
3199
3400
  if (!org)
3200
3401
  throw new CliError("Name the organisation: --org <organization id> (prudai whoami shows yours).");
3402
+ ctx.selection.organization = choice;
3201
3403
  positionals = [org, ...positionals];
3202
3404
  }
3203
3405
  const origin = resolveOrigin(PLATFORM_PRODUCT, ctx, platform.spec);
@@ -3215,7 +3417,8 @@ async function platformCommand(words, ctx) {
3215
3417
  if (op.custom === "memos-list")
3216
3418
  return listMemos(access, command, project, ctx);
3217
3419
  const flags = { ...ctx.flags };
3218
- delete flags.org;
3420
+ if (op.orgScoped)
3421
+ delete flags.org;
3219
3422
  for (const entry of op.body ?? [])
3220
3423
  for (const name of [entry.flag, ...entry.aliases ?? []])
3221
3424
  delete flags[name];
@@ -3227,6 +3430,7 @@ async function platformCommand(words, ctx) {
3227
3430
  }
3228
3431
  const target2 = project ? { project: { id: project.id, name: project.name } } : upload && positionals[0] ? { knowledge_base: positionals[0] } : undefined;
3229
3432
  const extras = {
3433
+ ...op.orgScoped ? { organizationInPath: true } : {},
3230
3434
  ...body ? { body } : {},
3231
3435
  consumed: [...op.query ?? [], ...extraFlags.filter((entry) => entry.query).map((entry) => entry.query)],
3232
3436
  ...upload ? { upload: { file: upload, ...target2 ? { target: target2 } : {} } } : {},
@@ -3340,7 +3544,7 @@ function platformHelp() {
3340
3544
  }
3341
3545
 
3342
3546
  // src/version.ts
3343
- var VERSION = "0.1.0";
3547
+ var VERSION = "0.1.2";
3344
3548
 
3345
3549
  // src/discovery.ts
3346
3550
  var CATALOG_FLAGS = ["json", "help", "profile", "refresh", "offline", "spec", "registry", "api-url"];
@@ -3374,6 +3578,8 @@ var ERROR_CODES = {
3374
3578
  invalid_response: "The server answered with something that is not JSON.",
3375
3579
  invalid_envelope: "The server sent a malformed /v1 envelope.",
3376
3580
  invalid_spec: "A spec could not be read or turned into commands.",
3581
+ organization_not_supported: "The product declares no organisation header; omit --org or use a product that declares x-prudai-organization.",
3582
+ organization_mismatch: "The server reported another organization than selected. Its data is hidden; after a real write, check state before retrying.",
3377
3583
  unknown_profile: "The selected profile does not exist; create it or pick another.",
3378
3584
  "<server code>": "Other HTTP errors carry the product's own code (context.error.code), e.g. not_found, conflict.",
3379
3585
  "http_<status>": "An HTTP error without a recognisable code; the message gives a hint per status.",
@@ -3443,7 +3649,12 @@ plus ops search and describe are enough.
3443
3649
  prudai describe <product> <command…> parameters, body schema + example, responses, curl
3444
3650
  prudai describe irma:<operationId> …or by operationId, or: prudai describe GET /v1/risks
3445
3651
  prudai describe keys create platform commands too: route, scope, approval, status
3446
- prudai <product> help every command of one product
3652
+ prudai <product> help object summary; --all lists every command
3653
+ prudai ops search "setup" --product irma
3654
+ NL/EN synonyms also find onboarding, organisations and frameworks
3655
+ IRMA start: prudai irma context read its ordered next steps and follow the startpad/status
3656
+ operation it names. A human loads a normenkader in the app first;
3657
+ agents build concepts/proposals for a human to adopt.
3447
3658
  prudai help --json machine-readable command list
3448
3659
  Products:
3449
3660
  ${products}
@@ -3460,16 +3671,30 @@ ${products}
3460
3671
  or export PRUDAI_REFRESH_TOKEN (the refresh token of such a login). A person can end any session.
3461
3672
  Check: prudai whoami (= auth status: user, organisation; --online proves the session still lives)
3462
3673
  Profiles: one login per profile; prudai profile list|create|use; --profile <name> per call. A login
3463
- belongs to one organisation: use another profile for another organisation.
3674
+ belongs to one Keycloak organisation; another login uses another profile.
3675
+ Product environment: organisation selection works only for a product whose spec declares
3676
+ x-prudai-organization. IRMA supports it once that release is live; until then an explicit
3677
+ selection returns organization_not_supported. Explicit priority: --org > PRUDAI_<PRODUCT>_ORG >
3678
+ prudai profile set orgs.<product> <id>. Only a flag, environment or profile choice sends
3679
+ the declared header. Without these, the product uses the login organisation without an
3680
+ organisation header; no mismatch check is made against the login organisation. The output
3681
+ uses the server-reported organisation with source login.
3682
+ With an explicit choice, a different organization id in the server response gives
3683
+ organization_mismatch (exit 2), with no response data shown. Real writes preview first where
3684
+ the operation declares dry run; otherwise a mismatch is detected after the write, which may
3685
+ already have happened elsewhere.
3686
+ whoami shows the product organisation map; whoami --product irma --org <id> checks a selection.
3687
+ Platform commands keep --org as their organisation path id: flag > PRUDAI_PLATFORM_ORG >
3688
+ profile orgs.platform > login organisation.
3464
3689
  Token for another tool, without printing it:
3465
3690
  curl -H "Authorization: Bearer $(prudai auth token --reveal --product irma)" … (never run --reveal bare)
3466
3691
  prudai logout ends the session at Keycloak first. Tokens are only sent to https://*.prudai.com and
3467
3692
  localhost; another origin needs PRUDAI_ALLOW_ORIGIN=<exact origin> in the environment.
3468
3693
 
3469
3694
  3. SCOPES <product>:<object>:<verb>, verb = read | write | delete
3470
- read scopes never need a person. write and delete scopes are the HITL class: their
3471
- operations carry an approval level (confirm, review, …; see 6), so a person approves before
3472
- the server executes. A key only needs the scope; the approval happens per call.
3695
+ read scopes never need a person. write and delete operations carry an approval level
3696
+ (confirm, review, …; see 6); this does not mean every write waits for another person.
3697
+ A key needs the scope; the server applies the operation's approval level and product mode per call.
3473
3698
  Wildcard <product>:*:<verb> covers every object of that product and verb, including later
3474
3699
  ones — but never explicit-only objects (licensed text, credit-spending chat/answers, api_keys,
3475
3700
  subscriptions). Invalid: *, *:x:read, p:*:*, p:o:*. prudai keys scopes lists them once the platform serves
@@ -3497,8 +3722,14 @@ ${products}
3497
3722
  --if-match <etag> for optimistic concurrency. Deletes are soft (restore exists).
3498
3723
 
3499
3724
  6. HUMAN APPROVAL (HITL)
3500
- Levels per operation (x-prudai-approval): none, instruct, confirm, review (second person),
3501
- forbidden_for_agents (refused locally; a human does it in the app).
3725
+ Levels per operation (x-prudai-approval), always subject to the product's permissions:
3726
+ none / instruct: no second-person review; writes still need --no-dry-run --yes.
3727
+ confirm: in shadow mode, --no-dry-run --yes executes directly within the agent's allowed
3728
+ concept/proposal boundary. In enforce mode, follow the server's approval response.
3729
+ review: waits for a second person where supported; it can instead be refused with
3730
+ approval_requires_enforce in shadow mode. A product administrator enables enforce;
3731
+ use the product app for the human action meanwhile. Do not bypass a refusal.
3732
+ forbidden_for_agents: never allowed for an agent (refused locally); a human acts in the app.
3502
3733
  HTTP 202 = approval_required, exit 2, NOT success. The answer shows the approval link (only
3503
3734
  for trusted Prudai origins) and: prudai approvals wait <id> --product <p> --execute
3504
3735
  which waits for the human decision and then lets the server run exactly the approved call.
@@ -3615,7 +3846,10 @@ var HELP = {
3615
3846
  "--refresh",
3616
3847
  "--offline",
3617
3848
  "--out <path> [--force]",
3618
- "--project <id|name>"
3849
+ "--project <id|name>",
3850
+ "--org <id>",
3851
+ "--all",
3852
+ "--version / -v"
3619
3853
  ],
3620
3854
  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.",
3621
3855
  exitCodes: EXIT_CODES,
@@ -3770,11 +4004,45 @@ function param(parameter) {
3770
4004
  `)[0].slice(0, 200) } : {}
3771
4005
  };
3772
4006
  }
4007
+ function bodySchemaLines(schema, prefix = "", depth = 0) {
4008
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
4009
+ return [` ${prefix || "body"} | ${String(schema)} | — | — | —`];
4010
+ const node = schema;
4011
+ if (depth > 12)
4012
+ return [` ${prefix || "body"} | nested schema; use --json | — | — | —`];
4013
+ const required = Array.isArray(node.required) ? node.required : [];
4014
+ const lines = [];
4015
+ if (node.properties && typeof node.properties === "object" && !Array.isArray(node.properties)) {
4016
+ for (const [name, value] of Object.entries(node.properties)) {
4017
+ const field = value && typeof value === "object" && !Array.isArray(value) ? value : {};
4018
+ const path = prefix ? `${prefix}.${name}` : name;
4019
+ 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");
4020
+ 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() : "—"}`);
4021
+ if (field.properties || field.allOf || field.anyOf || field.oneOf)
4022
+ lines.push(...bodySchemaLines(field, path, depth + 1));
4023
+ if (field.items)
4024
+ lines.push(...bodySchemaLines(field.items, `${path}[]`, depth + 1));
4025
+ }
4026
+ }
4027
+ for (const key of ["allOf", "oneOf", "anyOf"]) {
4028
+ if (Array.isArray(node[key]))
4029
+ for (const [index, variant] of node[key].entries()) {
4030
+ lines.push(...bodySchemaLines(variant, key === "allOf" ? prefix : `${prefix || "body"}[${key} ${index + 1}]`, depth + 1));
4031
+ }
4032
+ }
4033
+ if (!lines.length) {
4034
+ const type = Array.isArray(node.type) ? node.type.join(" | ") : node.type ?? (node.items ? "array" : "any");
4035
+ 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() : "—"}`);
4036
+ if (node.items)
4037
+ lines.push(...bodySchemaLines(node.items, `${prefix || "body"}[]`, depth + 1));
4038
+ }
4039
+ return lines;
4040
+ }
3773
4041
  function describeCommand(command, catalog) {
3774
4042
  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));
3775
4043
  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) }));
3776
4044
  const writing = command.method !== "GET" && !command.readsViaPost;
3777
- const body = command.inputSchema !== undefined ? { required: command.bodyRequired === true, schema: compactSchema(command.inputSchema), example: exampleFrom(command.inputSchema, "body") } : undefined;
4045
+ const body = command.inputSchema !== undefined ? { required: command.bodyRequired === true, schema: command.inputSchema, example: exampleFrom(command.inputSchema, "body") } : undefined;
3778
4046
  const base = ["prudai", command.product, command.name, ...command.positionals.map((name) => `<${name}>`)].join(" ");
3779
4047
  const dataArg = body ? ` --data '${JSON.stringify(body.example)}'` : "";
3780
4048
  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("] [")}]` : ""}`];
@@ -3849,7 +4117,8 @@ async function describePlatform(op, ctx) {
3849
4117
  `${doc.command}`,
3850
4118
  `${op.method} ${op.path} — ${op.summary}`,
3851
4119
  `scope: ${op.scope} approval: ${op.approval} status: ${op.status}${bound ? "" : " (not available yet)"}${op.costsMoney ? " costs money" : ""}`,
3852
- ...flags.length ? ["flags:", ...flags.map((f) => ` ${f.flag}${"field" in f ? ` → ${f.field}` : ""}`)] : []
4120
+ ...flags.length ? ["flags:", ...flags.map((f) => ` ${f.flag}${"field" in f ? ` → ${f.field}` : ""}`)] : [],
4121
+ ...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)}`] : []
3853
4122
  ].join(`
3854
4123
  `));
3855
4124
  return 0;
@@ -3877,7 +4146,7 @@ async function describeOperationCommand(words, ctx) {
3877
4146
  const doc = describeCommand(found.command, found.catalog);
3878
4147
  ctx.emit(localEnvelope(doc, {
3879
4148
  provenance: { kind: "catalog", product: found.catalog.product, source: found.catalog.source ?? null },
3880
- notIncluded: ["Full JSON Schemas are compacted to 5 levels; the product reference has every field."],
4149
+ notIncluded: ["Parameter descriptions are compacted; --json includes the complete resolved body schema."],
3881
4150
  next: [{ action: doc.examples.cli[0].replace(/\s+#.*$/, ""), why: found.command.method === "GET" ? "Run it." : "Preview it first." }]
3882
4151
  }), [
3883
4152
  `${doc.command}`,
@@ -3890,7 +4159,7 @@ ${doc.description}
3890
4159
  ...doc.idempotency ? [`idempotency: key always sent; replay protection ${doc.idempotency.declared ? "declared" : "not declared"}`] : [],
3891
4160
  ...doc.positionals.length ? ["positionals:", ...doc.positionals.map((p) => ` <${p.name}> (${p.in}${p.required ? ", required" : ""}) ${p.type ?? ""} ${p.description ?? ""}`)] : [],
3892
4161
  ...doc.flags.length ? ["flags:", ...doc.flags.map((f) => ` ${f.flag}${f.required ? " (required)" : ""} ${f.type ?? ""}${f.enum ? ` ${JSON.stringify(f.enum)}` : ""} ${f.description ?? ""}`)] : [],
3893
- ...doc.body ? [`body${doc.body.required ? " (required)" : ""}: ${JSON.stringify(doc.body.schema)}`, `example: ${JSON.stringify(doc.body.example)}`] : [],
4162
+ ...doc.body ? [`body${doc.body.required ? " (required)" : ""}:`, " field | type | presence | enum | description", ...bodySchemaLines(doc.body.schema), `example: ${JSON.stringify(doc.body.example)}`] : [],
3894
4163
  `responses: ${doc.responses.map((r) => `${r.status}${r.description ? ` ${r.description}` : ""}`).join("; ")}`,
3895
4164
  "examples:",
3896
4165
  ...doc.examples.cli.map((line) => ` ${line}`),
@@ -3920,11 +4189,30 @@ description: Use the Prudai CLI (\`prudai\`) for anything with Prudai — LEO, I
3920
4189
  \`prudai\` is the complete interface to Prudai for people and agents. Do not guess routes or
3921
4190
  scopes: discover them.
3922
4191
 
4192
+ Organisation selection works only for a product whose spec declares \`x-prudai-organization\`.
4193
+ IRMA supports it once that release is live; until then an explicit selection returns
4194
+ \`organization_not_supported\`. Explicit priority: \`--org <id>\` > \`PRUDAI_<PRODUCT>_ORG\` >
4195
+ \`profile set orgs.<product> <id>\`. Only a flag, environment or profile choice sends the declared
4196
+ header. Without these, the product uses the login organisation without an organisation header;
4197
+ no mismatch check is made against the login organisation. The output uses the server-reported
4198
+ organisation with source login. The server checks your access.
4199
+ \`whoami --product irma --org <id>\` shows the effective choice; plain \`whoami\` shows configured
4200
+ product choices. Platform commands place the organisation id in the route, with priority flag >
4201
+ \`PRUDAI_PLATFORM_ORG\` > \`profile orgs.platform\` > login. Begin IRMA work with \`prudai irma context\`
4202
+ and follow \`next\`: a missing framework must first be loaded by a person in the app.
4203
+ Use \`--help\` after any command; \`prudai irma help\` summarises objects and \`--all\` lists
4204
+ all operations. Search accepts NL/EN synonyms for setup, onboarding, organisations and frameworks.
4205
+ Without \`--json\`, lists show a table followed by completeness and next steps; \`describe\`
4206
+ shows body fields with type, required, enum and description. \`--json\` keeps one JSON document
4207
+ with the raw schema. \`prudai --version\` (or \`-v\`) prints the CLI version.
4208
+
3923
4209
  1. \`prudai ops search "<what you want>"\` — operations across all products, with the exact
3924
4210
  command, scope, approval level (HITL) and cost.
3925
4211
  2. \`prudai describe <product> <command…>\` — parameters, body schema, an example and curl.
3926
4212
  3. Run it with \`--json\`. Reads run directly; writes preview first (dry run) and need
3927
- \`--no-dry-run --yes\` to execute. HTTP 202 = a human must approve:
4213
+ \`--no-dry-run --yes\` to request execution. \`confirm\` may execute directly in shadow;
4214
+ \`review\` waits for a second person or is refused; \`forbidden_for_agents\` never runs.
4215
+ HTTP 202 = a human must approve:
3928
4216
  \`prudai approvals wait <id> --product <p> --execute\`.
3929
4217
  4. Exit codes: 0 done · 1 network/server (check state before retrying a write) · 2 you must act.
3930
4218
  "not available yet" (error not_available) means the platform has not built it: say so,
@@ -3939,8 +4227,14 @@ service runs them the answer is 403 \`approval_required\` and nothing happened;
3939
4227
 
3940
4228
  Never pass credentials as flags, never print a token (\`auth token --reveal\` only inside
3941
4229
  \`$(…)\`), never approve on a human's behalf, never pay. Credentials: \`prudai login\` (Keycloak device login; people and agents),
3942
- or \`PRUDAI_REFRESH_TOKEN\` on a runner that logged in once.
4230
+ or \`PRUDAI_REFRESH_TOKEN\` on a runner that logged in once. Login output separates the
4231
+ short-lived access token expiry from the offline login session, whose duration is governed by
4232
+ Keycloak policy; \`loginValidUntil\` is only the compatibility alias for access token expiry.
3943
4233
  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.
4234
+ For an explicit flag, environment or profile choice, organization_mismatch (exit 2) hides the response
4235
+ data: the server reported another organization than selected.
4236
+ Real writes preview first where declared; without a declared dry run a mismatch can be detected only
4237
+ after the write, so check the other organization's state before retrying.
3944
4238
 
3945
4239
  | Product | What | Operations | Catalogue |
3946
4240
  | --- | --- | --- | --- |
@@ -4064,11 +4358,11 @@ function matchCommand(commands, rest) {
4064
4358
  }
4065
4359
  return;
4066
4360
  }
4067
- var PROFILE_KEYS = /^(?:(productApiUrls|specs)\.([a-z][a-z0-9-]{0,63})|(registryUrl))$/;
4361
+ var PROFILE_KEYS = /^(?:(productApiUrls|specs|orgs)\.([a-z][a-z0-9-]{0,63})|(registryUrl))$/;
4068
4362
  function setProfileValue(profile, key, value, env2, stderr) {
4069
4363
  const match2 = PROFILE_KEYS.exec(key);
4070
4364
  if (!match2)
4071
- throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, registryUrl.");
4365
+ throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, orgs.<product>, registryUrl.");
4072
4366
  const next = { ...profile };
4073
4367
  if (match2[3]) {
4074
4368
  if (value === undefined) {
@@ -4090,6 +4384,10 @@ function setProfileValue(profile, key, value, env2, stderr) {
4090
4384
  map[product] = safeApiOrigin(value);
4091
4385
  if (!isTrustedOrigin(map[product], env2))
4092
4386
  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.`);
4387
+ } else if (field === "orgs") {
4388
+ if (!value.trim() || /[^\x21-\x7e]/.test(value))
4389
+ throw new CliError("Organization id must be a non-empty value without spaces or control characters.");
4390
+ map[product] = value;
4093
4391
  } else {
4094
4392
  if (!value.trim())
4095
4393
  throw new CliError("A spec source must be a path or URL.");
@@ -4221,7 +4519,7 @@ var BUILTINS = new Set([
4221
4519
  var ALIASES = { login: ["auth", "login"], logout: ["auth", "logout"], whoami: ["auth", "status"] };
4222
4520
  async function authCommand(words, ctx, options) {
4223
4521
  const { flags, env: env2, config, file } = ctx;
4224
- validateFlags(flags, new Set(["json", "profile", "no-browser", "stdin", "reveal", "online", "product", "device-name"]));
4522
+ validateFlags(flags, new Set(["json", "profile", "no-browser", "stdin", "reveal", "online", "product", "device-name", "org", "spec", "registry", "api-url", "refresh", "offline"]));
4225
4523
  const action = words[1];
4226
4524
  if (action === "switch-org")
4227
4525
  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");
@@ -4235,8 +4533,18 @@ async function authCommand(words, ctx, options) {
4235
4533
  throw new CliError("--reveal belongs to prudai auth token and prudai auth export.");
4236
4534
  if (flags.online && action !== "status")
4237
4535
  throw new CliError("--online belongs to prudai auth status.");
4238
- if (flags.product && action !== "token")
4239
- throw new CliError("--product belongs to prudai auth token.");
4536
+ if (flags.product && action !== "token" && action !== "status")
4537
+ throw new CliError("--product belongs to prudai auth token or status.");
4538
+ if (flags.org && (action !== "status" || !flags.product))
4539
+ throw new CliError("Use prudai whoami --product <product> --org <id> to inspect an environment selection.");
4540
+ let statusCatalog;
4541
+ if (action === "status" && flags.product) {
4542
+ const product = findProduct(str(flags, "product"))?.product ?? str(flags, "product");
4543
+ const catalog = await loadProductCatalog(product, ctx.catalog);
4544
+ throwIfUnusable(catalog);
4545
+ statusCatalog = catalog;
4546
+ organizationHeaders(product, organizationDeclaration(catalog.spec), ctx);
4547
+ }
4240
4548
  const save = options.saveConfig ?? ((cfg) => writeConfig(configPath(env2), cfg));
4241
4549
  const authOptions = {
4242
4550
  config,
@@ -4269,9 +4577,19 @@ async function authCommand(words, ctx, options) {
4269
4577
  ctx.emit(localEnvelope(meta, { provenance: { kind: "local" }, notIncluded: ["The secret itself; use --reveal only inside $(…)."] }), JSON.stringify(meta, null, 2));
4270
4578
  return 0;
4271
4579
  }
4272
- const result = action === "login" ? await authLogin(authOptions) : action === "status" ? await authStatus(authOptions, !!flags.online) : action === "logout" ? await authLogout(authOptions) : action === "set" ? await authSet(authOptions) : (() => {
4580
+ let result = action === "login" ? await authLogin(authOptions) : action === "status" ? await authStatus(authOptions, !!flags.online) : action === "logout" ? await authLogout(authOptions) : action === "set" ? await authSet(authOptions) : (() => {
4273
4581
  throw new CliError("Unknown auth command. Use login, status, logout, token, export or set --stdin.");
4274
4582
  })();
4583
+ if (action === "status" && isRecord(result)) {
4584
+ if (statusCatalog)
4585
+ organizationHeaders(statusCatalog.product, organizationDeclaration(statusCatalog.spec), ctx);
4586
+ const products = new Set([...Object.keys(config.orgs ?? {}), ...Object.keys(env2).flatMap((key) => /^PRUDAI_([A-Z0-9_]+)_ORG$/.exec(key)?.[1]?.toLowerCase().replaceAll("_", "-") ?? [])]);
4587
+ result = {
4588
+ ...result,
4589
+ selectedOrganizations: Object.fromEntries([...products].map((product) => [product, organizationChoice(product, ctx, false)])),
4590
+ ...ctx.selection.organization ? { selectedOrganization: ctx.selection.organization } : {}
4591
+ };
4592
+ }
4275
4593
  const message2 = result.message;
4276
4594
  ctx.emit(localEnvelope(result, { provenance: { kind: "auth", origin: config.issuer } }), typeof message2 === "string" ? `${message2}
4277
4595
  ${JSON.stringify(result, null, 2)}` : JSON.stringify(result, null, 2));
@@ -4288,8 +4606,35 @@ async function productCommand(words, ctx) {
4288
4606
  for (const warning of catalog.warnings)
4289
4607
  ctx.stderr(`Warning: ${warning}`);
4290
4608
  const product = catalog.product;
4609
+ organizationHeaders(product, organizationDeclaration(catalog.spec), ctx);
4610
+ if (ctx.flags.help && words.length > 1 && words[1] !== "help") {
4611
+ const matched2 = matchCommand(catalog.commands, words.slice(1));
4612
+ if (matched2) {
4613
+ const flags = Object.fromEntries(Object.entries(ctx.flags).filter(([name]) => ["json", "help", "profile", "spec", "registry", "api-url", "refresh", "offline"].includes(name)));
4614
+ return describeOperationCommand([product, ...matched2.operation.words], { ...ctx, flags });
4615
+ }
4616
+ const scoped = catalog.commands.filter((entry) => entry.resource === words.slice(1).join(" "));
4617
+ if (!scoped.length)
4618
+ throw new CliError(`Unknown ${product} command. Run prudai ${product} help.`);
4619
+ ctx.emit(localEnvelope(scoped), scoped.map((entry) => `prudai ${product} ${entry.name} ${entry.summary}`).join(`
4620
+ `));
4621
+ return 0;
4622
+ }
4291
4623
  if (words[1] === "help" || ctx.flags.help || words.length === 1) {
4292
- validateFlags(ctx.flags, GLOBAL_FLAGS);
4624
+ validateFlags(ctx.flags, [...GLOBAL_FLAGS, "all"]);
4625
+ const groups = new Map;
4626
+ for (const entry of catalog.commands)
4627
+ groups.set(entry.resource, [...groups.get(entry.resource) ?? [], entry]);
4628
+ const objects = [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([object3, entries]) => ({
4629
+ object: object3,
4630
+ operations: entries.length,
4631
+ description: (entries.find((entry) => entry.kind === "list") ?? entries[0]).summary
4632
+ }));
4633
+ const lines = ctx.flags.all ? [...groups].sort(([a], [b]) => a.localeCompare(b)).flatMap(([object3, entries]) => [
4634
+ `
4635
+ ${object3} (${entries.length})`,
4636
+ ...entries.map((entry) => ` ${[entry.name, ...entry.positionals.map((name) => `<${name}>`)].join(" ").padEnd(48)} ${entry.method} ${entry.path} approval: ${entry.approval}`)
4637
+ ]) : objects.map((entry) => ` ${entry.object.padEnd(36)} ${String(entry.operations).padStart(3)} ${entry.description}`);
4293
4638
  ctx.emit(localEnvelope(catalog.commands, {
4294
4639
  context: { product, origin: catalog.origin || null },
4295
4640
  provenance: { kind: "catalog", source: catalog.source ?? null },
@@ -4297,7 +4642,8 @@ async function productCommand(words, ctx) {
4297
4642
  next: [{ action: `prudai describe ${product} <command>`, why: "Parameters, body and examples." }]
4298
4643
  }), [
4299
4644
  `prudai ${product} <command> [args] [flags] (${catalog.commands.length} commands; catalogue: ${catalog.source?.kind ?? "none"}${catalog.source?.ref ? ` ${catalog.source.ref}` : ""})`,
4300
- ...catalog.commands.map((entry) => ` ${[entry.name, ...entry.positionals.map((name) => `<${name}>`)].join(" ").padEnd(48)} ${entry.method} ${entry.path} approval: ${entry.approval}`)
4645
+ `${objects.length} objects. Use prudai ${product} help --all for every operation, or prudai ${product} <object> --help.`,
4646
+ ...lines
4301
4647
  ].join(`
4302
4648
  `));
4303
4649
  return 0;
@@ -4312,6 +4658,8 @@ async function runCli(args, options = {}) {
4312
4658
  const stderr = options.stderr ?? ((text) => console.error(text));
4313
4659
  const json = args.includes("--json");
4314
4660
  const secrets = new Set;
4661
+ const selection = {};
4662
+ let platformOutput = false;
4315
4663
  let revealing = false;
4316
4664
  const redact = (text) => {
4317
4665
  if (revealing)
@@ -4322,7 +4670,22 @@ async function runCli(args, options = {}) {
4322
4670
  out = out.split(secret).join("[redacted]");
4323
4671
  return out;
4324
4672
  };
4325
- const emit = (value, human) => stdout(redact(json ? JSON.stringify(value) : human ?? JSON.stringify(value, null, 2)));
4673
+ const emit = (value, human) => {
4674
+ if (selection.organization && isRecord(value)) {
4675
+ const context = isRecord(value.context) ? value.context : {};
4676
+ const serverOrganization = isRecord(context.organization) ? context.organization : {};
4677
+ const selected = {
4678
+ ...selection.organization,
4679
+ ...platformOutput ? { product: "platform" } : {},
4680
+ ...selection.organization.source === "login" && typeof serverOrganization.id === "string" ? { id: serverOrganization.id } : {}
4681
+ };
4682
+ value = { ...value, context: { ...context, organization: { ...serverOrganization, ...selected } } };
4683
+ if (human !== undefined)
4684
+ human += `
4685
+ organization: ${selected.id} (${selected.product}; ${selected.source})`;
4686
+ }
4687
+ stdout(redact(json ? JSON.stringify(value) : human ?? (isEnvelopeLike(value) ? renderEnvelope(value) : JSON.stringify(value, null, 2))));
4688
+ };
4326
4689
  const errOut = (text) => stderr(redact(text));
4327
4690
  try {
4328
4691
  const first = args.findIndex((arg) => !arg.startsWith("-"));
@@ -4336,6 +4699,23 @@ async function runCli(args, options = {}) {
4336
4699
  const parsed = parseArgs(args);
4337
4700
  const flags = parsed.flags;
4338
4701
  let words = parsed.words;
4702
+ if (flags.version === true) {
4703
+ validateFlags(flags, ["json", "version"]);
4704
+ if (words.length)
4705
+ throw new CliError("Usage: prudai --version | -v | version");
4706
+ emit(localEnvelope({ name: "prudai", version: VERSION }), VERSION);
4707
+ return 0;
4708
+ }
4709
+ if (flags.help && words.length && words[0] !== "help" && BUILTINS.has(words[0])) {
4710
+ const requested = words.join(" ");
4711
+ const alias = ALIASES[words[0]];
4712
+ const group = alias?.[0] ?? words[0];
4713
+ const commands = HELP.commands.filter((line) => line === group || line.startsWith(`${group} `));
4714
+ const data = { command: requested, usage: commands.map((line) => `prudai ${line}`), flags: HELP.flags };
4715
+ emit(localEnvelope(data), [`Help: prudai ${requested}`, ...data.usage, `Flags: ${HELP.flags.join(" ")}`].join(`
4716
+ `));
4717
+ return 0;
4718
+ }
4339
4719
  if (words[0] && ALIASES[words[0]])
4340
4720
  words = [...ALIASES[words[0]], ...words.slice(1)];
4341
4721
  const command = words[0];
@@ -4377,7 +4757,7 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4377
4757
  const now = options.now ?? Date.now;
4378
4758
  const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
4379
4759
  const base = { flags, env: env2, file, config, options };
4380
- const productWord = command === "describe" ? words[1] : command === "ops" || command === "api" || command === "approvals" ? str(flags, "product") : command;
4760
+ const productWord = command === "describe" ? words[1] : command === "ops" || command === "api" || command === "approvals" || command === "auth" ? str(flags, "product") : command;
4381
4761
  const named = productWord ? findProduct(productWord)?.product ?? productWord : undefined;
4382
4762
  const catalog = {
4383
4763
  env: env2,
@@ -4399,7 +4779,7 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4399
4779
  revealing = true;
4400
4780
  };
4401
4781
  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 });
4402
- const ctx = { options, env: env2, file, config, flags, json, emit, stderr: errOut, fetch: fetchImpl, now, sleep, catalog, reveal, session };
4782
+ const ctx = { options, env: env2, file, config, flags, json, emit, stderr: errOut, fetch: fetchImpl, now, sleep, catalog, reveal, session, selection };
4403
4783
  if (command === "auth")
4404
4784
  return await authCommand(words, ctx, options);
4405
4785
  if (command === "guide")
@@ -4418,8 +4798,10 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4418
4798
  return await skillCommand(words.slice(1), ctx);
4419
4799
  if (command === "mcp" && words[1] !== "connections")
4420
4800
  return await mcpCommand(words.slice(1), ctx);
4421
- if (command === "mcp" || PLATFORM_GROUPS.has(command))
4801
+ if (command === "mcp" || PLATFORM_GROUPS.has(command)) {
4802
+ platformOutput = true;
4422
4803
  return await platformCommand(words, ctx);
4804
+ }
4423
4805
  return await productCommand(words, ctx);
4424
4806
  } catch (error) {
4425
4807
  const failure = error instanceof CliError ? error : new CliError("Unexpected local or server failure.", 1, "unexpected_error");