@senticor/hive 1.162.2 → 1.163.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/hive.cjs +441 -414
  2. package/package.json +1 -1
package/hive.cjs CHANGED
@@ -9419,9 +9419,305 @@ async function freshToken(minValidityMs = REFRESH_SKEW_MS) {
9419
9419
  }
9420
9420
  return refreshToken(creds);
9421
9421
  }
9422
- async function getValidToken() {
9423
- const fresh = await freshToken();
9424
- return fresh.ok ? fresh.token : null;
9422
+ function tokenFailureExit(failure2, minTtlSeconds) {
9423
+ switch (failure2.reason) {
9424
+ case "not_logged_in":
9425
+ return { code: EXIT_NOT_AUTHORIZED, symbolic: "NOT_AUTHENTICATED", issuerFailure: false, message: "not logged in. Run 'hive login' first." };
9426
+ case "no_refresh_token": {
9427
+ const left = Math.round((failure2.expiresAt - Date.now()) / 1e3);
9428
+ const state = left > 0 ? `has ${left} s left, less than --min-ttl ${minTtlSeconds ?? 60},` : "has expired";
9429
+ return { code: EXIT_NOT_AUTHORIZED, symbolic: "NOT_AUTHENTICATED", issuerFailure: false, message: `the stored token ${state} and the login holds no refresh token. Run 'hive login' again.` };
9430
+ }
9431
+ case "refresh_refused":
9432
+ return { code: EXIT_NOT_AUTHORIZED, symbolic: "NOT_AUTHENTICATED", issuerFailure: false, message: `the issuer refused to refresh the login (${failure2.detail}). Run 'hive login' again.` };
9433
+ case "issuer_unreachable":
9434
+ return { code: EXIT_TRANSPORT_FAILED, symbolic: "ISSUER_UNREACHABLE", issuerFailure: true, message: `could not reach ${failure2.issuer} to refresh the login. The login is kept; try again.` };
9435
+ case "issuer_error":
9436
+ return { code: EXIT_REMOTE_FAILED, symbolic: "ISSUER_ERROR", issuerFailure: true, message: `${failure2.issuer} did not refresh the login: ${failure2.detail}. The login is kept; try again.` };
9437
+ }
9438
+ }
9439
+ function refreshThrowExit(err) {
9440
+ const issuer = getStoredCredentials()?.issuer ?? "the issuer";
9441
+ return {
9442
+ code: EXIT_TRANSPORT_FAILED,
9443
+ symbolic: "ISSUER_UNREACHABLE",
9444
+ issuerFailure: true,
9445
+ message: `could not reach ${issuer} to refresh the login: ${err.message}. The login is kept; try again.`
9446
+ };
9447
+ }
9448
+
9449
+ // src/lib/errors.ts
9450
+ init_cjs_shims();
9451
+
9452
+ // src/lib/tenant-selection.ts
9453
+ init_cjs_shims();
9454
+ var applied = null;
9455
+ function recordTenantSelection(selection) {
9456
+ applied = selection;
9457
+ }
9458
+ function appliedTenantSelection() {
9459
+ return applied;
9460
+ }
9461
+ function describeAppliedTenant(selection) {
9462
+ if (!selection.applied || selection.value === null) {
9463
+ return "No X-Hive-Tenant was sent, so the server resolved your self-tenant";
9464
+ }
9465
+ return `Sent X-Hive-Tenant: ${selection.value} (${selection.source}, from ${selection.origin})`;
9466
+ }
9467
+
9468
+ // src/lib/break-glass.ts
9469
+ init_cjs_shims();
9470
+ var sent = false;
9471
+ function recordBreakGlass(reason) {
9472
+ sent = reason !== null;
9473
+ }
9474
+ function breakGlassSent() {
9475
+ return sent;
9476
+ }
9477
+
9478
+ // src/lib/errors.ts
9479
+ var CliCommandError = class extends Error {
9480
+ exitCode;
9481
+ symbolicCode;
9482
+ remediation;
9483
+ tenant;
9484
+ problemType;
9485
+ details;
9486
+ constructor(symbolicCode, exitCode, message, options) {
9487
+ super(message, options);
9488
+ this.name = "CliCommandError";
9489
+ this.exitCode = exitCode;
9490
+ this.symbolicCode = symbolicCode;
9491
+ this.remediation = options?.remediation;
9492
+ this.tenant = options?.tenant;
9493
+ this.problemType = options?.problemType;
9494
+ this.details = options?.details;
9495
+ }
9496
+ };
9497
+ function commandError(symbolicCode, exitCode, message, options) {
9498
+ return new CliCommandError(symbolicCode, exitCode, message, options);
9499
+ }
9500
+ function remoteErrorFields(data) {
9501
+ const body = data ?? {};
9502
+ if (typeof body.type === "string" && typeof body.title === "string" && typeof body.status === "number") {
9503
+ return {
9504
+ code: typeof body.code === "string" ? body.code.trim() : "",
9505
+ message: typeof body.detail === "string" ? body.detail.trim() : body.title.trim()
9506
+ };
9507
+ }
9508
+ const raw = body.error;
9509
+ if (raw && typeof raw === "object") {
9510
+ const nested = raw;
9511
+ return {
9512
+ code: String(nested.code ?? "").trim(),
9513
+ message: String(nested.message ?? "").trim()
9514
+ };
9515
+ }
9516
+ return {
9517
+ code: String(raw || body.code || "").trim(),
9518
+ message: String(body.message || "").trim()
9519
+ };
9520
+ }
9521
+ function remoteProblemType(data) {
9522
+ if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
9523
+ const body = data;
9524
+ return typeof body.type === "string" && typeof body.title === "string" && typeof body.status === "number" ? body.type : void 0;
9525
+ }
9526
+ function remoteProblemDetails(data) {
9527
+ if (!remoteProblemType(data)) return void 0;
9528
+ const raw = data.details;
9529
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
9530
+ const out = {};
9531
+ for (const [name, value] of Object.entries(raw)) {
9532
+ if (value === null || ["string", "number", "boolean"].includes(typeof value)) out[name] = value;
9533
+ }
9534
+ return Object.keys(out).length ? out : void 0;
9535
+ }
9536
+ function fieldText(value) {
9537
+ if (value === null || value === void 0) return "";
9538
+ if (typeof value === "object") {
9539
+ try {
9540
+ const json2 = JSON.stringify(value);
9541
+ return json2 && json2 !== "{}" && json2 !== "[]" ? json2 : "";
9542
+ } catch {
9543
+ return "";
9544
+ }
9545
+ }
9546
+ return String(value).trim();
9547
+ }
9548
+ function schemaErrorFields(data) {
9549
+ const errors = data?.schemaErrors;
9550
+ if (!Array.isArray(errors)) return [];
9551
+ const paths = errors.map((entry) => String(entry?.instancePath ?? "").trim()).filter(Boolean).map((path10) => path10.replace(/^\//, ""));
9552
+ return [...new Set(paths)];
9553
+ }
9554
+ function remoteFailureRemediation(data) {
9555
+ const code = remoteErrorFields(data).code.toUpperCase();
9556
+ const scope = tenantFailureScope();
9557
+ if (code === "TENANT_NOT_ALLOWED") {
9558
+ const selection = appliedTenantSelection();
9559
+ const pinned = selection?.applied === true && selection.source === "pinned";
9560
+ return scope + "The requested tenant is not in your active memberships. " + (pinned ? "It is a saved pin, not something this command asked for \u2014 run 'hive config clear --tenant' to drop it. " : "If the tenant is saved in CLI config, run 'hive config clear --tenant'. ") + "Platform-scoped commands (hive org *, hive admin list|grant|revoke) ignore a pin already; for other platform-admin operations (mission create) omit --tenant / HIVE_TENANT. Run 'hive diag authz' to list memberships and optionally pin one with 'hive config use --tenant=<displayKey>'.";
9561
+ }
9562
+ if (code === "MISSION_NOT_FOUND") {
9563
+ return scope + "The mission id was not found in the CURRENT tenant scope. A mission is only visible under the tenant it was created in \u2014 check you are using the same --tenant / HIVE_TENANT (or self-tenant) as at create time. Run 'hive mission list --tenant <tenant>' to find the scope that owns it." + // #503: since #501 a platform admin who is not a member gets this 404 too.
9564
+ (breakGlassSent() ? "" : ' A platform admin who is not a member of the mission reaches it with --break-glass "<ticket reference>", audited.');
9565
+ }
9566
+ return void 0;
9567
+ }
9568
+ function tenantFailureScope() {
9569
+ const selection = appliedTenantSelection();
9570
+ return selection ? `${describeAppliedTenant(selection)}. ` : "";
9571
+ }
9572
+ function remoteFailureTenant(data) {
9573
+ const code = remoteErrorFields(data).code.toUpperCase();
9574
+ if (code !== "TENANT_NOT_ALLOWED" && code !== "MISSION_NOT_FOUND") return void 0;
9575
+ return appliedTenantSelection() ?? void 0;
9576
+ }
9577
+ function remoteFailureError(status2, data, action, exitCode = exitCodeForStatus(status2)) {
9578
+ const remediation = remoteFailureRemediation(data);
9579
+ const tenant = remoteFailureTenant(data);
9580
+ const problemType = remoteProblemType(data);
9581
+ const details = remoteProblemDetails(data);
9582
+ return commandError(
9583
+ "REMOTE_FAILED",
9584
+ exitCode,
9585
+ `${action} failed${status2 ? ` (HTTP ${status2})` : ""}: ${remoteFailureText(data)}${remediation ? ` \u2014 ${remediation}` : ""}`,
9586
+ remediation || tenant || problemType || details ? {
9587
+ ...remediation ? { remediation } : {},
9588
+ ...tenant ? { tenant } : {},
9589
+ ...problemType ? { problemType } : {},
9590
+ ...details ? { details } : {}
9591
+ } : void 0
9592
+ );
9593
+ }
9594
+ function remoteFailureText(data) {
9595
+ const body = data;
9596
+ const { code, message } = remoteErrorFields(data);
9597
+ const isProblem = typeof body?.type === "string" && typeof body?.title === "string" && typeof body?.status === "number";
9598
+ const parts = [code, message, ...isProblem ? [] : [fieldText(body?.detail)]].filter(Boolean);
9599
+ const fields = isProblem ? [] : schemaErrorFields(data);
9600
+ if (fields.length) parts.push(`(offending field${fields.length > 1 ? "s" : ""}: ${fields.join(", ")})`);
9601
+ const text = [...new Set(parts)].join(": ") || "unexpected response";
9602
+ const details = remoteProblemDetails(data);
9603
+ if (!details) return text;
9604
+ return `${text} (${Object.entries(details).map(([name, value]) => `${name}: ${JSON.stringify(value)}`).join(", ")})`;
9605
+ }
9606
+ function toStructuredError(err) {
9607
+ const e = err;
9608
+ const code = e?.symbolicCode || e?.code || "ERROR";
9609
+ const message = e?.symbolicCode ? e.message : formatCliError(err);
9610
+ return {
9611
+ ok: false,
9612
+ error: {
9613
+ code,
9614
+ message,
9615
+ ...e?.remediation ? { remediation: e.remediation } : {},
9616
+ ...e?.problemType ? { type: e.problemType } : {},
9617
+ ...e?.tenant ? { tenant: e.tenant } : {},
9618
+ ...e?.details ? { details: e.details } : {}
9619
+ }
9620
+ };
9621
+ }
9622
+ function isJsonMode(ctx2) {
9623
+ const args = ctx2?.args;
9624
+ if (args) {
9625
+ if (args.json === true) return true;
9626
+ return String(args.format ?? "").toLowerCase() === "json";
9627
+ }
9628
+ const argv = process.argv;
9629
+ if (argv.includes("--json")) return true;
9630
+ if (argv.some((a) => a.toLowerCase() === "--format=json")) return true;
9631
+ const i = argv.indexOf("--format");
9632
+ return i !== -1 && String(argv[i + 1] || "").toLowerCase() === "json";
9633
+ }
9634
+ function formatCliError(err) {
9635
+ const e = err;
9636
+ if (e?.symbolicCode) return `${e.symbolicCode}: ${e.message}`;
9637
+ switch (e?.code) {
9638
+ case "ENOENT":
9639
+ return `file not found: ${e.path ?? "(unknown path)"}`;
9640
+ case "EACCES":
9641
+ return `permission denied: ${e.path ?? "(unknown path)"}`;
9642
+ case "EISDIR":
9643
+ return `expected a file but found a directory: ${e.path ?? ""}`;
9644
+ case "ECONNREFUSED":
9645
+ return `cannot reach the API${e.address ? ` at ${e.address}:${e.port}` : ""} (connection refused). Is the stack up? Check --api-url / HIVE_API_URL, or run 'hive login'.`;
9646
+ case "ENOTFOUND":
9647
+ return `cannot resolve host '${e.hostname ?? ""}'. Check the API URL (--api-url / HIVE_API_URL).`;
9648
+ case "ETIMEDOUT":
9649
+ case "ECONNRESET":
9650
+ return `network error reaching the API (${e.code}). Check connectivity or --api-url.`;
9651
+ }
9652
+ if (e instanceof SyntaxError) return `invalid JSON: ${e.message}`;
9653
+ return e && e.message || String(err);
9654
+ }
9655
+ function exitCodeForError(err) {
9656
+ const e = err;
9657
+ if (typeof e?.exitCode === "number") return e.exitCode;
9658
+ return exitCodeForTransportError(e?.code) ?? EXIT_FAILURE;
9659
+ }
9660
+ function installRemoteFailureExit() {
9661
+ process.on("exit", (code) => {
9662
+ if (code !== EXIT_OK) return;
9663
+ const failure2 = pendingRemoteFailure();
9664
+ if (!failure2) return;
9665
+ const symbolic = remoteErrorFields(failure2.body).code || remoteFailureCode(failure2.status);
9666
+ const remediation = remoteFailureRemediation(failure2.body) ?? (failure2.status === 401 ? "Run 'hive login' to authenticate, or set HIVE_TOKEN." : void 0);
9667
+ const tenant = remoteFailureTenant(failure2.body);
9668
+ const problemType = remoteProblemType(failure2.body);
9669
+ const details = remoteProblemDetails(failure2.body);
9670
+ const message = `${failure2.method} ${failure2.path} failed${failure2.status ? ` (HTTP ${failure2.status})` : ""}: ${remoteFailureText(failure2.body)}`;
9671
+ if (isJsonMode()) {
9672
+ console.error(JSON.stringify({
9673
+ ok: false,
9674
+ error: {
9675
+ code: symbolic,
9676
+ message,
9677
+ ...problemType ? { type: problemType } : {},
9678
+ ...remediation ? { remediation } : {},
9679
+ ...tenant ? { tenant } : {},
9680
+ ...details ? { details } : {}
9681
+ }
9682
+ }));
9683
+ } else {
9684
+ console.error(`\x1B[31mError:\x1B[0m ${symbolic}: ${message}`);
9685
+ if (remediation) console.error(remediation);
9686
+ }
9687
+ process.exitCode = exitCodeForStatus(failure2.status);
9688
+ });
9689
+ }
9690
+ function installErrorHandling(cmd) {
9691
+ const verbose = process.argv.includes("-v") || process.argv.includes("--verbose");
9692
+ const seen = /* @__PURE__ */ new Set();
9693
+ const walk = (c) => {
9694
+ if (!c || typeof c !== "object" || seen.has(c)) return;
9695
+ seen.add(c);
9696
+ const node2 = c;
9697
+ if (typeof node2.run === "function") {
9698
+ const orig = node2.run;
9699
+ node2.run = async (ctx2) => {
9700
+ try {
9701
+ return await orig(ctx2);
9702
+ } catch (err) {
9703
+ if (isJsonMode(ctx2)) {
9704
+ console.error(JSON.stringify(toStructuredError(err)));
9705
+ } else {
9706
+ console.error(`\x1B[31mError:\x1B[0m ${formatCliError(err)}`);
9707
+ }
9708
+ if (verbose && err instanceof Error && err.stack) console.error(err.stack);
9709
+ process.exit(exitCodeForError(err));
9710
+ }
9711
+ };
9712
+ }
9713
+ const subs = node2.subCommands;
9714
+ if (subs && typeof subs === "object") {
9715
+ for (const key of Object.keys(subs)) {
9716
+ walk(subs[key]);
9717
+ }
9718
+ }
9719
+ };
9720
+ walk(cmd);
9425
9721
  }
9426
9722
 
9427
9723
  // src/lib/client.ts
@@ -9441,14 +9737,33 @@ var HiveClient = class {
9441
9737
  const headers = { accept };
9442
9738
  if (this.tenant) headers["x-hive-tenant"] = this.tenant;
9443
9739
  if (this.breakGlass) headers["x-hive-break-glass"] = this.breakGlass;
9740
+ const envToken2 = envToken()?.token;
9741
+ if (envToken2) {
9742
+ headers["authorization"] = `Bearer ${envToken2}`;
9743
+ return headers;
9744
+ }
9745
+ let fresh;
9444
9746
  try {
9445
- const token = envToken()?.token || await getValidToken();
9446
- if (token) headers["authorization"] = `Bearer ${token}`;
9747
+ fresh = await freshToken();
9447
9748
  } catch (e) {
9448
- if (this.verbose) console.error("Warning: Could not fetch auth token", e.message);
9749
+ throw this._refreshStop(refreshThrowExit(e), e);
9750
+ }
9751
+ if (fresh.ok) {
9752
+ headers["authorization"] = `Bearer ${fresh.token}`;
9753
+ } else {
9754
+ const t = tokenFailureExit(fresh.failure);
9755
+ if (t.issuerFailure) throw this._refreshStop(t);
9449
9756
  }
9450
9757
  return headers;
9451
9758
  }
9759
+ /**
9760
+ * The error that stops a command whose stored login could not be refreshed because of the
9761
+ * issuer (#518). It names the ways out, since the stop also reaches a command that would not
9762
+ * have needed the token (an expired login, a local API without auth).
9763
+ */
9764
+ _refreshStop(t, cause) {
9765
+ return commandError(t.symbolic, t.code, `${t.message} To go on without the stored login, run 'hive logout' or set HIVE_TOKEN.`, cause === void 0 ? void 0 : { cause });
9766
+ }
9452
9767
  /** Low-level request helper (no external deps, uses Node built-ins) */
9453
9768
  async _request(method, path10, body) {
9454
9769
  const url2 = new import_node_url2.URL(path10, this.baseUrl);
@@ -9570,403 +9885,129 @@ function renderKV(obj) {
9570
9885
  if (typeof v === "object" && !Array.isArray(v)) {
9571
9886
  lines.push(`${k}:`);
9572
9887
  for (const [sk, sv] of Object.entries(v)) {
9573
- lines.push(` ${sk}: ${typeof sv === "object" ? JSON.stringify(sv) : sv}`);
9574
- }
9575
- } else if (Array.isArray(v)) {
9576
- lines.push(`${k}: [${v.length} items]`);
9577
- } else {
9578
- lines.push(`${k}: ${v}`);
9579
- }
9580
- }
9581
- return lines.join("\n");
9582
- }
9583
- function renderTable(rows, meta3) {
9584
- if (!rows.length) return "(empty)";
9585
- const colSet = /* @__PURE__ */ new Set();
9586
- rows.slice(0, 20).forEach((r) => Object.keys(r).forEach((k) => colSet.add(k)));
9587
- const cols = [...colSet];
9588
- const widths = cols.map((c) => {
9589
- const maxVal = rows.reduce((mx, r) => {
9590
- const v = String(r[c] ?? "");
9591
- return v.length > mx ? v.length : mx;
9592
- }, c.length);
9593
- return Math.min(maxVal, 40);
9594
- });
9595
- const hdr = cols.map((c, i) => c.toUpperCase().padEnd(widths[i])).join(" ");
9596
- const sep = cols.map((_, i) => "\u2500".repeat(widths[i])).join("\u2500\u2500");
9597
- const body = rows.map(
9598
- (r) => cols.map((c, i) => {
9599
- let v = r[c];
9600
- if (v === null || v === void 0) v = "";
9601
- v = String(v);
9602
- if (v.length > 40) v = v.slice(0, 37) + "...";
9603
- return v.padEnd(widths[i]);
9604
- }).join(" ")
9605
- );
9606
- const parts = [hdr, sep, ...body];
9607
- if (meta3) {
9608
- const extras = [];
9609
- for (const [k, v] of Object.entries(meta3)) {
9610
- if (Array.isArray(v)) continue;
9611
- if (typeof v === "object") continue;
9612
- extras.push(`${k}: ${v}`);
9613
- }
9614
- if (extras.length) parts.push("", extras.join(" \u2502 "));
9615
- }
9616
- return parts.join("\n");
9617
- }
9618
- function output(data, format) {
9619
- const fmt = (format || "table").toLowerCase();
9620
- let text;
9621
- if (fmt === "json") text = formatJson(data);
9622
- else if (fmt === "yaml") text = formatYaml(data);
9623
- else text = formatTable(data);
9624
- console.log(text);
9625
- }
9626
-
9627
- // src/lib/config.ts
9628
- init_cjs_shims();
9629
- var import_node_fs2 = __toESM(require("fs"), 1);
9630
- var import_node_os2 = __toESM(require("os"), 1);
9631
- var import_node_path2 = __toESM(require("path"), 1);
9632
- var hiveDir2 = () => process.env.HIVE_CLI_STATE_DIR?.trim() || import_node_path2.default.join(import_node_os2.default.homedir(), ".hive");
9633
- var configFile = () => import_node_path2.default.join(hiveDir2(), "config.json");
9634
- function configPath() {
9635
- return configFile();
9636
- }
9637
- function readConfig() {
9638
- try {
9639
- const parsed = JSON.parse(import_node_fs2.default.readFileSync(configFile(), "utf-8"));
9640
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
9641
- } catch {
9642
- return {};
9643
- }
9644
- }
9645
- function saveConfig(patch2) {
9646
- const merged = { ...readConfig() };
9647
- for (const [key, value] of Object.entries(patch2)) {
9648
- if (typeof value === "string" && value.trim() !== "") merged[key] = value.trim();
9649
- }
9650
- import_node_fs2.default.mkdirSync(hiveDir2(), { recursive: true, mode: 448 });
9651
- import_node_fs2.default.writeFileSync(configFile(), JSON.stringify(merged, null, 2) + "\n", { mode: 384 });
9652
- return merged;
9653
- }
9654
- function clearConfig(keys) {
9655
- const merged = { ...readConfig() };
9656
- for (const key of keys) delete merged[key];
9657
- import_node_fs2.default.mkdirSync(hiveDir2(), { recursive: true, mode: 448 });
9658
- import_node_fs2.default.writeFileSync(configFile(), JSON.stringify(merged, null, 2) + "\n", { mode: 384 });
9659
- return merged;
9660
- }
9661
- function isInteractive() {
9662
- return Boolean(process.stdin.isTTY);
9663
- }
9664
- async function resolveSetting(opts) {
9665
- const flag = typeof opts.flag === "string" && opts.flag.trim() ? opts.flag.trim() : void 0;
9666
- if (flag) return { value: flag, source: "flag" };
9667
- const envVars = opts.envVar === void 0 ? [] : Array.isArray(opts.envVar) ? opts.envVar : [opts.envVar];
9668
- for (const name of envVars) {
9669
- const env = process.env[name]?.trim();
9670
- if (env) return { value: env, source: "env" };
9671
- }
9672
- const saved = opts.saved?.trim();
9673
- if (saved) return { value: saved, source: "saved" };
9674
- if (isInteractive()) {
9675
- const answer = (await promptText(`${opts.label} [${opts.def}]: `)).trim();
9676
- return answer ? { value: answer, source: "prompt" } : { value: opts.def, source: "default" };
9677
- }
9678
- return { value: opts.def, source: "default" };
9679
- }
9680
- async function fetchAuthConfig(apiUrl) {
9681
- try {
9682
- const base = apiUrl.replace(/\/+$/, "");
9683
- const res = await fetch(`${base}/api/auth/config`, { headers: { accept: "application/json, application/problem+json" } });
9684
- if (!res.ok) return null;
9685
- const body = await res.json();
9686
- const issuerUrl = typeof body.issuerUrl === "string" ? body.issuerUrl : void 0;
9687
- if (!issuerUrl) return null;
9688
- return {
9689
- issuerUrl,
9690
- clientId: typeof body.clientId === "string" ? body.clientId : void 0,
9691
- audience: typeof body.audience === "string" ? body.audience : void 0
9692
- };
9693
- } catch {
9694
- return null;
9695
- }
9696
- }
9697
-
9698
- // src/lib/errors.ts
9699
- init_cjs_shims();
9700
-
9701
- // src/lib/tenant-selection.ts
9702
- init_cjs_shims();
9703
- var applied = null;
9704
- function recordTenantSelection(selection) {
9705
- applied = selection;
9706
- }
9707
- function appliedTenantSelection() {
9708
- return applied;
9709
- }
9710
- function describeAppliedTenant(selection) {
9711
- if (!selection.applied || selection.value === null) {
9712
- return "No X-Hive-Tenant was sent, so the server resolved your self-tenant";
9713
- }
9714
- return `Sent X-Hive-Tenant: ${selection.value} (${selection.source}, from ${selection.origin})`;
9715
- }
9716
-
9717
- // src/lib/break-glass.ts
9718
- init_cjs_shims();
9719
- var sent = false;
9720
- function recordBreakGlass(reason) {
9721
- sent = reason !== null;
9722
- }
9723
- function breakGlassSent() {
9724
- return sent;
9725
- }
9726
-
9727
- // src/lib/errors.ts
9728
- var CliCommandError = class extends Error {
9729
- exitCode;
9730
- symbolicCode;
9731
- remediation;
9732
- tenant;
9733
- problemType;
9734
- details;
9735
- constructor(symbolicCode, exitCode, message, options) {
9736
- super(message, options);
9737
- this.name = "CliCommandError";
9738
- this.exitCode = exitCode;
9739
- this.symbolicCode = symbolicCode;
9740
- this.remediation = options?.remediation;
9741
- this.tenant = options?.tenant;
9742
- this.problemType = options?.problemType;
9743
- this.details = options?.details;
9744
- }
9745
- };
9746
- function commandError(symbolicCode, exitCode, message, options) {
9747
- return new CliCommandError(symbolicCode, exitCode, message, options);
9748
- }
9749
- function remoteErrorFields(data) {
9750
- const body = data ?? {};
9751
- if (typeof body.type === "string" && typeof body.title === "string" && typeof body.status === "number") {
9752
- return {
9753
- code: typeof body.code === "string" ? body.code.trim() : "",
9754
- message: typeof body.detail === "string" ? body.detail.trim() : body.title.trim()
9755
- };
9756
- }
9757
- const raw = body.error;
9758
- if (raw && typeof raw === "object") {
9759
- const nested = raw;
9760
- return {
9761
- code: String(nested.code ?? "").trim(),
9762
- message: String(nested.message ?? "").trim()
9763
- };
9764
- }
9765
- return {
9766
- code: String(raw || body.code || "").trim(),
9767
- message: String(body.message || "").trim()
9768
- };
9769
- }
9770
- function remoteProblemType(data) {
9771
- if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
9772
- const body = data;
9773
- return typeof body.type === "string" && typeof body.title === "string" && typeof body.status === "number" ? body.type : void 0;
9774
- }
9775
- function remoteProblemDetails(data) {
9776
- if (!remoteProblemType(data)) return void 0;
9777
- const raw = data.details;
9778
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
9779
- const out = {};
9780
- for (const [name, value] of Object.entries(raw)) {
9781
- if (value === null || ["string", "number", "boolean"].includes(typeof value)) out[name] = value;
9782
- }
9783
- return Object.keys(out).length ? out : void 0;
9784
- }
9785
- function fieldText(value) {
9786
- if (value === null || value === void 0) return "";
9787
- if (typeof value === "object") {
9788
- try {
9789
- const json2 = JSON.stringify(value);
9790
- return json2 && json2 !== "{}" && json2 !== "[]" ? json2 : "";
9791
- } catch {
9792
- return "";
9793
- }
9794
- }
9795
- return String(value).trim();
9796
- }
9797
- function schemaErrorFields(data) {
9798
- const errors = data?.schemaErrors;
9799
- if (!Array.isArray(errors)) return [];
9800
- const paths = errors.map((entry) => String(entry?.instancePath ?? "").trim()).filter(Boolean).map((path10) => path10.replace(/^\//, ""));
9801
- return [...new Set(paths)];
9802
- }
9803
- function remoteFailureRemediation(data) {
9804
- const code = remoteErrorFields(data).code.toUpperCase();
9805
- const scope = tenantFailureScope();
9806
- if (code === "TENANT_NOT_ALLOWED") {
9807
- const selection = appliedTenantSelection();
9808
- const pinned = selection?.applied === true && selection.source === "pinned";
9809
- return scope + "The requested tenant is not in your active memberships. " + (pinned ? "It is a saved pin, not something this command asked for \u2014 run 'hive config clear --tenant' to drop it. " : "If the tenant is saved in CLI config, run 'hive config clear --tenant'. ") + "Platform-scoped commands (hive org *, hive admin list|grant|revoke) ignore a pin already; for other platform-admin operations (mission create) omit --tenant / HIVE_TENANT. Run 'hive diag authz' to list memberships and optionally pin one with 'hive config use --tenant=<displayKey>'.";
9810
- }
9811
- if (code === "MISSION_NOT_FOUND") {
9812
- return scope + "The mission id was not found in the CURRENT tenant scope. A mission is only visible under the tenant it was created in \u2014 check you are using the same --tenant / HIVE_TENANT (or self-tenant) as at create time. Run 'hive mission list --tenant <tenant>' to find the scope that owns it." + // #503: since #501 a platform admin who is not a member gets this 404 too.
9813
- (breakGlassSent() ? "" : ' A platform admin who is not a member of the mission reaches it with --break-glass "<ticket reference>", audited.');
9888
+ lines.push(` ${sk}: ${typeof sv === "object" ? JSON.stringify(sv) : sv}`);
9889
+ }
9890
+ } else if (Array.isArray(v)) {
9891
+ lines.push(`${k}: [${v.length} items]`);
9892
+ } else {
9893
+ lines.push(`${k}: ${v}`);
9894
+ }
9814
9895
  }
9815
- return void 0;
9816
- }
9817
- function tenantFailureScope() {
9818
- const selection = appliedTenantSelection();
9819
- return selection ? `${describeAppliedTenant(selection)}. ` : "";
9820
- }
9821
- function remoteFailureTenant(data) {
9822
- const code = remoteErrorFields(data).code.toUpperCase();
9823
- if (code !== "TENANT_NOT_ALLOWED" && code !== "MISSION_NOT_FOUND") return void 0;
9824
- return appliedTenantSelection() ?? void 0;
9896
+ return lines.join("\n");
9825
9897
  }
9826
- function remoteFailureError(status2, data, action, exitCode = exitCodeForStatus(status2)) {
9827
- const remediation = remoteFailureRemediation(data);
9828
- const tenant = remoteFailureTenant(data);
9829
- const problemType = remoteProblemType(data);
9830
- const details = remoteProblemDetails(data);
9831
- return commandError(
9832
- "REMOTE_FAILED",
9833
- exitCode,
9834
- `${action} failed${status2 ? ` (HTTP ${status2})` : ""}: ${remoteFailureText(data)}${remediation ? ` \u2014 ${remediation}` : ""}`,
9835
- remediation || tenant || problemType || details ? {
9836
- ...remediation ? { remediation } : {},
9837
- ...tenant ? { tenant } : {},
9838
- ...problemType ? { problemType } : {},
9839
- ...details ? { details } : {}
9840
- } : void 0
9898
+ function renderTable(rows, meta3) {
9899
+ if (!rows.length) return "(empty)";
9900
+ const colSet = /* @__PURE__ */ new Set();
9901
+ rows.slice(0, 20).forEach((r) => Object.keys(r).forEach((k) => colSet.add(k)));
9902
+ const cols = [...colSet];
9903
+ const widths = cols.map((c) => {
9904
+ const maxVal = rows.reduce((mx, r) => {
9905
+ const v = String(r[c] ?? "");
9906
+ return v.length > mx ? v.length : mx;
9907
+ }, c.length);
9908
+ return Math.min(maxVal, 40);
9909
+ });
9910
+ const hdr = cols.map((c, i) => c.toUpperCase().padEnd(widths[i])).join(" ");
9911
+ const sep = cols.map((_, i) => "\u2500".repeat(widths[i])).join("\u2500\u2500");
9912
+ const body = rows.map(
9913
+ (r) => cols.map((c, i) => {
9914
+ let v = r[c];
9915
+ if (v === null || v === void 0) v = "";
9916
+ v = String(v);
9917
+ if (v.length > 40) v = v.slice(0, 37) + "...";
9918
+ return v.padEnd(widths[i]);
9919
+ }).join(" ")
9841
9920
  );
9921
+ const parts = [hdr, sep, ...body];
9922
+ if (meta3) {
9923
+ const extras = [];
9924
+ for (const [k, v] of Object.entries(meta3)) {
9925
+ if (Array.isArray(v)) continue;
9926
+ if (typeof v === "object") continue;
9927
+ extras.push(`${k}: ${v}`);
9928
+ }
9929
+ if (extras.length) parts.push("", extras.join(" \u2502 "));
9930
+ }
9931
+ return parts.join("\n");
9842
9932
  }
9843
- function remoteFailureText(data) {
9844
- const body = data;
9845
- const { code, message } = remoteErrorFields(data);
9846
- const isProblem = typeof body?.type === "string" && typeof body?.title === "string" && typeof body?.status === "number";
9847
- const parts = [code, message, ...isProblem ? [] : [fieldText(body?.detail)]].filter(Boolean);
9848
- const fields = isProblem ? [] : schemaErrorFields(data);
9849
- if (fields.length) parts.push(`(offending field${fields.length > 1 ? "s" : ""}: ${fields.join(", ")})`);
9850
- const text = [...new Set(parts)].join(": ") || "unexpected response";
9851
- const details = remoteProblemDetails(data);
9852
- if (!details) return text;
9853
- return `${text} (${Object.entries(details).map(([name, value]) => `${name}: ${JSON.stringify(value)}`).join(", ")})`;
9933
+ function output(data, format) {
9934
+ const fmt = (format || "table").toLowerCase();
9935
+ let text;
9936
+ if (fmt === "json") text = formatJson(data);
9937
+ else if (fmt === "yaml") text = formatYaml(data);
9938
+ else text = formatTable(data);
9939
+ console.log(text);
9854
9940
  }
9855
- function toStructuredError(err) {
9856
- const e = err;
9857
- const code = e?.symbolicCode || e?.code || "ERROR";
9858
- const message = e?.symbolicCode ? e.message : formatCliError(err);
9859
- return {
9860
- ok: false,
9861
- error: {
9862
- code,
9863
- message,
9864
- ...e?.remediation ? { remediation: e.remediation } : {},
9865
- ...e?.problemType ? { type: e.problemType } : {},
9866
- ...e?.tenant ? { tenant: e.tenant } : {},
9867
- ...e?.details ? { details: e.details } : {}
9868
- }
9869
- };
9941
+
9942
+ // src/lib/config.ts
9943
+ init_cjs_shims();
9944
+ var import_node_fs2 = __toESM(require("fs"), 1);
9945
+ var import_node_os2 = __toESM(require("os"), 1);
9946
+ var import_node_path2 = __toESM(require("path"), 1);
9947
+ var hiveDir2 = () => process.env.HIVE_CLI_STATE_DIR?.trim() || import_node_path2.default.join(import_node_os2.default.homedir(), ".hive");
9948
+ var configFile = () => import_node_path2.default.join(hiveDir2(), "config.json");
9949
+ function configPath() {
9950
+ return configFile();
9870
9951
  }
9871
- function isJsonMode(ctx2) {
9872
- const args = ctx2?.args;
9873
- if (args) {
9874
- if (args.json === true) return true;
9875
- return String(args.format ?? "").toLowerCase() === "json";
9952
+ function readConfig() {
9953
+ try {
9954
+ const parsed = JSON.parse(import_node_fs2.default.readFileSync(configFile(), "utf-8"));
9955
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
9956
+ } catch {
9957
+ return {};
9876
9958
  }
9877
- const argv = process.argv;
9878
- if (argv.includes("--json")) return true;
9879
- if (argv.some((a) => a.toLowerCase() === "--format=json")) return true;
9880
- const i = argv.indexOf("--format");
9881
- return i !== -1 && String(argv[i + 1] || "").toLowerCase() === "json";
9882
9959
  }
9883
- function formatCliError(err) {
9884
- const e = err;
9885
- if (e?.symbolicCode) return `${e.symbolicCode}: ${e.message}`;
9886
- switch (e?.code) {
9887
- case "ENOENT":
9888
- return `file not found: ${e.path ?? "(unknown path)"}`;
9889
- case "EACCES":
9890
- return `permission denied: ${e.path ?? "(unknown path)"}`;
9891
- case "EISDIR":
9892
- return `expected a file but found a directory: ${e.path ?? ""}`;
9893
- case "ECONNREFUSED":
9894
- return `cannot reach the API${e.address ? ` at ${e.address}:${e.port}` : ""} (connection refused). Is the stack up? Check --api-url / HIVE_API_URL, or run 'hive login'.`;
9895
- case "ENOTFOUND":
9896
- return `cannot resolve host '${e.hostname ?? ""}'. Check the API URL (--api-url / HIVE_API_URL).`;
9897
- case "ETIMEDOUT":
9898
- case "ECONNRESET":
9899
- return `network error reaching the API (${e.code}). Check connectivity or --api-url.`;
9960
+ function saveConfig(patch2) {
9961
+ const merged = { ...readConfig() };
9962
+ for (const [key, value] of Object.entries(patch2)) {
9963
+ if (typeof value === "string" && value.trim() !== "") merged[key] = value.trim();
9900
9964
  }
9901
- if (e instanceof SyntaxError) return `invalid JSON: ${e.message}`;
9902
- return e && e.message || String(err);
9965
+ import_node_fs2.default.mkdirSync(hiveDir2(), { recursive: true, mode: 448 });
9966
+ import_node_fs2.default.writeFileSync(configFile(), JSON.stringify(merged, null, 2) + "\n", { mode: 384 });
9967
+ return merged;
9903
9968
  }
9904
- function exitCodeForError(err) {
9905
- const e = err;
9906
- if (typeof e?.exitCode === "number") return e.exitCode;
9907
- return exitCodeForTransportError(e?.code) ?? EXIT_FAILURE;
9969
+ function clearConfig(keys) {
9970
+ const merged = { ...readConfig() };
9971
+ for (const key of keys) delete merged[key];
9972
+ import_node_fs2.default.mkdirSync(hiveDir2(), { recursive: true, mode: 448 });
9973
+ import_node_fs2.default.writeFileSync(configFile(), JSON.stringify(merged, null, 2) + "\n", { mode: 384 });
9974
+ return merged;
9908
9975
  }
9909
- function installRemoteFailureExit() {
9910
- process.on("exit", (code) => {
9911
- if (code !== EXIT_OK) return;
9912
- const failure2 = pendingRemoteFailure();
9913
- if (!failure2) return;
9914
- const symbolic = remoteErrorFields(failure2.body).code || remoteFailureCode(failure2.status);
9915
- const remediation = remoteFailureRemediation(failure2.body) ?? (failure2.status === 401 ? "Run 'hive login' to authenticate, or set HIVE_TOKEN." : void 0);
9916
- const tenant = remoteFailureTenant(failure2.body);
9917
- const problemType = remoteProblemType(failure2.body);
9918
- const details = remoteProblemDetails(failure2.body);
9919
- const message = `${failure2.method} ${failure2.path} failed${failure2.status ? ` (HTTP ${failure2.status})` : ""}: ${remoteFailureText(failure2.body)}`;
9920
- if (isJsonMode()) {
9921
- console.error(JSON.stringify({
9922
- ok: false,
9923
- error: {
9924
- code: symbolic,
9925
- message,
9926
- ...problemType ? { type: problemType } : {},
9927
- ...remediation ? { remediation } : {},
9928
- ...tenant ? { tenant } : {},
9929
- ...details ? { details } : {}
9930
- }
9931
- }));
9932
- } else {
9933
- console.error(`\x1B[31mError:\x1B[0m ${symbolic}: ${message}`);
9934
- if (remediation) console.error(remediation);
9935
- }
9936
- process.exitCode = exitCodeForStatus(failure2.status);
9937
- });
9976
+ function isInteractive() {
9977
+ return Boolean(process.stdin.isTTY);
9938
9978
  }
9939
- function installErrorHandling(cmd) {
9940
- const verbose = process.argv.includes("-v") || process.argv.includes("--verbose");
9941
- const seen = /* @__PURE__ */ new Set();
9942
- const walk = (c) => {
9943
- if (!c || typeof c !== "object" || seen.has(c)) return;
9944
- seen.add(c);
9945
- const node2 = c;
9946
- if (typeof node2.run === "function") {
9947
- const orig = node2.run;
9948
- node2.run = async (ctx2) => {
9949
- try {
9950
- return await orig(ctx2);
9951
- } catch (err) {
9952
- if (isJsonMode(ctx2)) {
9953
- console.error(JSON.stringify(toStructuredError(err)));
9954
- } else {
9955
- console.error(`\x1B[31mError:\x1B[0m ${formatCliError(err)}`);
9956
- }
9957
- if (verbose && err instanceof Error && err.stack) console.error(err.stack);
9958
- process.exit(exitCodeForError(err));
9959
- }
9960
- };
9961
- }
9962
- const subs = node2.subCommands;
9963
- if (subs && typeof subs === "object") {
9964
- for (const key of Object.keys(subs)) {
9965
- walk(subs[key]);
9966
- }
9967
- }
9968
- };
9969
- walk(cmd);
9979
+ async function resolveSetting(opts) {
9980
+ const flag = typeof opts.flag === "string" && opts.flag.trim() ? opts.flag.trim() : void 0;
9981
+ if (flag) return { value: flag, source: "flag" };
9982
+ const envVars = opts.envVar === void 0 ? [] : Array.isArray(opts.envVar) ? opts.envVar : [opts.envVar];
9983
+ for (const name of envVars) {
9984
+ const env = process.env[name]?.trim();
9985
+ if (env) return { value: env, source: "env" };
9986
+ }
9987
+ const saved = opts.saved?.trim();
9988
+ if (saved) return { value: saved, source: "saved" };
9989
+ if (isInteractive()) {
9990
+ const answer = (await promptText(`${opts.label} [${opts.def}]: `)).trim();
9991
+ return answer ? { value: answer, source: "prompt" } : { value: opts.def, source: "default" };
9992
+ }
9993
+ return { value: opts.def, source: "default" };
9994
+ }
9995
+ async function fetchAuthConfig(apiUrl) {
9996
+ try {
9997
+ const base = apiUrl.replace(/\/+$/, "");
9998
+ const res = await fetch(`${base}/api/auth/config`, { headers: { accept: "application/json, application/problem+json" } });
9999
+ if (!res.ok) return null;
10000
+ const body = await res.json();
10001
+ const issuerUrl = typeof body.issuerUrl === "string" ? body.issuerUrl : void 0;
10002
+ if (!issuerUrl) return null;
10003
+ return {
10004
+ issuerUrl,
10005
+ clientId: typeof body.clientId === "string" ? body.clientId : void 0,
10006
+ audience: typeof body.audience === "string" ? body.audience : void 0
10007
+ };
10008
+ } catch {
10009
+ return null;
10010
+ }
9970
10011
  }
9971
10012
 
9972
10013
  // src/lib/runtime.ts
@@ -10511,22 +10552,22 @@ var artifactName = injectedString(
10511
10552
  true ? "hive-cli" : void 0
10512
10553
  ) || String(process.env.HIVE_CLI_ARTIFACT_NAME || "hive-cli").trim() || "hive-cli";
10513
10554
  var packageVersion = injectedString(
10514
- true ? "1.162.2" : void 0
10555
+ true ? "1.163.1" : void 0
10515
10556
  ) || String(process.env.HIVE_CLI_PACKAGE_VERSION || "").trim() || readPackageVersion();
10516
10557
  var releaseVersion = injectedString(
10517
- true ? "1.162.2" : void 0
10558
+ true ? "1.163.1" : void 0
10518
10559
  ) || String(process.env.HIVE_CLI_RELEASE_VERSION || "").trim() || packageVersion || "dev";
10519
10560
  var releaseChannel = injectedString(
10520
10561
  true ? "final" : void 0
10521
10562
  ) || String(process.env.HIVE_CLI_RELEASE_CHANNEL || "").trim() || (releaseVersion.includes("-rc.") ? "rc" : releaseVersion === "dev" ? "dev" : "final");
10522
10563
  var buildCommit = injectedString(
10523
- true ? "5dfc2911afa120277c2a835af7ae0f7e9808eaec" : void 0
10564
+ true ? "9bc96d0072199373b9292867188f0b072b278910" : void 0
10524
10565
  ) || String(process.env.HIVE_CLI_BUILD_COMMIT || "").trim() || "unknown";
10525
10566
  var buildTimestamp = injectedString(
10526
- true ? "2026-11-17T18:42:56Z" : void 0
10567
+ true ? "2026-11-18T00:17:57Z" : void 0
10527
10568
  ) || String(process.env.HIVE_CLI_BUILD_TIMESTAMP || "").trim() || "unknown";
10528
10569
  var ociRef = injectedString(
10529
- true ? "registry.onstackit.cloud/senticor/hive-cli:1.162.2" : void 0
10570
+ true ? "registry.onstackit.cloud/senticor/hive-cli:1.163.1" : void 0
10530
10571
  ) || String(process.env.HIVE_CLI_OCI_REF || "").trim() || `registry.onstackit.cloud/senticor/${artifactName}:${releaseVersion}`;
10531
10572
  var RELEASE_INFO = Object.freeze({
10532
10573
  packageVersion,
@@ -11692,26 +11733,12 @@ async function printAuthToken(args) {
11692
11733
  try {
11693
11734
  fresh = await freshToken(minTtl * 1e3);
11694
11735
  } catch (err) {
11695
- const issuer = getStoredCredentials()?.issuer ?? "the issuer";
11696
- tokenFailure(`could not reach ${issuer} to refresh the login: ${err.message}`, EXIT_TRANSPORT_FAILED);
11736
+ const t = refreshThrowExit(err);
11737
+ tokenFailure(t.message, t.code);
11697
11738
  }
11698
11739
  if (!fresh.ok) {
11699
- const { failure: failure2 } = fresh;
11700
- switch (failure2.reason) {
11701
- case "not_logged_in":
11702
- return tokenFailure("not logged in. Run 'hive login' first.", EXIT_NOT_AUTHORIZED);
11703
- case "no_refresh_token": {
11704
- const left2 = Math.round((failure2.expiresAt - Date.now()) / 1e3);
11705
- const state = left2 > 0 ? `has ${left2} s left, less than --min-ttl ${minTtl},` : "has expired";
11706
- return tokenFailure(`the stored token ${state} and the login holds no refresh token. Run 'hive login' again.`, EXIT_NOT_AUTHORIZED);
11707
- }
11708
- case "refresh_refused":
11709
- return tokenFailure(`the issuer refused to refresh the login (${failure2.detail}). Run 'hive login' again.`, EXIT_NOT_AUTHORIZED);
11710
- case "issuer_unreachable":
11711
- return tokenFailure(`could not reach ${failure2.issuer} to refresh the login. The login is kept; try again.`, EXIT_TRANSPORT_FAILED);
11712
- case "issuer_error":
11713
- return tokenFailure(`${failure2.issuer} did not refresh the login: ${failure2.detail}. The login is kept; try again.`, EXIT_REMOTE_FAILED);
11714
- }
11740
+ const t = tokenFailureExit(fresh.failure, minTtl);
11741
+ return tokenFailure(t.message, t.code);
11715
11742
  }
11716
11743
  const left = Math.round((fresh.expiresAt - Date.now()) / 1e3);
11717
11744
  if (left < minTtl) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senticor/hive",
3
- "version": "1.162.2",
3
+ "version": "1.163.1",
4
4
  "description": "Cognitive Hive OS — unified CLI",
5
5
  "type": "commonjs",
6
6
  "bin": {