@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/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
  }
@@ -1088,6 +1324,7 @@ function generateCommands(product, spec, options = {}) {
1088
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;
1089
1325
  drafts.push({ preferred, fallback, pinned: !!pinned, command: {
1090
1326
  product,
1327
+ ...organization ? { organization } : {},
1091
1328
  kind,
1092
1329
  method: method.toUpperCase(),
1093
1330
  path,
@@ -1307,9 +1544,10 @@ function buildOperationRequest(command, args = {}) {
1307
1544
  const suppliedHeaders = new Map;
1308
1545
  for (const [name, value] of Object.entries(args.headers ?? {})) {
1309
1546
  const normalized = name.toLowerCase();
1310
- if (!isSafeHeaderName(name))
1547
+ const organizationHeader = command.organization?.header.toLowerCase() === normalized;
1548
+ if (!organizationHeader && !isSafeHeaderName(name))
1311
1549
  throw new CliError(`Header cannot be supplied as input: ${name}`, 2, "invalid_parameter");
1312
- if (!declaredHeaders.has(normalized) && normalized !== "if-match" && normalized !== "idempotency-key")
1550
+ if (!organizationHeader && !declaredHeaders.has(normalized) && normalized !== "if-match" && normalized !== "idempotency-key")
1313
1551
  throw new CliError(`Undeclared header parameter: ${name}`, 2, "invalid_parameter");
1314
1552
  if (typeof value !== "string" || /[^\t\x20-\x7e\x80-\xff]/.test(value))
1315
1553
  throw new CliError(`Invalid header parameter: ${name}`, 2, "invalid_parameter");
@@ -1356,113 +1594,6 @@ function buildOperationRequest(command, args = {}) {
1356
1594
  // src/cli.ts
1357
1595
  import { resolve as resolvePath } from "node:path";
1358
1596
 
1359
- // src/args.ts
1360
- var BOOLEAN_FLAGS = new Set([
1361
- "json",
1362
- "help",
1363
- "yes",
1364
- "dry-run",
1365
- "no-dry-run",
1366
- "no-browser",
1367
- "stdin",
1368
- "online",
1369
- "refresh",
1370
- "offline",
1371
- "reveal",
1372
- "force",
1373
- "execute",
1374
- "print",
1375
- "wait",
1376
- "no-wait",
1377
- "check",
1378
- "all",
1379
- "include-archived",
1380
- "trash"
1381
- ]);
1382
- var GLOBAL_FLAGS = new Set([
1383
- "json",
1384
- "help",
1385
- "yes",
1386
- "dry-run",
1387
- "no-dry-run",
1388
- "refresh",
1389
- "offline",
1390
- "wait",
1391
- "timeout",
1392
- "profile",
1393
- "spec",
1394
- "registry",
1395
- "api-url",
1396
- "data",
1397
- "idempotency-key",
1398
- "if-match"
1399
- ]);
1400
- function parseArgs(args) {
1401
- const words = [];
1402
- const flags = {};
1403
- for (let index = 0;index < args.length; index++) {
1404
- const arg = args[index];
1405
- if (arg === "-h") {
1406
- flags.help = true;
1407
- continue;
1408
- }
1409
- if (arg === "-y") {
1410
- flags.yes = true;
1411
- continue;
1412
- }
1413
- if (!arg.startsWith("--")) {
1414
- words.push(arg);
1415
- continue;
1416
- }
1417
- const equals = arg.indexOf("=");
1418
- const name = arg.slice(2, equals === -1 ? undefined : equals);
1419
- if (/(token|secret|password|credential|authorization|api[-_]?key)/i.test(name)) {
1420
- throw new CliError("Credentials must come from the environment or the protected config file; credential flags are forbidden.");
1421
- }
1422
- if (!name || Object.hasOwn(flags, name))
1423
- throw new CliError("Empty or duplicate flag.");
1424
- if (BOOLEAN_FLAGS.has(name)) {
1425
- if (equals !== -1)
1426
- throw new CliError(`--${name} does not accept a value.`);
1427
- flags[name] = true;
1428
- } else {
1429
- const value = equals !== -1 ? arg.slice(equals + 1) : args[++index];
1430
- if (value === undefined || value.startsWith("--"))
1431
- throw new CliError(`--${name} requires a value.`);
1432
- flags[name] = value;
1433
- }
1434
- }
1435
- if (flags["dry-run"] && flags["no-dry-run"])
1436
- throw new CliError("Conflicting dry-run flags.");
1437
- if (flags.wait && flags["no-wait"])
1438
- throw new CliError("Conflicting wait flags.");
1439
- return { words, flags };
1440
- }
1441
- function str(flags, key) {
1442
- return typeof flags[key] === "string" ? flags[key] : undefined;
1443
- }
1444
- function validateFlags(flags, allowed) {
1445
- const set = new Set(allowed);
1446
- for (const name of Object.keys(flags))
1447
- if (!set.has(name))
1448
- throw new CliError(`Unknown flag --${name}.`);
1449
- }
1450
- function safeApiOrigin(raw) {
1451
- const url = secureUrl(raw);
1452
- if (url.pathname !== "/" || url.search)
1453
- throw new CliError("API URL must be an origin without a path or query.");
1454
- return url.origin;
1455
- }
1456
- function intFlag(flags, key, fallback, min, max) {
1457
- const raw = str(flags, key);
1458
- if (raw === undefined)
1459
- return fallback;
1460
- const value = Number(raw);
1461
- if (!Number.isInteger(value) || value < min || value > max)
1462
- throw new CliError(`--${key} must be a whole number from ${min} to ${max}.`);
1463
- return value;
1464
- }
1465
-
1466
1597
  // src/catalog.ts
1467
1598
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
1468
1599
  import { dirname as dirname2, join as join2 } from "node:path";
@@ -1702,9 +1833,18 @@ async function loadCatalog(ctx, only) {
1702
1833
  function commandLine(command) {
1703
1834
  return [command.commandLine ?? `prudai ${command.product} ${command.name}`, ...command.positionals.map((name) => `<${name}>`)].join(" ");
1704
1835
  }
1705
- 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`);
1706
1845
  function searchOperations(catalogs, query, filters = {}) {
1707
1846
  const terms = tokens(query);
1847
+ const concepts = terms.map((term) => ({ term, alternatives: new Set([term, ...SEARCH_SYNONYMS.filter((group) => group.includes(term)).flat()]) }));
1708
1848
  const hits = [];
1709
1849
  for (const catalog of catalogs) {
1710
1850
  if (filters.product && catalog.product !== (findProduct(filters.product)?.product ?? filters.product))
@@ -1715,29 +1855,38 @@ function searchOperations(catalogs, query, filters = {}) {
1715
1855
  if (filters.method && command.method !== filters.method.toUpperCase())
1716
1856
  continue;
1717
1857
  const fields = [
1718
- [`${command.commandLine ?? `${command.product} ${command.name}`}`, 5],
1719
- [command.path, 3],
1720
- [command.summary, 3],
1721
- [command.operationId, 2],
1722
- [(command.tags ?? []).join(" "), 2],
1723
- [(command.scopes ?? []).join(" "), 2],
1724
- [(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]
1725
1865
  ];
1726
1866
  let score = 0;
1727
1867
  let matched = 0;
1728
- for (const term of terms) {
1868
+ let directPrimary = 0;
1869
+ for (const { term, alternatives } of concepts) {
1729
1870
  let best = 0;
1730
- for (const [text, weight] of fields)
1731
- 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))))
1732
1878
  best = Math.max(best, weight);
1879
+ }
1733
1880
  if (best) {
1734
1881
  matched++;
1735
1882
  score += best;
1736
1883
  }
1737
1884
  }
1738
- if (terms.length && !matched)
1885
+ if (terms.length && matched !== terms.length)
1739
1886
  continue;
1740
- score += matched * 10;
1887
+ score += directPrimary * 100;
1888
+ if (concepts.length === 1 && concepts[0].alternatives.has(command.name.toLowerCase()))
1889
+ score += 30;
1741
1890
  hits.push({
1742
1891
  command: commandLine(command),
1743
1892
  product: command.product,
@@ -1881,7 +2030,15 @@ async function requireToken(ctx, product) {
1881
2030
  }
1882
2031
  async function call(ctx, t, method, suffix, body) {
1883
2032
  requireTrustedOrigin(t.origin, ctx.env);
1884
- 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}`;
1885
2042
  }
1886
2043
  function fail(status, body, what) {
1887
2044
  const error = httpError(status, body);
@@ -1893,7 +2050,7 @@ var idOf = (value) => {
1893
2050
  return value;
1894
2051
  };
1895
2052
  async function waitForApproval(ctx, opts) {
1896
- 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 };
1897
2054
  const deadline = ctx.now() + (opts.timeoutSeconds ?? 600) * 1000;
1898
2055
  let status = "pending";
1899
2056
  let last = {};
@@ -1906,14 +2063,14 @@ async function waitForApproval(ctx, opts) {
1906
2063
  if (status !== "pending")
1907
2064
  break;
1908
2065
  if (ctx.now() >= deadline) {
1909
- 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");
1910
2067
  }
1911
2068
  await ctx.sleep(Math.min(APPROVAL_POLL_MS, Math.max(0, deadline - ctx.now())));
1912
2069
  }
1913
2070
  const summary = { id: opts.id, product: opts.product, status, level: last.level, operation: last.operation, executeUntil: last.executeUntil ?? null };
1914
2071
  if (status === "approved") {
1915
2072
  if (!opts.execute) {
1916
- const next = `prudai approvals execute ${opts.id} --product ${opts.product}`;
2073
+ const next = followCommand(ctx, t, "execute", opts.id);
1917
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}`);
1918
2075
  return 0;
1919
2076
  }
@@ -1936,14 +2093,15 @@ async function executeApproved(ctx, t, id) {
1936
2093
  if (executed.status !== "executed" || typeof executed.resultStatus !== "number")
1937
2094
  throw new CliError("Unexpected execute response.", 1, "invalid_response");
1938
2095
  const result = executed.result;
2096
+ assertOrganizationMatches(result, ctx.selection.organization, true);
1939
2097
  if (executed.resultStatus >= 400)
1940
2098
  throw new CliError(`The approved call ran and returned HTTP ${executed.resultStatus}.`, executed.resultStatus >= 500 ? 1 : 2, `http_${executed.resultStatus}`);
1941
2099
  const envelope = isEnvelopeLike(result) ? parseEnvelope(result) : localEnvelope(result ?? null, { provenance: { kind: "product", product: t.product }, context: { approvalRequestId: id, resultStatus: executed.resultStatus } });
1942
- ctx.emit(envelope, renderEnvelope(envelope));
2100
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
1943
2101
  return 0;
1944
2102
  }
1945
2103
  async function approvalsCommand(words, ctx) {
1946
- 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"]);
1947
2105
  const [action, id, ...extra] = words;
1948
2106
  if (extra.length)
1949
2107
  throw new CliError("Too many arguments.");
@@ -1951,6 +2109,10 @@ async function approvalsCommand(words, ctx) {
1951
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");
1952
2110
  }
1953
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);
1954
2116
  if (action === "list") {
1955
2117
  const status = str(ctx.flags, "status") ?? "pending";
1956
2118
  if (!["pending", "approved", "all"].includes(status))
@@ -1966,7 +2128,7 @@ async function approvalsCommand(words, ctx) {
1966
2128
  ctx.emit(localEnvelope(items, {
1967
2129
  provenance: { kind: "product", product: t.product },
1968
2130
  completeness: { returned: items.length, truncated: items.length >= limit },
1969
- 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." }]
1970
2132
  }));
1971
2133
  return 0;
1972
2134
  }
@@ -1974,7 +2136,8 @@ async function approvalsCommand(words, ctx) {
1974
2136
  const response = await call(ctx, t, "GET", `/${encodeURIComponent(idOf(id))}${action === "status" ? "/status" : ""}`);
1975
2137
  if (response.status !== 200)
1976
2138
  fail(response.status, response.body, "Approval lookup");
1977
- 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 }));
1978
2141
  return 0;
1979
2142
  }
1980
2143
  if (action === "wait") {
@@ -1986,7 +2149,8 @@ async function approvalsCommand(words, ctx) {
1986
2149
  const response = await call(ctx, t, "POST", `/${encodeURIComponent(idOf(id))}/cancel`);
1987
2150
  if (response.status !== 200)
1988
2151
  fail(response.status, response.body, "Cancel approval");
1989
- 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 }));
1990
2154
  return 0;
1991
2155
  }
1992
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)");
@@ -2276,6 +2440,8 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2276
2440
  allowed.add(parameter.name);
2277
2441
  }
2278
2442
  validateFlags(flags, allowed);
2443
+ if (!extras.organizationInPath)
2444
+ organizationHeaders(operation.product, operation.organization, ctx);
2279
2445
  if (operation.approval === "forbidden_for_agents")
2280
2446
  throw new CliError("This operation is forbidden for agents; a human does it in the product app.", 2, "forbidden_for_agents");
2281
2447
  if (operation.multipart && !extras.upload) {
@@ -2288,6 +2454,7 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2288
2454
  const token = await credentialFor(operation.product, ctx);
2289
2455
  if (!token)
2290
2456
  throw missingCredential(operation.product);
2457
+ const selectedHeaders = extras.organizationInPath ? {} : organizationHeaders(operation.product, operation.organization, ctx);
2291
2458
  const isGet = operation.method.toUpperCase() === "GET";
2292
2459
  const writing = !isGet && !operation.readsViaPost;
2293
2460
  const approvalsPath = extras.approvalsPath ?? findProduct(operation.product)?.approvalsPath;
@@ -2343,6 +2510,8 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2343
2510
  const etag = str(flags, "if-match");
2344
2511
  if (etag)
2345
2512
  headers["if-match"] = etag;
2513
+ for (const [name, value] of Object.entries(selectedHeaders))
2514
+ headers[name.toLowerCase()] = value;
2346
2515
  const dryRun = writing && !flags["no-dry-run"];
2347
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") });
2348
2517
  if (extras.upload && dryRun) {
@@ -2372,6 +2541,15 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2372
2541
  if (extras.irreversible && !dryRun)
2373
2542
  stderr(`Warning: ${IRREVERSIBLE}`);
2374
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
+ }
2375
2553
  let result;
2376
2554
  if (extras.upload) {
2377
2555
  const sent = await requestMultipart(ctx.fetch, target2, { method: request.method, headers: request.headers, token, env: env2, file: extras.upload.file });
@@ -2385,6 +2563,7 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2385
2563
  result = answer;
2386
2564
  } else
2387
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");
2388
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;
2389
2568
  if (accepted)
2390
2569
  stderr("Note: accepted. The document is processed again in the background (status pending); read its status with the matching get command.");
@@ -2394,10 +2573,11 @@ async function executeOperation(operation, positionals, origin, ctx, extras = {}
2394
2573
  stderr(`Warning: ${pending.warning}`);
2395
2574
  const request202 = pending.approvalRequest;
2396
2575
  const id = typeof request202.approvalRequestId === "string" ? request202.approvalRequestId : typeof request202.id === "string" ? request202.id : undefined;
2397
- 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;
2398
2578
  if (flags.wait && id && approvalsPath) {
2399
2579
  stderr(`APPROVAL REQUIRED. ${pending.next} Waiting (prudai approvals wait ${id}).`);
2400
- 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) });
2401
2581
  }
2402
2582
  const out = { ...pending, ...follow ? { follow, next: `${pending.next} Then run: ${follow}` } : {} };
2403
2583
  emit(out, `APPROVAL REQUIRED. ${out.next}
@@ -2427,7 +2607,7 @@ ${JSON.stringify(pending.approvalRequest, null, 2)}`);
2427
2607
  `DRY RUN — nothing was executed. Would send: ${would.method} ${would.path}${request.body !== undefined ? ` ${JSON.stringify(request.body)}` : ""}`,
2428
2608
  `approval: ${operation.approval}`,
2429
2609
  ...extras.irreversible ? [`IRREVERSIBLE: ${IRREVERSIBLE}`] : [],
2430
- ...envelope ? [renderEnvelope(envelope)] : [],
2610
+ ...envelope ? [renderEnvelope(envelope, { list: operation.kind === "list" })] : [],
2431
2611
  "Repeat with --no-dry-run --yes to execute this request.",
2432
2612
  ...extras.after ? [`Afterwards: ${extras.after.action} (${extras.after.why})`] : []
2433
2613
  ].join(`
@@ -2439,7 +2619,7 @@ ${JSON.stringify(pending.approvalRequest, null, 2)}`);
2439
2619
  return 0;
2440
2620
  }
2441
2621
  const shown = extras.after ? { ...envelope, next: [...envelope.next, extras.after] } : envelope;
2442
- emit(shown, renderEnvelope(shown));
2622
+ emit(shown, renderEnvelope(shown, { list: operation.kind === "list" }));
2443
2623
  return 0;
2444
2624
  }
2445
2625
  async function emitDownload(answer, options, operation, ctx) {
@@ -2575,7 +2755,9 @@ async function apiCommand(words, ctx) {
2575
2755
  delete flags.product;
2576
2756
  return executeOperation(match.command, positionals, origin, { ...ctx, flags });
2577
2757
  }
2578
- 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);
2579
2761
  if (!origin)
2580
2762
  throw new CliError(`Configure the ${product} API origin (--api-url).`);
2581
2763
  if (catalog?.notAvailable)
@@ -2585,6 +2767,7 @@ async function apiCommand(words, ctx) {
2585
2767
  const token = await credentialFor(product, ctx);
2586
2768
  if (!token)
2587
2769
  throw missingCredential(product);
2770
+ const selectedHeaders = organizationHeaders(product, organization, ctx);
2588
2771
  const writing = method !== "GET";
2589
2772
  const body = await readData(ctx.flags);
2590
2773
  if (!writing && body !== undefined)
@@ -2592,7 +2775,7 @@ async function apiCommand(words, ctx) {
2592
2775
  if (writing && !(ctx.flags["no-dry-run"] && ctx.flags.yes)) {
2593
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");
2594
2777
  }
2595
- const headers = {};
2778
+ const headers = { ...selectedHeaders };
2596
2779
  if (writing) {
2597
2780
  const key = str(ctx.flags, "idempotency-key") ?? crypto.randomUUID();
2598
2781
  if (!key.trim() || /[^\t\x20-\x7e]/.test(key))
@@ -2602,6 +2785,7 @@ async function apiCommand(words, ctx) {
2602
2785
  }
2603
2786
  ctx.stderr(`Note: ${method} ${path} is not in the ${product} catalogue; sent as-is to ${apiUrl}.`);
2604
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");
2605
2789
  if (result.status === 202) {
2606
2790
  const pending = approvalResult(result.body, ctx.env);
2607
2791
  if (pending.warning)
@@ -2612,7 +2796,7 @@ async function apiCommand(words, ctx) {
2612
2796
  if (result.status >= 400)
2613
2797
  throw httpError(result.status, result.body, product);
2614
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."] });
2615
- ctx.emit(envelope, renderEnvelope(envelope));
2799
+ ctx.emit(envelope, renderEnvelope(envelope, { list: false }));
2616
2800
  return 0;
2617
2801
  }
2618
2802
 
@@ -3208,9 +3392,14 @@ async function platformCommand(words, ctx) {
3208
3392
  if (op.costsMoney)
3209
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.");
3210
3394
  if (op.orgScoped) {
3211
- 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;
3212
3400
  if (!org)
3213
3401
  throw new CliError("Name the organisation: --org <organization id> (prudai whoami shows yours).");
3402
+ ctx.selection.organization = choice;
3214
3403
  positionals = [org, ...positionals];
3215
3404
  }
3216
3405
  const origin = resolveOrigin(PLATFORM_PRODUCT, ctx, platform.spec);
@@ -3228,7 +3417,8 @@ async function platformCommand(words, ctx) {
3228
3417
  if (op.custom === "memos-list")
3229
3418
  return listMemos(access, command, project, ctx);
3230
3419
  const flags = { ...ctx.flags };
3231
- delete flags.org;
3420
+ if (op.orgScoped)
3421
+ delete flags.org;
3232
3422
  for (const entry of op.body ?? [])
3233
3423
  for (const name of [entry.flag, ...entry.aliases ?? []])
3234
3424
  delete flags[name];
@@ -3240,6 +3430,7 @@ async function platformCommand(words, ctx) {
3240
3430
  }
3241
3431
  const target2 = project ? { project: { id: project.id, name: project.name } } : upload && positionals[0] ? { knowledge_base: positionals[0] } : undefined;
3242
3432
  const extras = {
3433
+ ...op.orgScoped ? { organizationInPath: true } : {},
3243
3434
  ...body ? { body } : {},
3244
3435
  consumed: [...op.query ?? [], ...extraFlags.filter((entry) => entry.query).map((entry) => entry.query)],
3245
3436
  ...upload ? { upload: { file: upload, ...target2 ? { target: target2 } : {} } } : {},
@@ -3353,7 +3544,7 @@ function platformHelp() {
3353
3544
  }
3354
3545
 
3355
3546
  // src/version.ts
3356
- var VERSION = "0.1.1";
3547
+ var VERSION = "0.1.2";
3357
3548
 
3358
3549
  // src/discovery.ts
3359
3550
  var CATALOG_FLAGS = ["json", "help", "profile", "refresh", "offline", "spec", "registry", "api-url"];
@@ -3387,6 +3578,8 @@ var ERROR_CODES = {
3387
3578
  invalid_response: "The server answered with something that is not JSON.",
3388
3579
  invalid_envelope: "The server sent a malformed /v1 envelope.",
3389
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.",
3390
3583
  unknown_profile: "The selected profile does not exist; create it or pick another.",
3391
3584
  "<server code>": "Other HTTP errors carry the product's own code (context.error.code), e.g. not_found, conflict.",
3392
3585
  "http_<status>": "An HTTP error without a recognisable code; the message gives a hint per status.",
@@ -3456,7 +3649,12 @@ plus ops search and describe are enough.
3456
3649
  prudai describe <product> <command…> parameters, body schema + example, responses, curl
3457
3650
  prudai describe irma:<operationId> …or by operationId, or: prudai describe GET /v1/risks
3458
3651
  prudai describe keys create platform commands too: route, scope, approval, status
3459
- 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.
3460
3658
  prudai help --json machine-readable command list
3461
3659
  Products:
3462
3660
  ${products}
@@ -3473,16 +3671,30 @@ ${products}
3473
3671
  or export PRUDAI_REFRESH_TOKEN (the refresh token of such a login). A person can end any session.
3474
3672
  Check: prudai whoami (= auth status: user, organisation; --online proves the session still lives)
3475
3673
  Profiles: one login per profile; prudai profile list|create|use; --profile <name> per call. A login
3476
- 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.
3477
3689
  Token for another tool, without printing it:
3478
3690
  curl -H "Authorization: Bearer $(prudai auth token --reveal --product irma)" … (never run --reveal bare)
3479
3691
  prudai logout ends the session at Keycloak first. Tokens are only sent to https://*.prudai.com and
3480
3692
  localhost; another origin needs PRUDAI_ALLOW_ORIGIN=<exact origin> in the environment.
3481
3693
 
3482
3694
  3. SCOPES <product>:<object>:<verb>, verb = read | write | delete
3483
- read scopes never need a person. write and delete scopes are the HITL class: their
3484
- operations carry an approval level (confirm, review, …; see 6), so a person approves before
3485
- 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.
3486
3698
  Wildcard <product>:*:<verb> covers every object of that product and verb, including later
3487
3699
  ones — but never explicit-only objects (licensed text, credit-spending chat/answers, api_keys,
3488
3700
  subscriptions). Invalid: *, *:x:read, p:*:*, p:o:*. prudai keys scopes lists them once the platform serves
@@ -3510,8 +3722,14 @@ ${products}
3510
3722
  --if-match <etag> for optimistic concurrency. Deletes are soft (restore exists).
3511
3723
 
3512
3724
  6. HUMAN APPROVAL (HITL)
3513
- Levels per operation (x-prudai-approval): none, instruct, confirm, review (second person),
3514
- 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.
3515
3733
  HTTP 202 = approval_required, exit 2, NOT success. The answer shows the approval link (only
3516
3734
  for trusted Prudai origins) and: prudai approvals wait <id> --product <p> --execute
3517
3735
  which waits for the human decision and then lets the server run exactly the approved call.
@@ -3628,7 +3846,10 @@ var HELP = {
3628
3846
  "--refresh",
3629
3847
  "--offline",
3630
3848
  "--out <path> [--force]",
3631
- "--project <id|name>"
3849
+ "--project <id|name>",
3850
+ "--org <id>",
3851
+ "--all",
3852
+ "--version / -v"
3632
3853
  ],
3633
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.",
3634
3855
  exitCodes: EXIT_CODES,
@@ -3783,11 +4004,45 @@ function param(parameter) {
3783
4004
  `)[0].slice(0, 200) } : {}
3784
4005
  };
3785
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
+ }
3786
4041
  function describeCommand(command, catalog) {
3787
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));
3788
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) }));
3789
4044
  const writing = command.method !== "GET" && !command.readsViaPost;
3790
- 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;
3791
4046
  const base = ["prudai", command.product, command.name, ...command.positionals.map((name) => `<${name}>`)].join(" ");
3792
4047
  const dataArg = body ? ` --data '${JSON.stringify(body.example)}'` : "";
3793
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("] [")}]` : ""}`];
@@ -3862,7 +4117,8 @@ async function describePlatform(op, ctx) {
3862
4117
  `${doc.command}`,
3863
4118
  `${op.method} ${op.path} — ${op.summary}`,
3864
4119
  `scope: ${op.scope} approval: ${op.approval} status: ${op.status}${bound ? "" : " (not available yet)"}${op.costsMoney ? " costs money" : ""}`,
3865
- ...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)}`] : []
3866
4122
  ].join(`
3867
4123
  `));
3868
4124
  return 0;
@@ -3890,7 +4146,7 @@ async function describeOperationCommand(words, ctx) {
3890
4146
  const doc = describeCommand(found.command, found.catalog);
3891
4147
  ctx.emit(localEnvelope(doc, {
3892
4148
  provenance: { kind: "catalog", product: found.catalog.product, source: found.catalog.source ?? null },
3893
- 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."],
3894
4150
  next: [{ action: doc.examples.cli[0].replace(/\s+#.*$/, ""), why: found.command.method === "GET" ? "Run it." : "Preview it first." }]
3895
4151
  }), [
3896
4152
  `${doc.command}`,
@@ -3903,7 +4159,7 @@ ${doc.description}
3903
4159
  ...doc.idempotency ? [`idempotency: key always sent; replay protection ${doc.idempotency.declared ? "declared" : "not declared"}`] : [],
3904
4160
  ...doc.positionals.length ? ["positionals:", ...doc.positionals.map((p) => ` <${p.name}> (${p.in}${p.required ? ", required" : ""}) ${p.type ?? ""} ${p.description ?? ""}`)] : [],
3905
4161
  ...doc.flags.length ? ["flags:", ...doc.flags.map((f) => ` ${f.flag}${f.required ? " (required)" : ""} ${f.type ?? ""}${f.enum ? ` ${JSON.stringify(f.enum)}` : ""} ${f.description ?? ""}`)] : [],
3906
- ...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)}`] : [],
3907
4163
  `responses: ${doc.responses.map((r) => `${r.status}${r.description ? ` ${r.description}` : ""}`).join("; ")}`,
3908
4164
  "examples:",
3909
4165
  ...doc.examples.cli.map((line) => ` ${line}`),
@@ -3933,11 +4189,30 @@ description: Use the Prudai CLI (\`prudai\`) for anything with Prudai — LEO, I
3933
4189
  \`prudai\` is the complete interface to Prudai for people and agents. Do not guess routes or
3934
4190
  scopes: discover them.
3935
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
+
3936
4209
  1. \`prudai ops search "<what you want>"\` — operations across all products, with the exact
3937
4210
  command, scope, approval level (HITL) and cost.
3938
4211
  2. \`prudai describe <product> <command…>\` — parameters, body schema, an example and curl.
3939
4212
  3. Run it with \`--json\`. Reads run directly; writes preview first (dry run) and need
3940
- \`--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:
3941
4216
  \`prudai approvals wait <id> --product <p> --execute\`.
3942
4217
  4. Exit codes: 0 done · 1 network/server (check state before retrying a write) · 2 you must act.
3943
4218
  "not available yet" (error not_available) means the platform has not built it: say so,
@@ -3952,8 +4227,14 @@ service runs them the answer is 403 \`approval_required\` and nothing happened;
3952
4227
 
3953
4228
  Never pass credentials as flags, never print a token (\`auth token --reveal\` only inside
3954
4229
  \`$(…)\`), never approve on a human's behalf, never pay. Credentials: \`prudai login\` (Keycloak device login; people and agents),
3955
- 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.
3956
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.
3957
4238
 
3958
4239
  | Product | What | Operations | Catalogue |
3959
4240
  | --- | --- | --- | --- |
@@ -4077,11 +4358,11 @@ function matchCommand(commands, rest) {
4077
4358
  }
4078
4359
  return;
4079
4360
  }
4080
- 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))$/;
4081
4362
  function setProfileValue(profile, key, value, env2, stderr) {
4082
4363
  const match2 = PROFILE_KEYS.exec(key);
4083
4364
  if (!match2)
4084
- throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, registryUrl.");
4365
+ throw new CliError("Settable keys: productApiUrls.<product>, specs.<product>, orgs.<product>, registryUrl.");
4085
4366
  const next = { ...profile };
4086
4367
  if (match2[3]) {
4087
4368
  if (value === undefined) {
@@ -4103,6 +4384,10 @@ function setProfileValue(profile, key, value, env2, stderr) {
4103
4384
  map[product] = safeApiOrigin(value);
4104
4385
  if (!isTrustedOrigin(map[product], env2))
4105
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;
4106
4391
  } else {
4107
4392
  if (!value.trim())
4108
4393
  throw new CliError("A spec source must be a path or URL.");
@@ -4234,7 +4519,7 @@ var BUILTINS = new Set([
4234
4519
  var ALIASES = { login: ["auth", "login"], logout: ["auth", "logout"], whoami: ["auth", "status"] };
4235
4520
  async function authCommand(words, ctx, options) {
4236
4521
  const { flags, env: env2, config, file } = ctx;
4237
- 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"]));
4238
4523
  const action = words[1];
4239
4524
  if (action === "switch-org")
4240
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");
@@ -4248,8 +4533,18 @@ async function authCommand(words, ctx, options) {
4248
4533
  throw new CliError("--reveal belongs to prudai auth token and prudai auth export.");
4249
4534
  if (flags.online && action !== "status")
4250
4535
  throw new CliError("--online belongs to prudai auth status.");
4251
- if (flags.product && action !== "token")
4252
- 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
+ }
4253
4548
  const save = options.saveConfig ?? ((cfg) => writeConfig(configPath(env2), cfg));
4254
4549
  const authOptions = {
4255
4550
  config,
@@ -4282,9 +4577,19 @@ async function authCommand(words, ctx, options) {
4282
4577
  ctx.emit(localEnvelope(meta, { provenance: { kind: "local" }, notIncluded: ["The secret itself; use --reveal only inside $(…)."] }), JSON.stringify(meta, null, 2));
4283
4578
  return 0;
4284
4579
  }
4285
- 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) : (() => {
4286
4581
  throw new CliError("Unknown auth command. Use login, status, logout, token, export or set --stdin.");
4287
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
+ }
4288
4593
  const message2 = result.message;
4289
4594
  ctx.emit(localEnvelope(result, { provenance: { kind: "auth", origin: config.issuer } }), typeof message2 === "string" ? `${message2}
4290
4595
  ${JSON.stringify(result, null, 2)}` : JSON.stringify(result, null, 2));
@@ -4301,8 +4606,35 @@ async function productCommand(words, ctx) {
4301
4606
  for (const warning of catalog.warnings)
4302
4607
  ctx.stderr(`Warning: ${warning}`);
4303
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
+ }
4304
4623
  if (words[1] === "help" || ctx.flags.help || words.length === 1) {
4305
- 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}`);
4306
4638
  ctx.emit(localEnvelope(catalog.commands, {
4307
4639
  context: { product, origin: catalog.origin || null },
4308
4640
  provenance: { kind: "catalog", source: catalog.source ?? null },
@@ -4310,7 +4642,8 @@ async function productCommand(words, ctx) {
4310
4642
  next: [{ action: `prudai describe ${product} <command>`, why: "Parameters, body and examples." }]
4311
4643
  }), [
4312
4644
  `prudai ${product} <command> [args] [flags] (${catalog.commands.length} commands; catalogue: ${catalog.source?.kind ?? "none"}${catalog.source?.ref ? ` ${catalog.source.ref}` : ""})`,
4313
- ...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
4314
4647
  ].join(`
4315
4648
  `));
4316
4649
  return 0;
@@ -4325,6 +4658,8 @@ async function runCli(args, options = {}) {
4325
4658
  const stderr = options.stderr ?? ((text) => console.error(text));
4326
4659
  const json = args.includes("--json");
4327
4660
  const secrets = new Set;
4661
+ const selection = {};
4662
+ let platformOutput = false;
4328
4663
  let revealing = false;
4329
4664
  const redact = (text) => {
4330
4665
  if (revealing)
@@ -4335,7 +4670,22 @@ async function runCli(args, options = {}) {
4335
4670
  out = out.split(secret).join("[redacted]");
4336
4671
  return out;
4337
4672
  };
4338
- 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
+ };
4339
4689
  const errOut = (text) => stderr(redact(text));
4340
4690
  try {
4341
4691
  const first = args.findIndex((arg) => !arg.startsWith("-"));
@@ -4349,6 +4699,23 @@ async function runCli(args, options = {}) {
4349
4699
  const parsed = parseArgs(args);
4350
4700
  const flags = parsed.flags;
4351
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
+ }
4352
4719
  if (words[0] && ALIASES[words[0]])
4353
4720
  words = [...ALIASES[words[0]], ...words.slice(1)];
4354
4721
  const command = words[0];
@@ -4390,7 +4757,7 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4390
4757
  const now = options.now ?? Date.now;
4391
4758
  const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
4392
4759
  const base = { flags, env: env2, file, config, options };
4393
- 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;
4394
4761
  const named = productWord ? findProduct(productWord)?.product ?? productWord : undefined;
4395
4762
  const catalog = {
4396
4763
  env: env2,
@@ -4412,7 +4779,7 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4412
4779
  revealing = true;
4413
4780
  };
4414
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 });
4415
- 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 };
4416
4783
  if (command === "auth")
4417
4784
  return await authCommand(words, ctx, options);
4418
4785
  if (command === "guide")
@@ -4431,8 +4798,10 @@ Exit codes: 0 completed · 1 network/server · 2 you must act (validation, auth,
4431
4798
  return await skillCommand(words.slice(1), ctx);
4432
4799
  if (command === "mcp" && words[1] !== "connections")
4433
4800
  return await mcpCommand(words.slice(1), ctx);
4434
- if (command === "mcp" || PLATFORM_GROUPS.has(command))
4801
+ if (command === "mcp" || PLATFORM_GROUPS.has(command)) {
4802
+ platformOutput = true;
4435
4803
  return await platformCommand(words, ctx);
4804
+ }
4436
4805
  return await productCommand(words, ctx);
4437
4806
  } catch (error) {
4438
4807
  const failure = error instanceof CliError ? error : new CliError("Unexpected local or server failure.", 1, "unexpected_error");