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