@nouter/platform-cli 0.2.0 → 0.4.0

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 (3) hide show
  1. package/README.md +82 -6
  2. package/dist/index.js +2641 -516
  3. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -7368,23 +7368,11 @@ var require_dist = __commonJS({
7368
7368
 
7369
7369
  // src/index.ts
7370
7370
  import { spawn } from "node:child_process";
7371
- import { randomBytes } from "node:crypto";
7372
- import {
7373
- chmodSync,
7374
- closeSync,
7375
- existsSync,
7376
- fchmodSync,
7377
- lstatSync,
7378
- mkdirSync,
7379
- openSync,
7380
- readFileSync as readFileSync3,
7381
- renameSync,
7382
- statSync as statSync2,
7383
- unlinkSync,
7384
- writeSync
7385
- } from "node:fs";
7386
- import { homedir, hostname } from "node:os";
7387
- import { join as join2 } from "node:path";
7371
+ import { randomBytes as randomBytes3 } from "node:crypto";
7372
+ import { readFileSync as readFileSync4 } from "node:fs";
7373
+ import { hostname } from "node:os";
7374
+ import { dirname, join as join3 } from "node:path";
7375
+ import { fileURLToPath } from "node:url";
7388
7376
  import {
7389
7377
  NouterPlatform
7390
7378
  } from "@nouter/platform";
@@ -8248,318 +8236,1074 @@ function formatApplyResults(results) {
8248
8236
  return lines;
8249
8237
  }
8250
8238
 
8251
- // src/identity-token.ts
8252
- import { readFileSync as readFileSync2 } from "node:fs";
8253
- var IdentityTokenError = class extends Error {
8254
- constructor(message) {
8255
- super(message);
8256
- this.name = "IdentityTokenError";
8239
+ // src/api-errors.ts
8240
+ function describeApiFailure(error) {
8241
+ const candidate = error;
8242
+ const status = typeof candidate.status === "number" ? candidate.status : void 0;
8243
+ if (status !== void 0) {
8244
+ const type = candidate.error?.error?.type ?? candidate.error?.type ?? candidate.type;
8245
+ const code2 = candidate.error?.error?.details?.error_code ?? candidate.errorCode;
8246
+ const detail = [type, code2].filter((part) => typeof part === "string" && part.length > 0).join(", ");
8247
+ const requestId = candidate.request_id ?? candidate.error?.request_id ?? candidate.requestId ?? candidate.requestID;
8248
+ return `the server answered ${status}${detail ? ` (${detail})` : ""}${requestId ? `, request ${requestId}` : ""}`;
8257
8249
  }
8258
- };
8259
- var NON_EMPTY = (value) => typeof value === "string" && value.length > 0;
8260
- function identityTokenSourceFromEnv(env = process.env) {
8261
- const value = env.NOUTER_PLATFORM_IDENTITY_TOKEN;
8262
- if (NON_EMPTY(value)) return { kind: "value", token: value };
8263
- const path = env.NOUTER_PLATFORM_IDENTITY_TOKEN_FILE;
8264
- if (NON_EMPTY(path)) return { kind: "file", path };
8265
- return null;
8266
- }
8267
- var PRINTABLE = /^[\x21-\x7e]+$/u;
8268
- function clean(token) {
8269
- const trimmed = token.trim();
8270
- if (trimmed.length === 0) throw new IdentityTokenError("The identity token is empty.");
8271
- if (!PRINTABLE.test(trimmed)) {
8272
- throw new IdentityTokenError("The identity token has characters the CLI cannot use.");
8250
+ const name = error.name;
8251
+ const causeName = candidate.cause?.name;
8252
+ if (name === "AbortError" || name === "TimeoutError" || name === "APIConnectionTimeoutError" || // El SDK envuelve el aborto propio (nuestro `AbortSignal.timeout`) en este error.
8253
+ name === "APIUserAbortError" || causeName === "AbortError" || causeName === "TimeoutError" || candidate.cause?.code === "ABORT_ERR") {
8254
+ return "the request timed out";
8273
8255
  }
8274
- return trimmed;
8256
+ const code = candidate.cause?.code;
8257
+ return code ? `the request failed (${code})` : "the request failed";
8275
8258
  }
8276
- function createIdentityTokenReader(source, read = (path) => readFileSync2(path, "utf8")) {
8277
- if (source.kind === "value") {
8278
- return { read: () => clean(source.token) };
8259
+
8260
+ // src/feedback.ts
8261
+ var import_yaml2 = __toESM(require_dist(), 1);
8262
+ import { randomUUID } from "node:crypto";
8263
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
8264
+ import { createInterface } from "node:readline/promises";
8265
+
8266
+ // src/printable.ts
8267
+ var UNSAFE_CHARACTERS = new RegExp(
8268
+ "[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u061c\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2069\\ufeff\\ufe00-\\ufe0f\\u{e0000}-\\u{e007f}]",
8269
+ "gu"
8270
+ );
8271
+ function printable(text) {
8272
+ return text.replace(UNSAFE_CHARACTERS, "\uFFFD");
8273
+ }
8274
+
8275
+ // src/non-api-host.ts
8276
+ function hostOf(url) {
8277
+ try {
8278
+ return new URL(url).host;
8279
+ } catch {
8280
+ return url;
8279
8281
  }
8280
- return {
8281
- read() {
8282
- let contents;
8283
- try {
8284
- contents = read(source.path);
8285
- } catch {
8286
- throw new IdentityTokenError(`Could not read the identity token file ${source.path}.`);
8287
- }
8288
- return clean(contents);
8289
- }
8290
- };
8282
+ }
8283
+ function notTheApiMessage(url, response) {
8284
+ const status = response.status;
8285
+ if (status >= 500) return null;
8286
+ const contentType = (response.headers.get("content-type") ?? "").trim();
8287
+ const mediaType = contentType.toLowerCase();
8288
+ const isRedirect = status >= 300 && status < 400;
8289
+ const isHtml = mediaType.startsWith("text/html");
8290
+ const followedToNonJson = response.redirected && !mediaType.includes("application/json");
8291
+ if (!isRedirect && !isHtml && !followedToNonJson) return null;
8292
+ const shown = printable(contentType || "(no content-type)");
8293
+ return `this host is not the API: ${hostOf(url)} responded ${status} ${shown}`;
8291
8294
  }
8292
8295
 
8293
- // src/federation.ts
8294
- var FederationError = class extends Error {
8295
- constructor(message) {
8296
- super(message);
8297
- this.name = "FederationError";
8296
+ // src/feedback.ts
8297
+ var FEEDBACK_FLAG = "NOUTER_PLATFORM_FEEDBACK";
8298
+ var FEEDBACK_DISABLED_MESSAGE = "Feedback commands are disabled; set NOUTER_PLATFORM_FEEDBACK=1";
8299
+ var FEEDBACK_CREATE_VALUES = ["--title", "--field", "--fields"];
8300
+ var FEEDBACK_CREATE_BOOLEANS = ["--yes", "--confirm-duplicate", "--json"];
8301
+ var FEEDBACK_SHOW_VALUES = [];
8302
+ var FEEDBACK_SHOW_BOOLEANS = ["--json"];
8303
+ var FEEDBACK_VOTE_VALUES = [];
8304
+ var FEEDBACK_VOTE_BOOLEANS = [];
8305
+ var FEEDBACK_COMMENT_VALUES = ["--body", "--body-file"];
8306
+ var FEEDBACK_COMMENT_BOOLEANS = [];
8307
+ var FEEDBACK_LIST_VALUES = ["--cursor"];
8308
+ var FEEDBACK_LIST_BOOLEANS = ["--json"];
8309
+ var FEEDBACK_COMMANDS = [
8310
+ {
8311
+ path: "feedback bug",
8312
+ summary: "Report a bug to the Nouter feedback repository",
8313
+ values: FEEDBACK_CREATE_VALUES,
8314
+ booleans: FEEDBACK_CREATE_BOOLEANS,
8315
+ positionals: []
8316
+ },
8317
+ {
8318
+ path: "feedback feature",
8319
+ summary: "Request a feature in the Nouter feedback repository",
8320
+ values: FEEDBACK_CREATE_VALUES,
8321
+ booleans: FEEDBACK_CREATE_BOOLEANS,
8322
+ positionals: []
8323
+ },
8324
+ {
8325
+ path: "feedback question",
8326
+ summary: "Ask a question in the Nouter feedback repository",
8327
+ values: FEEDBACK_CREATE_VALUES,
8328
+ booleans: FEEDBACK_CREATE_BOOLEANS,
8329
+ positionals: []
8330
+ },
8331
+ {
8332
+ path: "feedback show",
8333
+ summary: "Show one feedback issue, its body and its replies",
8334
+ values: FEEDBACK_SHOW_VALUES,
8335
+ booleans: FEEDBACK_SHOW_BOOLEANS,
8336
+ positionals: ["<n>"]
8337
+ },
8338
+ {
8339
+ path: "feedback vote",
8340
+ summary: "Vote for a feedback issue",
8341
+ values: FEEDBACK_VOTE_VALUES,
8342
+ booleans: FEEDBACK_VOTE_BOOLEANS,
8343
+ positionals: ["<n>"]
8344
+ },
8345
+ {
8346
+ path: "feedback comment",
8347
+ summary: "Comment on a feedback issue",
8348
+ values: FEEDBACK_COMMENT_VALUES,
8349
+ booleans: FEEDBACK_COMMENT_BOOLEANS,
8350
+ positionals: ["<n>"]
8351
+ },
8352
+ {
8353
+ path: "feedback list",
8354
+ summary: "List the feedback issues you opened, voted for or commented on",
8355
+ values: FEEDBACK_LIST_VALUES,
8356
+ booleans: FEEDBACK_LIST_BOOLEANS,
8357
+ positionals: []
8358
+ }
8359
+ ];
8360
+ function feedbackEnabled(env = process.env) {
8361
+ return env[FEEDBACK_FLAG] === "1";
8362
+ }
8363
+ function feedbackHelpLines() {
8364
+ if (!feedbackEnabled()) return [];
8365
+ return [" feedback bug | feature | question | show | vote | comment | list"];
8366
+ }
8367
+ var FEEDBACK_MAX_TITLE = 200;
8368
+ var FEEDBACK_MAX_TEXT = 8e3;
8369
+ var FEEDBACK_MAX_INPUT_FILE_BYTES = 1024 * 1024;
8370
+ var FEEDBACK_MAX_FIELDS = 50;
8371
+ var FEEDBACK_KINDS = ["bug", "feature", "question"];
8372
+ var FORM_FIELD_TYPES = ["textarea", "input", "dropdown", "checkboxes"];
8373
+ var FeedbackApiError = class extends Error {
8374
+ status;
8375
+ code;
8376
+ requestId;
8377
+ retryAfterMs;
8378
+ fields;
8379
+ candidates;
8380
+ formsVersion;
8381
+ constructor(init) {
8382
+ super(`the feedback API answered ${init.status} (${init.code})`);
8383
+ this.name = "FeedbackApiError";
8384
+ this.status = init.status;
8385
+ this.code = init.code;
8386
+ this.requestId = init.requestId;
8387
+ this.retryAfterMs = init.retryAfterMs;
8388
+ this.fields = init.fields ?? [];
8389
+ this.candidates = init.candidates ?? [];
8390
+ this.formsVersion = init.formsVersion ?? null;
8298
8391
  }
8299
8392
  };
8300
- var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
8301
- var REFRESH_MARGIN_SECONDS = 30;
8302
- var MIN_EXPIRES_IN = 60;
8303
- var MAX_EXPIRES_IN = 86400;
8304
- var present = (value) => typeof value === "string" && value.length > 0;
8305
- function federationSettingsFromEnv(env = process.env) {
8306
- if (!present(env.NOUTER_PLATFORM_FEDERATION_RULE_ID)) return null;
8307
- if (!present(env.NOUTER_PLATFORM_ORGANIZATION_ID)) {
8308
- throw new FederationError(
8309
- "NOUTER_PLATFORM_ORGANIZATION_ID is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
8310
- );
8311
- }
8312
- const identityToken = identityTokenSourceFromEnv(env);
8313
- if (identityToken === null) {
8314
- throw new IdentityTokenError(
8315
- "NOUTER_PLATFORM_IDENTITY_TOKEN or NOUTER_PLATFORM_IDENTITY_TOKEN_FILE is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
8316
- );
8393
+ function isObject2(value) {
8394
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8395
+ }
8396
+ function parseRetryAfterMs(value) {
8397
+ if (value === null) return null;
8398
+ const seconds = Number(value);
8399
+ return Number.isInteger(seconds) && seconds >= 0 ? seconds * 1e3 : null;
8400
+ }
8401
+ function parseFields(value) {
8402
+ if (!Array.isArray(value)) return [];
8403
+ const fields = [];
8404
+ for (const raw of value) {
8405
+ if (!isObject2(raw)) continue;
8406
+ if (typeof raw.field !== "string" || typeof raw.problem !== "string") continue;
8407
+ fields.push({ field: raw.field, problem: raw.problem });
8408
+ }
8409
+ return fields;
8410
+ }
8411
+ function parseCandidates(value) {
8412
+ if (!Array.isArray(value)) return [];
8413
+ const candidates = [];
8414
+ for (const raw of value) {
8415
+ if (!isObject2(raw)) continue;
8416
+ if (typeof raw.issue !== "number" || typeof raw.title !== "string") continue;
8417
+ if (typeof raw.url !== "string" || typeof raw.state !== "string") continue;
8418
+ candidates.push({ issue: raw.issue, title: raw.title, url: raw.url, state: raw.state });
8419
+ }
8420
+ return candidates;
8421
+ }
8422
+ function parseApiError(status, body, headers) {
8423
+ const root = isObject2(body) ? body : {};
8424
+ const error = isObject2(root.error) ? root.error : {};
8425
+ const details = isObject2(error.details) ? error.details : {};
8426
+ const code = typeof details.error_code === "string" && details.error_code.length > 0 ? details.error_code : typeof error.type === "string" && error.type.length > 0 ? error.type : "unknown_error";
8427
+ const requestId = typeof root.request_id === "string" && root.request_id.length > 0 ? root.request_id : headers.get("request-id") ?? headers.get("x-request-id");
8428
+ const retryAfterMs = typeof error.retry_after_ms === "number" ? error.retry_after_ms : parseRetryAfterMs(headers.get("retry-after"));
8429
+ return new FeedbackApiError({
8430
+ status,
8431
+ code,
8432
+ requestId,
8433
+ retryAfterMs,
8434
+ fields: parseFields(details.fields),
8435
+ candidates: parseCandidates(details.candidates),
8436
+ formsVersion: typeof details.forms_version === "number" ? details.forms_version : null
8437
+ });
8438
+ }
8439
+ function retrySeconds(error) {
8440
+ return error.retryAfterMs === null ? 60 : Math.max(1, Math.ceil(error.retryAfterMs / 1e3));
8441
+ }
8442
+ function describeCode(error) {
8443
+ switch (error.code) {
8444
+ case "person_required":
8445
+ return "This command needs a personal login; run `nouter-platform login`.";
8446
+ case "sensitive_data":
8447
+ return "The text seems to contain customer data, personal data or secrets.";
8448
+ case "daily_limit":
8449
+ return `The daily feedback limit was reached; try again in ${retrySeconds(error)} seconds.`;
8450
+ case "invalid_fields":
8451
+ return "The fields do not match the form.";
8452
+ case "possible_duplicates":
8453
+ return "There are open issues with a similar title.";
8454
+ case "not_found":
8455
+ return "The feedback issue was not found.";
8456
+ case "feedback_timeout":
8457
+ return "The feedback service took too long to answer; try again later.";
8458
+ case "feedback_unavailable":
8459
+ case "github_unavailable":
8460
+ case "review_unavailable":
8461
+ return "Feedback is not available right now; try again later.";
8462
+ default:
8463
+ return `The feedback service answered ${error.status}${error.code === "unknown_error" ? "" : ` (${printable(error.code)})`}; try again later.`;
8317
8464
  }
8318
- return {
8319
- ruleId: env.NOUTER_PLATFORM_FEDERATION_RULE_ID,
8320
- organizationId: env.NOUTER_PLATFORM_ORGANIZATION_ID,
8321
- ...present(env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID) && { serviceAccountId: env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID },
8322
- ...present(env.NOUTER_PLATFORM_WORKSPACE_ID) && { workspaceId: env.NOUTER_PLATFORM_WORKSPACE_ID },
8323
- identityToken
8324
- };
8325
8465
  }
8326
- function parseToken(payload) {
8327
- if (typeof payload !== "object" || payload === null) return null;
8328
- const body = payload;
8329
- if (typeof body.access_token !== "string" || !body.access_token.startsWith("oma_oat_")) return null;
8330
- if (body.token_type !== "Bearer") return null;
8331
- if (typeof body.expires_in !== "number" || !Number.isInteger(body.expires_in) || body.expires_in < MIN_EXPIRES_IN || body.expires_in > MAX_EXPIRES_IN) {
8332
- return null;
8466
+ function describeFeedbackFailure(error) {
8467
+ const suffix = error.requestId === null ? "" : ` (request ${printable(error.requestId)})`;
8468
+ const lines = [`${describeCode(error)}${suffix}`];
8469
+ if (error.code === "invalid_fields") {
8470
+ for (const field of error.fields) lines.push(`${printable(field.field)}: ${printable(field.problem)}`);
8333
8471
  }
8334
- if (typeof body.scope !== "string" || body.scope.trim().length === 0) return null;
8335
- return {
8336
- accessToken: body.access_token,
8337
- expiresIn: body.expires_in,
8338
- scopes: body.scope.split(" ").filter((scope) => scope.length > 0)
8339
- };
8472
+ return lines;
8340
8473
  }
8341
- async function exchange(baseUrl, settings, assertion, fetch, timeoutMs) {
8474
+ function isTimeout(error) {
8475
+ const value = error;
8476
+ return value?.name === "TimeoutError" || value?.name === "AbortError" || value?.cause?.name === "TimeoutError" || value?.cause?.name === "AbortError" || value?.cause?.code === "ABORT_ERR";
8477
+ }
8478
+ function describeNetworkFailure(error) {
8479
+ const value = error;
8480
+ return value?.cause?.code ?? value?.name ?? "network error";
8481
+ }
8482
+ async function feedbackRequest(auth, method, path, body, deps, headers = {}) {
8483
+ const url = `${auth.baseUrl.replace(/\/+$/, "")}${path}`;
8484
+ const requestHeaders = {
8485
+ Accept: "application/json",
8486
+ "User-Agent": deps.userAgent,
8487
+ ...headers
8488
+ };
8489
+ if (auth.transport === "bearer") requestHeaders.Authorization = `Bearer ${auth.credential}`;
8490
+ else requestHeaders["x-api-key"] = auth.credential;
8491
+ const payload = body === void 0 ? void 0 : JSON.stringify(body);
8492
+ if (payload !== void 0) requestHeaders["Content-Type"] = "application/json";
8342
8493
  let response;
8343
8494
  try {
8344
- response = await fetch(`${baseUrl}/v1/oauth/token`, {
8345
- method: "POST",
8346
- headers: { "content-type": "application/json", accept: "application/json" },
8347
- body: JSON.stringify({
8348
- grant_type: GRANT_TYPE,
8349
- assertion,
8350
- federation_rule_id: settings.ruleId,
8351
- organization_id: settings.organizationId,
8352
- ...settings.serviceAccountId !== void 0 && { service_account_id: settings.serviceAccountId },
8353
- ...settings.workspaceId !== void 0 && { workspace_id: settings.workspaceId }
8354
- }),
8355
- signal: AbortSignal.timeout(timeoutMs)
8495
+ response = await deps.fetch(url, {
8496
+ method,
8497
+ headers: requestHeaders,
8498
+ ...payload !== void 0 && { body: payload },
8499
+ redirect: "manual",
8500
+ signal: AbortSignal.timeout(deps.requestTimeoutMs)
8356
8501
  });
8502
+ } catch (error) {
8503
+ if (isTimeout(error)) throw new deps.CliError("The feedback request timed out; try again later.");
8504
+ throw new deps.CliError(
8505
+ `The feedback request could not reach the API (${describeNetworkFailure(error)}); try again later.`
8506
+ );
8507
+ }
8508
+ const notApi = notTheApiMessage(url, response);
8509
+ if (notApi !== null) throw new deps.CliError(printable(notApi));
8510
+ const text = await response.text();
8511
+ let parsed;
8512
+ let invalid = false;
8513
+ try {
8514
+ parsed = text === "" ? void 0 : JSON.parse(text);
8357
8515
  } catch {
8358
- throw new FederationError("The federation exchange failed (network error).");
8516
+ invalid = true;
8359
8517
  }
8360
- if (response.status === 401) {
8361
- throw new FederationError("Authentication failed");
8518
+ if (!response.ok) throw parseApiError(response.status, invalid ? void 0 : parsed, response.headers);
8519
+ if (invalid) throw new deps.CliError("The feedback service answered with something that is not JSON.");
8520
+ return parsed;
8521
+ }
8522
+ function parseFormFields(value) {
8523
+ if (!Array.isArray(value)) return null;
8524
+ const fields = [];
8525
+ for (const raw of value) {
8526
+ if (!isObject2(raw)) return null;
8527
+ if (typeof raw.id !== "string" || typeof raw.label !== "string" || typeof raw.required !== "boolean") {
8528
+ return null;
8529
+ }
8530
+ if (!FORM_FIELD_TYPES.includes(raw.type)) return null;
8531
+ const field = {
8532
+ id: printable(raw.id),
8533
+ type: raw.type,
8534
+ label: printable(raw.label),
8535
+ required: raw.required
8536
+ };
8537
+ if (Array.isArray(raw.options) && raw.options.every((option) => typeof option === "string")) {
8538
+ field.options = raw.options.map((option) => printable(option));
8539
+ }
8540
+ if (typeof raw.maxLength === "number") field.maxLength = raw.maxLength;
8541
+ fields.push(field);
8362
8542
  }
8363
- if (!response.ok) {
8364
- throw new FederationError(`The federation exchange failed (the server answered ${response.status}).`);
8543
+ return fields;
8544
+ }
8545
+ async function loadForms(auth, deps) {
8546
+ const body = await feedbackRequest(auth, "GET", "/v1/feedback/forms", void 0, deps);
8547
+ if (!isObject2(body)) throw new deps.CliError("The feedback service returned forms in an unexpected shape.");
8548
+ const version = body.version;
8549
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {
8550
+ throw new deps.CliError("The feedback service returned forms without a version.");
8551
+ }
8552
+ const rawForms = body.forms;
8553
+ if (!isObject2(rawForms)) throw new deps.CliError("The feedback service returned forms without fields.");
8554
+ const forms = {};
8555
+ for (const kind of FEEDBACK_KINDS) {
8556
+ const raw = rawForms[kind];
8557
+ if (!isObject2(raw) || typeof raw.name !== "string") {
8558
+ throw new deps.CliError(`The feedback service returned a broken "${kind}" form.`);
8559
+ }
8560
+ const fields = parseFormFields(raw.fields);
8561
+ if (fields === null) {
8562
+ throw new deps.CliError(`The feedback service returned the "${kind}" form without fields.`);
8563
+ }
8564
+ forms[kind] = { name: raw.name, fields };
8565
+ }
8566
+ return { version, forms };
8567
+ }
8568
+ function parseFeedbackOptions(args, values, booleans, CliError2) {
8569
+ const parsed = { values: /* @__PURE__ */ new Map(), booleans: /* @__PURE__ */ new Set(), positionals: [] };
8570
+ for (let index = 0; index < args.length; index += 1) {
8571
+ const argument = args[index];
8572
+ if (!argument.startsWith("--")) {
8573
+ parsed.positionals.push(argument);
8574
+ continue;
8575
+ }
8576
+ const equals = argument.indexOf("=");
8577
+ const name = equals === -1 ? argument : argument.slice(0, equals);
8578
+ const inline = equals === -1 ? void 0 : argument.slice(equals + 1);
8579
+ if (booleans.includes(name)) {
8580
+ if (inline !== void 0) throw new CliError2(`The option ${name} takes no value.`);
8581
+ parsed.booleans.add(name);
8582
+ continue;
8583
+ }
8584
+ if (!values.includes(name)) throw new CliError2(`Unknown option: ${name}.`);
8585
+ const value = inline ?? args[index + 1];
8586
+ if (value === void 0) throw new CliError2(`The option ${name} needs a value.`);
8587
+ if (inline === void 0) index += 1;
8588
+ const list = parsed.values.get(name) ?? [];
8589
+ list.push(value);
8590
+ parsed.values.set(name, list);
8365
8591
  }
8366
- let payload;
8592
+ return parsed;
8593
+ }
8594
+ function lastValue(options, name) {
8595
+ return options.values.get(name)?.at(-1);
8596
+ }
8597
+ var NOTE_JSON_NEEDS_YES = "--json needs --yes: without a terminal, the report cannot be confirmed.";
8598
+ function parseFieldFlags(values, deps) {
8599
+ const fields = {};
8600
+ for (const raw of values) {
8601
+ const equals = raw.indexOf("=");
8602
+ if (equals <= 0) throw new deps.CliError(`--field expects id=value (got "${printable(raw)}").`);
8603
+ fields[raw.slice(0, equals)] = raw.slice(equals + 1);
8604
+ }
8605
+ return fields;
8606
+ }
8607
+ function readSmallInputFile(path, label2, deps) {
8608
+ let fd;
8367
8609
  try {
8368
- payload = await response.json();
8610
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
8369
8611
  } catch {
8370
- throw new FederationError("The federation exchange returned an unexpected response.");
8612
+ throw new deps.CliError(`Could not read the ${label2} ${printable(path)}.`);
8371
8613
  }
8372
- const token = parseToken(payload);
8373
- if (token === null) throw new FederationError("The federation exchange returned an unexpected response.");
8374
- return token;
8375
- }
8376
- function createFederationTokenProvider(options) {
8377
- const now = options.now ?? Date.now;
8378
- const reader = createIdentityTokenReader(options.settings.identityToken, options.readFile);
8379
- let cached = null;
8380
- return {
8381
- async getToken() {
8382
- const assertion = reader.read();
8383
- const current = now();
8384
- if (cached !== null && cached.assertion === assertion && current < cached.refreshAt) {
8385
- return cached.token;
8614
+ try {
8615
+ if (!fstatSync(fd).isFile()) {
8616
+ throw new deps.CliError(`The ${label2} is not a regular file.`);
8617
+ }
8618
+ const buffer = Buffer.alloc(FEEDBACK_MAX_INPUT_FILE_BYTES + 1);
8619
+ let total = 0;
8620
+ for (; ; ) {
8621
+ const read = readSync(fd, buffer, total, buffer.length - total, null);
8622
+ if (read === 0) break;
8623
+ total += read;
8624
+ if (total > FEEDBACK_MAX_INPUT_FILE_BYTES) {
8625
+ throw new deps.CliError(`The ${label2} is larger than 1 MiB.`);
8386
8626
  }
8387
- const token = await exchange(options.baseUrl, options.settings, assertion, options.fetch, options.timeoutMs);
8388
- cached = {
8389
- token,
8390
- assertion,
8391
- refreshAt: current + Math.max(token.expiresIn - REFRESH_MARGIN_SECONDS, 0) * 1e3
8392
- };
8393
- return token;
8394
8627
  }
8395
- };
8396
- }
8397
-
8398
- // src/login-callback.ts
8399
- import { timingSafeEqual } from "node:crypto";
8400
- import { createServer } from "node:http";
8401
- var LOGIN_CALLBACK_TIMEOUT_MS = 5 * 60 * 1e3;
8402
- var MAX_BODY_BYTES = 16 * 1024;
8403
- var LoginAccessDeniedError = class extends Error {
8404
- constructor() {
8405
- super("The login was canceled (access_denied).");
8406
- this.name = "LoginAccessDeniedError";
8628
+ return buffer.subarray(0, total).toString("utf8");
8629
+ } catch (error) {
8630
+ if (error instanceof deps.CliError) throw error;
8631
+ throw new deps.CliError(`Could not read the ${label2} ${printable(path)}.`);
8632
+ } finally {
8633
+ closeSync(fd);
8407
8634
  }
8408
- };
8409
- var LoginCallbackTimeoutError = class extends Error {
8410
- constructor() {
8411
- super("The login timed out after five minutes.");
8412
- this.name = "LoginCallbackTimeoutError";
8635
+ }
8636
+ function readFieldsFile(path, deps) {
8637
+ const text = readSmallInputFile(path, "--fields file", deps);
8638
+ let parsed;
8639
+ try {
8640
+ parsed = JSON.parse(text);
8641
+ } catch {
8642
+ try {
8643
+ parsed = (0, import_yaml2.parse)(text);
8644
+ } catch {
8645
+ throw new deps.CliError("The --fields file is not valid JSON or YAML.");
8646
+ }
8413
8647
  }
8414
- };
8415
- function startLoginCallback(options) {
8416
- const timeoutMs = options.timeoutMs ?? LOGIN_CALLBACK_TIMEOUT_MS;
8417
- let settled = false;
8418
- let timer;
8419
- let resolveResult = () => {
8420
- };
8421
- let rejectResult = () => {
8422
- };
8423
- const result = new Promise((resolve, reject) => {
8424
- resolveResult = resolve;
8425
- rejectResult = reject;
8426
- });
8427
- result.catch(() => {
8428
- });
8429
- const server = createServer((request, response) => {
8430
- void handleRequest(request, response).catch(() => {
8431
- sendHtml(response, 500, "The login callback could not read the request.");
8432
- });
8433
- });
8434
- function stateMatches(given) {
8435
- if (given === null) return false;
8436
- const expected = Buffer.from(options.state, "utf8");
8437
- const received = Buffer.from(given, "utf8");
8438
- return received.length === expected.length && timingSafeEqual(received, expected);
8648
+ if (!isObject2(parsed)) throw new deps.CliError("The --fields file must be an object of field ids.");
8649
+ const fields = {};
8650
+ for (const [id, value] of Object.entries(parsed)) {
8651
+ if (typeof value !== "string" && typeof value !== "boolean") {
8652
+ throw new deps.CliError(`The --fields file has a non-text value for ${printable(id)}.`);
8653
+ }
8654
+ fields[id] = value;
8439
8655
  }
8440
- const finish = (action) => {
8441
- if (settled) return false;
8442
- settled = true;
8443
- if (timer) clearTimeout(timer);
8444
- action();
8445
- if (server.listening) server.close();
8446
- return true;
8447
- };
8448
- async function handleRequest(request, response) {
8449
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
8450
- if (url.pathname !== "/callback") {
8451
- sendHtml(response, 404, "Not found.");
8452
- return;
8656
+ return fields;
8657
+ }
8658
+ function isChecked(value) {
8659
+ return typeof value === "boolean" ? value : /^(true|yes|y|1)$/i.test(value.trim());
8660
+ }
8661
+ function validateFields(form, provided, deps) {
8662
+ const known = new Set(form.fields.map((field) => field.id));
8663
+ for (const id of Object.keys(provided)) {
8664
+ if (!known.has(id)) throw new deps.CliError(`Unknown field: ${printable(id)}.`);
8665
+ }
8666
+ if (Object.keys(provided).length > FEEDBACK_MAX_FIELDS) {
8667
+ throw new deps.CliError(`At most ${FEEDBACK_MAX_FIELDS} fields can be sent.`);
8668
+ }
8669
+ const fields = {};
8670
+ for (const field of form.fields) {
8671
+ const raw = provided[field.id];
8672
+ if (raw === void 0) {
8673
+ if (field.required) throw new deps.CliError(`Missing required field: ${field.id}.`);
8674
+ if (field.type === "checkboxes") throw new deps.CliError(`The field ${field.id} must be checked.`);
8675
+ continue;
8453
8676
  }
8454
- if (request.method === "POST") {
8455
- const contentType = request.headers["content-type"] ?? "";
8456
- if (!contentType.toLowerCase().startsWith("application/x-www-form-urlencoded")) {
8457
- sendHtml(response, 415, "The callback only accepts an application/x-www-form-urlencoded form.");
8458
- return;
8459
- }
8460
- const body = await readBody(request);
8461
- const form = new URLSearchParams(body);
8462
- if (!stateMatches(form.get("state"))) {
8463
- sendHtml(response, 400, "Invalid state.");
8464
- return;
8465
- }
8466
- if (form.get("error") === "access_denied") {
8467
- if (finish(() => rejectResult(new LoginAccessDeniedError()))) {
8468
- sendHtml(response, 200, "Login canceled. You can close this window.");
8469
- } else {
8470
- sendHtml(response, 409, "The login callback was already used.");
8471
- }
8472
- return;
8473
- }
8474
- const token = form.get("token");
8475
- if (!token) {
8476
- sendHtml(response, 400, "Missing token.");
8477
- return;
8478
- }
8479
- const delivered = {
8480
- token,
8481
- keyId: form.get("key_id"),
8482
- tenantId: form.get("tenant_id"),
8483
- tenantName: form.get("tenant_name"),
8484
- role: form.get("role")
8485
- };
8486
- if (finish(() => resolveResult(delivered))) {
8487
- sendHtml(response, 200, "Login approved. You can close this window.");
8488
- } else {
8489
- sendHtml(response, 409, "The login callback was already used.");
8677
+ if (field.type === "checkboxes") {
8678
+ if (!isChecked(raw)) {
8679
+ throw new deps.CliError(
8680
+ field.required ? `Missing required field: ${field.id}.` : `The field ${field.id} must be checked.`
8681
+ );
8490
8682
  }
8491
- return;
8683
+ fields[field.id] = true;
8684
+ continue;
8492
8685
  }
8493
- if (request.method === "GET") {
8494
- sendHtml(response, 400, "The callback accepts the login result only as a POST form.");
8495
- return;
8686
+ if (typeof raw !== "string") throw new deps.CliError(`The field ${field.id} must be text.`);
8687
+ if (field.required && raw.trim() === "") throw new deps.CliError(`Missing required field: ${field.id}.`);
8688
+ if (field.type === "dropdown" && field.options !== void 0 && !field.options.includes(raw)) {
8689
+ throw new deps.CliError(
8690
+ `Invalid value for ${printable(field.id)}: "${printable(raw)}". Allowed: ${field.options.join(", ")}.`
8691
+ );
8496
8692
  }
8497
- sendHtml(response, 405, "Method not allowed.");
8693
+ const maxLength = field.maxLength ?? FEEDBACK_MAX_TEXT;
8694
+ if (raw.length > maxLength) {
8695
+ throw new deps.CliError(`The value of ${field.id} must be at most ${maxLength} characters.`);
8696
+ }
8697
+ fields[field.id] = raw;
8498
8698
  }
8499
- timer = setTimeout(() => {
8500
- finish(() => rejectResult(new LoginCallbackTimeoutError()));
8501
- }, timeoutMs);
8502
- timer.unref?.();
8503
- return new Promise((resolveServer, rejectServer) => {
8504
- server.on("error", (error) => {
8505
- settled = true;
8506
- if (timer) clearTimeout(timer);
8507
- rejectServer(error);
8508
- });
8509
- server.listen(0, "127.0.0.1", () => {
8510
- const address = server.address();
8511
- if (!address || typeof address === "string") {
8512
- rejectServer(new Error("The login callback did not bind a TCP port."));
8513
- return;
8514
- }
8515
- resolveServer({
8516
- callbackUrl: `http://127.0.0.1:${address.port}/callback`,
8517
- waitForResult: () => result,
8518
- close: () => new Promise((resolveClose) => {
8519
- settled = true;
8520
- if (timer) clearTimeout(timer);
8521
- if (!server.listening) {
8522
- resolveClose();
8523
- return;
8524
- }
8525
- server.close(() => resolveClose());
8526
- server.closeAllConnections?.();
8527
- })
8699
+ return fields;
8700
+ }
8701
+ async function promptLine(question) {
8702
+ const readline = createInterface({ input: process.stdin, output: process.stdout });
8703
+ try {
8704
+ return /^y(es)?$/i.test((await readline.question(question)).trim());
8705
+ } finally {
8706
+ readline.close();
8707
+ }
8708
+ }
8709
+ function printCreatePreview(kind, title, form, fields, deps) {
8710
+ deps.writeStdout(`${kind}: ${printable(title)}`);
8711
+ for (const field of form.fields) {
8712
+ const value = fields[field.id];
8713
+ if (value === void 0) continue;
8714
+ deps.writeStdout(
8715
+ value === true ? ` [x] ${field.label}` : ` ${field.label}: ${printable(value)}`
8716
+ );
8717
+ }
8718
+ }
8719
+ function printFeedbackError(error, deps) {
8720
+ for (const line of describeFeedbackFailure(error)) deps.writeStderr(line);
8721
+ if (error.code === "invalid_fields" && error.formsVersion !== null) {
8722
+ deps.writeStderr(
8723
+ `The forms changed (version ${error.formsVersion}); run the command again with the new form.`
8724
+ );
8725
+ }
8726
+ }
8727
+ function printCreateResult(body, options, deps) {
8728
+ if (options.booleans.has("--json")) {
8729
+ deps.writeStdout(JSON.stringify(body, null, 2));
8730
+ return 0;
8731
+ }
8732
+ if (isObject2(body) && body.dryRun === true && isObject2(body.wouldCreate)) {
8733
+ deps.writeStdout("Dry run: the issue would be created with:");
8734
+ deps.writeStdout(` Title: ${printable(String(body.wouldCreate.title ?? ""))}`);
8735
+ if (Array.isArray(body.wouldCreate.labels)) {
8736
+ deps.writeStdout(` Labels: ${printable(body.wouldCreate.labels.join(", "))}`);
8737
+ }
8738
+ deps.writeStdout(` Body:
8739
+ ${printable(String(body.wouldCreate.body ?? ""))}`);
8740
+ return 0;
8741
+ }
8742
+ if (!isObject2(body)) throw new deps.CliError("The feedback service returned an unexpected answer.");
8743
+ const issue = typeof body.issue === "number" ? body.issue : "?";
8744
+ const url = typeof body.url === "string" ? printable(body.url) : "";
8745
+ deps.writeStdout(`Opened issue #${issue}${url ? `: ${url}` : ""}`);
8746
+ return 0;
8747
+ }
8748
+ async function handleDuplicates(error, options, resend, deps) {
8749
+ if (options.booleans.has("--json")) {
8750
+ const body = { error: "possible_duplicates", requestId: error.requestId, candidates: error.candidates };
8751
+ deps.writeStdout(JSON.stringify(body, null, 2));
8752
+ return 1;
8753
+ }
8754
+ if (error.candidates.length === 0) deps.writeStdout("Possible duplicates were reported, but none were listed.");
8755
+ for (const candidate of error.candidates) {
8756
+ deps.writeStdout(
8757
+ `#${candidate.issue} ${printable(candidate.title)} (${printable(candidate.state)}) ${printable(candidate.url)}`
8758
+ );
8759
+ }
8760
+ if (options.booleans.has("--confirm-duplicate")) return resend();
8761
+ if (process.stdin.isTTY === true) {
8762
+ if (await promptLine("Open a new issue anyway? [y/N] ")) return resend();
8763
+ deps.writeStdout("Nothing was sent. Vote for an existing issue with `nouter-platform feedback vote <n>`.");
8764
+ return 0;
8765
+ }
8766
+ deps.writeStderr(
8767
+ "Possible duplicates were found. Re-run with --confirm-duplicate to open a new issue anyway."
8768
+ );
8769
+ return 1;
8770
+ }
8771
+ async function feedbackCreate(kind, argv, deps) {
8772
+ const options = parseFeedbackOptions(argv, FEEDBACK_CREATE_VALUES, FEEDBACK_CREATE_BOOLEANS, deps.CliError);
8773
+ if (options.positionals.length > 0) {
8774
+ throw new deps.CliError(`Usage: nouter-platform feedback ${kind} --title <title> [--field id=value]...`);
8775
+ }
8776
+ const title = (lastValue(options, "--title") ?? "").trim();
8777
+ if (title.length === 0) throw new deps.CliError("The option --title is required.");
8778
+ if (title.length > FEEDBACK_MAX_TITLE) {
8779
+ throw new deps.CliError(`The title must be at most ${FEEDBACK_MAX_TITLE} characters.`);
8780
+ }
8781
+ if (options.booleans.has("--json") && !options.booleans.has("--yes")) {
8782
+ throw new deps.CliError(NOTE_JSON_NEEDS_YES);
8783
+ }
8784
+ const fileFields = options.values.has("--fields") ? readFieldsFile(lastValue(options, "--fields"), deps) : {};
8785
+ const provided = {
8786
+ ...fileFields,
8787
+ ...parseFieldFlags(options.values.get("--field") ?? [], deps)
8788
+ };
8789
+ const auth = await deps.resolveAuth();
8790
+ let forms;
8791
+ try {
8792
+ forms = await loadForms(auth, deps);
8793
+ } catch (error) {
8794
+ if (!(error instanceof FeedbackApiError)) throw error;
8795
+ printFeedbackError(error, deps);
8796
+ return 1;
8797
+ }
8798
+ const form = forms.forms[kind];
8799
+ const fields = validateFields(form, provided, deps);
8800
+ if (!options.booleans.has("--yes")) {
8801
+ if (process.stdin.isTTY !== true) {
8802
+ deps.writeStdout("Nothing was sent: run the command in a terminal or pass --yes.");
8803
+ return 0;
8804
+ }
8805
+ printCreatePreview(kind, title, form, fields, deps);
8806
+ if (!await promptLine("Send this report? [y/N] ")) {
8807
+ deps.writeStdout("Nothing was sent.");
8808
+ return 0;
8809
+ }
8810
+ }
8811
+ const send = async (confirmDuplicateCheck) => {
8812
+ const body = { kind, title, fields, formsVersion: forms.version, confirmDuplicateCheck };
8813
+ try {
8814
+ const result = await feedbackRequest(auth, "POST", "/v1/feedback", body, deps, {
8815
+ "Idempotency-Key": randomUUID()
8528
8816
  });
8529
- });
8530
- });
8817
+ return printCreateResult(result, options, deps);
8818
+ } catch (error) {
8819
+ if (!(error instanceof FeedbackApiError)) throw error;
8820
+ if (error.code === "possible_duplicates" && !confirmDuplicateCheck) {
8821
+ return handleDuplicates(error, options, () => send(true), deps);
8822
+ }
8823
+ printFeedbackError(error, deps);
8824
+ return 1;
8825
+ }
8826
+ };
8827
+ return send(false);
8531
8828
  }
8532
- function sendHtml(response, status, message) {
8533
- response.writeHead(status, {
8534
- "content-type": "text/html; charset=utf-8",
8535
- "cache-control": "no-store",
8536
- "referrer-policy": "no-referrer",
8537
- connection: "close"
8538
- });
8539
- response.end(`<!doctype html><meta charset="utf-8"><title>Nouter platform login</title><p>${message}</p>`);
8829
+ function parseIssueArgument(raw, deps) {
8830
+ if (raw === void 0 || !/^\d{1,10}$/.test(raw)) {
8831
+ throw new deps.CliError("The issue number must be a positive integer.");
8832
+ }
8833
+ const issue = Number(raw);
8834
+ if (!Number.isInteger(issue) || issue < 1) throw new deps.CliError("The issue number must be a positive integer.");
8835
+ return issue;
8540
8836
  }
8541
- async function readBody(request) {
8542
- let body = "";
8543
- for await (const chunk of request) {
8544
- body += String(chunk);
8545
- if (body.length > MAX_BODY_BYTES) {
8546
- throw new Error("The login callback body is too large.");
8837
+ function stringArray(value) {
8838
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
8839
+ }
8840
+ function parseThread(body, deps) {
8841
+ if (!isObject2(body) || typeof body.issue !== "number" || typeof body.title !== "string" || typeof body.body !== "string") {
8842
+ throw new deps.CliError("The feedback service returned an unexpected thread.");
8843
+ }
8844
+ const comments = Array.isArray(body.comments) ? body.comments.filter(isObject2).map((raw) => ({
8845
+ author: typeof raw.author === "string" ? raw.author : "",
8846
+ role: typeof raw.role === "string" ? raw.role : "community",
8847
+ body: typeof raw.body === "string" ? raw.body : "",
8848
+ createdAt: typeof raw.createdAt === "string" ? raw.createdAt : "",
8849
+ url: typeof raw.url === "string" ? raw.url : ""
8850
+ })) : [];
8851
+ return {
8852
+ issue: body.issue,
8853
+ title: body.title,
8854
+ url: typeof body.url === "string" ? body.url : "",
8855
+ state: typeof body.state === "string" ? body.state : "",
8856
+ labels: stringArray(body.labels),
8857
+ toolVotes: typeof body.toolVotes === "number" ? body.toolVotes : 0,
8858
+ body: body.body,
8859
+ comments,
8860
+ lastCommentAt: typeof body.lastCommentAt === "string" ? body.lastCommentAt : null
8861
+ };
8862
+ }
8863
+ function parseMine(body, deps) {
8864
+ if (!isObject2(body) || !Array.isArray(body.items)) {
8865
+ throw new deps.CliError("The feedback service returned an unexpected list.");
8866
+ }
8867
+ const items = body.items.filter(isObject2).map((raw) => ({
8868
+ issue: typeof raw.issue === "number" ? raw.issue : 0,
8869
+ title: typeof raw.title === "string" ? raw.title : "",
8870
+ url: typeof raw.url === "string" ? raw.url : "",
8871
+ state: typeof raw.state === "string" ? raw.state : "",
8872
+ labels: stringArray(raw.labels),
8873
+ comments: typeof raw.comments === "number" ? raw.comments : 0,
8874
+ lastCommentAt: typeof raw.lastCommentAt === "string" ? raw.lastCommentAt : null,
8875
+ mine: typeof raw.mine === "string" ? raw.mine : ""
8876
+ }));
8877
+ return { items, nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null };
8878
+ }
8879
+ function formatThread(thread) {
8880
+ const lines = [
8881
+ `#${thread.issue} ${printable(thread.title)} (${printable(thread.state)})`,
8882
+ printable(thread.url),
8883
+ `Labels: ${thread.labels.length > 0 ? printable(thread.labels.join(", ")) : "(none)"}`,
8884
+ `Tool votes: ${thread.toolVotes}`,
8885
+ "",
8886
+ printable(thread.body)
8887
+ ];
8888
+ if (thread.comments.length > 0) {
8889
+ lines.push("", "Comments:");
8890
+ for (const comment of thread.comments) {
8891
+ lines.push(`[${printable(comment.role)}] ${printable(comment.author)}: ${printable(comment.body)}`);
8547
8892
  }
8548
8893
  }
8549
- return body;
8894
+ return lines;
8895
+ }
8896
+ function formatMine(mine) {
8897
+ if (mine.items.length === 0) return ["No feedback issues."];
8898
+ const lines = [];
8899
+ for (const item of mine.items) {
8900
+ lines.push(`#${item.issue} ${printable(item.title)} (${printable(item.state)}, ${printable(item.mine)})`);
8901
+ lines.push(` ${printable(item.url)}`);
8902
+ const lastComment = item.lastCommentAt === null ? "none" : printable(item.lastCommentAt);
8903
+ lines.push(` comments: ${item.comments}, last comment: ${lastComment}`);
8904
+ }
8905
+ return lines;
8906
+ }
8907
+ async function feedbackShow(argv, deps) {
8908
+ const options = parseFeedbackOptions(argv, FEEDBACK_SHOW_VALUES, FEEDBACK_SHOW_BOOLEANS, deps.CliError);
8909
+ if (options.positionals.length !== 1) throw new deps.CliError("Usage: nouter-platform feedback show <n>");
8910
+ const issue = parseIssueArgument(options.positionals[0], deps);
8911
+ const auth = await deps.resolveAuth();
8912
+ try {
8913
+ const body = await feedbackRequest(auth, "GET", `/v1/feedback/issues/${issue}`, void 0, deps);
8914
+ if (options.booleans.has("--json")) {
8915
+ deps.writeStdout(JSON.stringify(body, null, 2));
8916
+ return 0;
8917
+ }
8918
+ for (const line of formatThread(parseThread(body, deps))) deps.writeStdout(line);
8919
+ return 0;
8920
+ } catch (error) {
8921
+ if (error instanceof FeedbackApiError) {
8922
+ printFeedbackError(error, deps);
8923
+ return 1;
8924
+ }
8925
+ throw error;
8926
+ }
8927
+ }
8928
+ async function feedbackList(argv, deps) {
8929
+ const options = parseFeedbackOptions(argv, FEEDBACK_LIST_VALUES, FEEDBACK_LIST_BOOLEANS, deps.CliError);
8930
+ if (options.positionals.length > 0) {
8931
+ throw new deps.CliError("Usage: nouter-platform feedback list [--cursor <offset>] [--json]");
8932
+ }
8933
+ const cursor = lastValue(options, "--cursor");
8934
+ if (cursor !== void 0 && !/^\d{1,10}$/.test(cursor)) {
8935
+ throw new deps.CliError("The cursor must be a number of up to 10 digits.");
8936
+ }
8937
+ const auth = await deps.resolveAuth();
8938
+ const query = cursor === void 0 ? "" : `?${new URLSearchParams({ cursor }).toString()}`;
8939
+ try {
8940
+ const body = await feedbackRequest(auth, "GET", `/v1/feedback/mine${query}`, void 0, deps);
8941
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(body, null, 2));
8942
+ else for (const line of formatMine(parseMine(body, deps))) deps.writeStdout(line);
8943
+ const nextCursor = isObject2(body) && typeof body.nextCursor === "string" ? body.nextCursor : null;
8944
+ if (nextCursor !== null) {
8945
+ deps.writeStderr(`There are more issues: run with --cursor ${printable(nextCursor)}.`);
8946
+ }
8947
+ return 0;
8948
+ } catch (error) {
8949
+ if (error instanceof FeedbackApiError) {
8950
+ printFeedbackError(error, deps);
8951
+ return 1;
8952
+ }
8953
+ throw error;
8954
+ }
8955
+ }
8956
+ function parseVoteResult(body, deps) {
8957
+ if (!isObject2(body) || typeof body.issue !== "number") {
8958
+ throw new deps.CliError("The feedback service returned an unexpected vote.");
8959
+ }
8960
+ return {
8961
+ issue: body.issue,
8962
+ voted: body.voted === true,
8963
+ alreadyVoted: body.alreadyVoted === true,
8964
+ toolVotes: typeof body.toolVotes === "number" ? body.toolVotes : 0
8965
+ };
8966
+ }
8967
+ function parseCommentResult(body, deps) {
8968
+ if (!isObject2(body) || typeof body.issue !== "number" || typeof body.commentUrl !== "string") {
8969
+ throw new deps.CliError("The feedback service returned an unexpected comment.");
8970
+ }
8971
+ return {
8972
+ issue: body.issue,
8973
+ commentUrl: body.commentUrl,
8974
+ ref: typeof body.ref === "string" ? body.ref : ""
8975
+ };
8976
+ }
8977
+ function readBodyFile(path, deps) {
8978
+ return readSmallInputFile(path, "--body-file", deps);
8979
+ }
8980
+ async function feedbackVote(argv, deps) {
8981
+ const options = parseFeedbackOptions(argv, FEEDBACK_VOTE_VALUES, FEEDBACK_VOTE_BOOLEANS, deps.CliError);
8982
+ if (options.positionals.length !== 1) throw new deps.CliError("Usage: nouter-platform feedback vote <n>");
8983
+ const issue = parseIssueArgument(options.positionals[0], deps);
8984
+ const auth = await deps.resolveAuth();
8985
+ try {
8986
+ const body = await feedbackRequest(auth, "POST", "/v1/feedback/votes", { issue }, deps, {
8987
+ "Idempotency-Key": randomUUID()
8988
+ });
8989
+ if (isObject2(body) && body.dryRun === true) {
8990
+ deps.writeStdout("Dry run: the vote was not recorded.");
8991
+ return 0;
8992
+ }
8993
+ const result = parseVoteResult(body, deps);
8994
+ const verb = result.alreadyVoted ? "Already voted on" : "Voted on";
8995
+ deps.writeStdout(`${verb} #${result.issue} (${result.toolVotes} votes).`);
8996
+ return 0;
8997
+ } catch (error) {
8998
+ if (error instanceof FeedbackApiError) {
8999
+ printFeedbackError(error, deps);
9000
+ return 1;
9001
+ }
9002
+ throw error;
9003
+ }
9004
+ }
9005
+ async function feedbackComment(argv, deps) {
9006
+ const options = parseFeedbackOptions(argv, FEEDBACK_COMMENT_VALUES, FEEDBACK_COMMENT_BOOLEANS, deps.CliError);
9007
+ if (options.positionals.length !== 1) {
9008
+ throw new deps.CliError("Usage: nouter-platform feedback comment <n> --body <text>|--body-file <path>");
9009
+ }
9010
+ const issue = parseIssueArgument(options.positionals[0], deps);
9011
+ const inline = lastValue(options, "--body");
9012
+ const file = lastValue(options, "--body-file");
9013
+ if (inline !== void 0 && file !== void 0) {
9014
+ throw new deps.CliError("Use either --body or --body-file, not both.");
9015
+ }
9016
+ if (inline === void 0 && file === void 0) {
9017
+ throw new deps.CliError("A comment needs --body <text> or --body-file <path>.");
9018
+ }
9019
+ const text = inline ?? readBodyFile(file, deps);
9020
+ if (text.trim() === "") throw new deps.CliError("The comment cannot be empty.");
9021
+ if (text.length > FEEDBACK_MAX_TEXT) {
9022
+ throw new deps.CliError(`The comment must be at most ${FEEDBACK_MAX_TEXT} characters.`);
9023
+ }
9024
+ const auth = await deps.resolveAuth();
9025
+ try {
9026
+ const body = await feedbackRequest(auth, "POST", "/v1/feedback/comments", { issue, body: text }, deps, {
9027
+ "Idempotency-Key": randomUUID()
9028
+ });
9029
+ if (isObject2(body) && body.dryRun === true) {
9030
+ deps.writeStdout("Dry run: the comment was not posted.");
9031
+ return 0;
9032
+ }
9033
+ const result = parseCommentResult(body, deps);
9034
+ deps.writeStdout(`Comment added: ${printable(result.commentUrl)}`);
9035
+ return 0;
9036
+ } catch (error) {
9037
+ if (error instanceof FeedbackApiError) {
9038
+ printFeedbackError(error, deps);
9039
+ return 1;
9040
+ }
9041
+ throw error;
9042
+ }
9043
+ }
9044
+ async function feedbackCommand(argv, deps) {
9045
+ if (!feedbackEnabled()) {
9046
+ deps.writeStderr(FEEDBACK_DISABLED_MESSAGE);
9047
+ return 1;
9048
+ }
9049
+ const [subcommand, ...rest] = argv;
9050
+ switch (subcommand) {
9051
+ case "bug":
9052
+ case "feature":
9053
+ case "question":
9054
+ return await feedbackCreate(subcommand, rest, deps);
9055
+ case "show":
9056
+ return await feedbackShow(rest, deps);
9057
+ case "list":
9058
+ return await feedbackList(rest, deps);
9059
+ case "vote":
9060
+ return await feedbackVote(rest, deps);
9061
+ case "comment":
9062
+ return await feedbackComment(rest, deps);
9063
+ default:
9064
+ deps.writeStderr("Usage: nouter-platform feedback bug|feature|question|show|vote|comment|list");
9065
+ return 1;
9066
+ }
8550
9067
  }
8551
9068
 
8552
- // src/index.ts
8553
- var USER_AGENT = "NouterPlatform-CLI/0.1";
8554
- var REQUEST_TIMEOUT_MS = 3e4;
9069
+ // src/commands.ts
9070
+ var COMMANDS = [
9071
+ {
9072
+ path: "login",
9073
+ summary: "Log in through the browser or a pasted code, or store an API key from stdin",
9074
+ values: [],
9075
+ booleans: ["--api-key", "--browser", "--paste"],
9076
+ positionals: []
9077
+ },
9078
+ {
9079
+ path: "logout",
9080
+ summary: "Revoke the CLI session and remove the stored credential (--all: every session)",
9081
+ values: [],
9082
+ booleans: ["--all"],
9083
+ positionals: []
9084
+ },
9085
+ {
9086
+ path: "whoami",
9087
+ summary: "Show the organization, the role, the scopes and the session",
9088
+ values: [],
9089
+ booleans: ["--json"],
9090
+ positionals: []
9091
+ },
9092
+ {
9093
+ path: "auth status",
9094
+ summary: "Show which credential the CLI would use, without printing it",
9095
+ values: [],
9096
+ booleans: [],
9097
+ positionals: []
9098
+ },
9099
+ {
9100
+ path: "auth sessions list",
9101
+ summary: "List the CLI sessions of the stored session",
9102
+ values: [],
9103
+ booleans: ["--json"],
9104
+ positionals: []
9105
+ },
9106
+ {
9107
+ path: "auth sessions revoke",
9108
+ summary: "Revoke one of the CLI sessions of this user",
9109
+ values: [],
9110
+ booleans: ["--json"],
9111
+ positionals: ["<session-id>"]
9112
+ },
9113
+ {
9114
+ path: "version",
9115
+ summary: "Show the CLI version and the version of the SDK it ships",
9116
+ values: [],
9117
+ booleans: [],
9118
+ positionals: []
9119
+ },
9120
+ {
9121
+ path: "agents list",
9122
+ summary: "List every agent",
9123
+ values: [],
9124
+ booleans: ["--json"],
9125
+ positionals: []
9126
+ },
9127
+ {
9128
+ path: "agents get",
9129
+ summary: "Show one agent by id",
9130
+ values: [],
9131
+ booleans: [],
9132
+ positionals: ["<agent-id>"]
9133
+ },
9134
+ {
9135
+ path: "environments list",
9136
+ summary: "List every environment",
9137
+ values: [],
9138
+ booleans: ["--json"],
9139
+ positionals: []
9140
+ },
9141
+ {
9142
+ path: "environments get",
9143
+ summary: "Show one environment by id",
9144
+ values: [],
9145
+ booleans: [],
9146
+ positionals: ["<environment-id>"]
9147
+ },
9148
+ {
9149
+ path: "sessions list",
9150
+ summary: "List the sessions, with the filters the API accepts",
9151
+ values: ["--agent", "--agent-version", "--user-profile", "--status", "--since", "--until", "--order"],
9152
+ booleans: ["--include-archived", "--json"],
9153
+ positionals: []
9154
+ },
9155
+ {
9156
+ path: "sessions get",
9157
+ summary: "Show one session by id",
9158
+ values: [],
9159
+ booleans: ["--json"],
9160
+ positionals: ["<session-id>"]
9161
+ },
9162
+ {
9163
+ path: "sessions events",
9164
+ summary: "List the events and the traces of a session",
9165
+ values: ["--type", "--since", "--until", "--order"],
9166
+ booleans: ["--json"],
9167
+ positionals: ["<session-id>"]
9168
+ },
9169
+ {
9170
+ path: "usage",
9171
+ summary: "Show the usage and the cost by day, model, agent, person or session",
9172
+ values: ["--days", "--since", "--until", "--group-by", "--user-profile", "--limit", "--page"],
9173
+ booleans: ["--json"],
9174
+ positionals: []
9175
+ },
9176
+ {
9177
+ path: "service-accounts list",
9178
+ summary: "List the service accounts",
9179
+ values: [],
9180
+ booleans: ["--include-archived", "--json"],
9181
+ positionals: []
9182
+ },
9183
+ {
9184
+ path: "service-accounts create",
9185
+ summary: "Create a service account",
9186
+ values: ["--name", "--organization-role"],
9187
+ booleans: ["--json"],
9188
+ positionals: []
9189
+ },
9190
+ {
9191
+ path: "service-accounts archive",
9192
+ summary: "Archive a service account by id",
9193
+ values: [],
9194
+ booleans: [],
9195
+ positionals: ["<service-account-id>"]
9196
+ },
9197
+ {
9198
+ path: "federation issuers list",
9199
+ summary: "List the federation issuers",
9200
+ values: [],
9201
+ booleans: ["--include-archived", "--json"],
9202
+ positionals: []
9203
+ },
9204
+ {
9205
+ path: "federation issuers create",
9206
+ summary: "Create a federation issuer",
9207
+ values: ["--name", "--provider", "--issuer-url", "--jwks-url", "--check-jti", "--max-token-lifetime"],
9208
+ booleans: ["--json"],
9209
+ positionals: []
9210
+ },
9211
+ {
9212
+ path: "federation issuers archive",
9213
+ summary: "Archive a federation issuer by id",
9214
+ values: [],
9215
+ booleans: [],
9216
+ positionals: ["<issuer-id>"]
9217
+ },
9218
+ {
9219
+ path: "federation rules list",
9220
+ summary: "List the federation rules, optionally by issuer",
9221
+ values: ["--issuer"],
9222
+ booleans: ["--include-archived", "--json"],
9223
+ positionals: []
9224
+ },
9225
+ {
9226
+ path: "federation rules create",
9227
+ summary: "Create a federation rule",
9228
+ values: [
9229
+ "--name",
9230
+ "--issuer",
9231
+ "--service-account",
9232
+ "--subject-prefix",
9233
+ "--audience",
9234
+ "--claim",
9235
+ "--workspace",
9236
+ "--scopes",
9237
+ "--token-lifetime"
9238
+ ],
9239
+ booleans: ["--all-workspaces", "--json"],
9240
+ positionals: []
9241
+ },
9242
+ {
9243
+ path: "federation rules archive",
9244
+ summary: "Archive a federation rule by id",
9245
+ values: [],
9246
+ booleans: [],
9247
+ positionals: ["<rule-id>"]
9248
+ },
9249
+ {
9250
+ path: "federation token",
9251
+ summary: "Exchange the federated identity for a platform access token",
9252
+ values: [],
9253
+ booleans: ["--json"],
9254
+ positionals: []
9255
+ },
9256
+ {
9257
+ path: "elevate",
9258
+ summary: "Confirm it's you for two hours, through the browser or a pasted code",
9259
+ values: [],
9260
+ booleans: ["--browser", "--paste"],
9261
+ positionals: []
9262
+ },
9263
+ {
9264
+ path: "apply",
9265
+ summary: "Apply agents and environments from files",
9266
+ values: ["--file"],
9267
+ booleans: ["--dry-run", "--rotate-secrets"],
9268
+ positionals: [],
9269
+ shortValues: ["-f"]
9270
+ },
9271
+ ...FEEDBACK_COMMANDS
9272
+ ];
9273
+ var BY_PATH = new Map(COMMANDS.map((command) => [command.path, command]));
9274
+ function specFor(path) {
9275
+ const spec = BY_PATH.get(path);
9276
+ if (spec === void 0) throw new Error(`Unknown command path: ${path}`);
9277
+ return spec;
9278
+ }
9279
+
9280
+ // src/config-file.ts
9281
+ import { randomBytes } from "node:crypto";
9282
+ import {
9283
+ chmodSync,
9284
+ closeSync as closeSync2,
9285
+ existsSync,
9286
+ fchmodSync,
9287
+ lstatSync,
9288
+ mkdirSync,
9289
+ openSync as openSync2,
9290
+ readFileSync as readFileSync2,
9291
+ renameSync,
9292
+ statSync as statSync2,
9293
+ unlinkSync,
9294
+ writeSync
9295
+ } from "node:fs";
9296
+ import { homedir } from "node:os";
9297
+ import { join as join2 } from "node:path";
8555
9298
  var CONFIG_DIRECTORY = "nouter-platform";
8556
9299
  var CONFIG_FILE = "config.json";
8557
- var CliError = class extends Error {
8558
- exitCode;
8559
- constructor(message, exitCode = 1) {
9300
+ var CLI_CLIENT_ID = "nouter-platform";
9301
+ var ConfigStorageError = class extends Error {
9302
+ code = "STORAGE_INSECURE";
9303
+ exitCode = 77;
9304
+ constructor(message) {
8560
9305
  super(message);
8561
- this.name = "CliError";
8562
- this.exitCode = exitCode;
9306
+ this.name = "ConfigStorageError";
8563
9307
  }
8564
9308
  };
8565
9309
  function configDirectory() {
@@ -8570,33 +9314,32 @@ function configDirectory() {
8570
9314
  function configPath() {
8571
9315
  return join2(configDirectory(), CONFIG_FILE);
8572
9316
  }
8573
- var warnedAboutLoosePermissions = false;
8574
- function warnAboutLoosePermissions(path, mode, platform, warn) {
8575
- if (platform === "win32" || warnedAboutLoosePermissions) return;
8576
- if ((mode & 63) === 0) return;
8577
- warnedAboutLoosePermissions = true;
8578
- const shown = (mode & 511).toString(8).padStart(3, "0");
8579
- warn(`Warning: the config file ${path} is readable by other users (mode ${shown}); run \`chmod 600 ${path}\`.`);
8580
- }
8581
9317
  function readConfig(options = {}) {
8582
9318
  const platform = options.platform ?? process.platform;
8583
- const warn = options.warn ?? ((message) => process.stderr.write(`${message}
8584
- `));
8585
9319
  const path = configPath();
8586
9320
  if (!existsSync(path)) return null;
8587
- let mode;
8588
- try {
8589
- mode = statSync2(path).mode;
8590
- } catch {
8591
- mode = void 0;
9321
+ if (platform !== "win32") {
9322
+ const mode = statSync2(path).mode;
9323
+ if ((mode & 63) !== 0) {
9324
+ const shown = (mode & 511).toString(8).padStart(3, "0");
9325
+ throw new ConfigStorageError(
9326
+ `The config file ${path} is readable by other users (mode ${shown}); run \`chmod 600 ${path}\` or \`nouter-platform logout\`.`
9327
+ );
9328
+ }
8592
9329
  }
8593
- if (mode !== void 0) warnAboutLoosePermissions(path, mode, platform, warn);
8594
9330
  try {
8595
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
9331
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
8596
9332
  if (typeof parsed.apiKey !== "string" || parsed.apiKey.length === 0) return null;
8597
- const baseUrl = typeof parsed.baseUrl === "string" && parsed.baseUrl.length > 0 ? parsed.baseUrl : null;
8598
- return { baseUrl, apiKey: parsed.apiKey };
8599
- } catch {
9333
+ const loaded = {
9334
+ baseUrl: typeof parsed.baseUrl === "string" && parsed.baseUrl.length > 0 ? parsed.baseUrl : null,
9335
+ apiKey: parsed.apiKey
9336
+ };
9337
+ if (typeof parsed.iss === "string" && parsed.iss.length > 0) loaded.iss = parsed.iss;
9338
+ if (typeof parsed.clientId === "string" && parsed.clientId.length > 0) loaded.clientId = parsed.clientId;
9339
+ if (typeof parsed.sessionId === "string" && parsed.sessionId.length > 0) loaded.sessionId = parsed.sessionId;
9340
+ return loaded;
9341
+ } catch (error) {
9342
+ if (error instanceof ConfigStorageError) throw error;
8600
9343
  return null;
8601
9344
  }
8602
9345
  }
@@ -8609,7 +9352,7 @@ function rejectSymlink(path, what) {
8609
9352
  throw error;
8610
9353
  }
8611
9354
  if (stats.isSymbolicLink()) {
8612
- throw new CliError(`${what} is a symbolic link; refusing to follow it.`);
9355
+ throw new Error(`${what} is a symbolic link; refusing to follow it.`);
8613
9356
  }
8614
9357
  }
8615
9358
  function writeConfig(config) {
@@ -8619,28 +9362,28 @@ function writeConfig(config) {
8619
9362
  try {
8620
9363
  chmodSync(directory, 448);
8621
9364
  } catch {
8622
- throw new CliError(`Could not set the config directory ${directory} to 0700.`);
9365
+ throw new Error(`Could not set the config directory ${directory} to 0700.`);
8623
9366
  }
8624
9367
  const path = configPath();
8625
9368
  rejectSymlink(path, "The config file");
8626
9369
  const temporary = join2(directory, `.config.json.${randomBytes(6).toString("hex")}.tmp`);
8627
- const fd = openSync(temporary, "wx", 384);
9370
+ const fd = openSync2(temporary, "wx", 384);
8628
9371
  let open = true;
8629
9372
  try {
8630
9373
  try {
8631
9374
  fchmodSync(fd, 384);
8632
9375
  } catch {
8633
- throw new CliError("Could not set the config file to 0600.");
9376
+ throw new Error("Could not set the config file to 0600.");
8634
9377
  }
8635
9378
  writeSync(fd, `${JSON.stringify(config, null, 2)}
8636
9379
  `);
8637
- closeSync(fd);
9380
+ closeSync2(fd);
8638
9381
  open = false;
8639
9382
  renameSync(temporary, path);
8640
9383
  } catch (error) {
8641
9384
  if (open) {
8642
9385
  try {
8643
- closeSync(fd);
9386
+ closeSync2(fd);
8644
9387
  } catch {
8645
9388
  }
8646
9389
  }
@@ -8657,27 +9400,561 @@ function clearConfig() {
8657
9400
  unlinkSync(path);
8658
9401
  return true;
8659
9402
  }
8660
- function describeApiFailure(error) {
8661
- const candidate = error;
8662
- const status = typeof candidate.status === "number" ? candidate.status : void 0;
8663
- if (status !== void 0) {
8664
- const type = candidate.error?.error?.type ?? candidate.error?.type;
8665
- const requestId = candidate.request_id;
8666
- return `the server answered ${status}${type ? ` (${type})` : ""}${requestId ? `, request ${requestId}` : ""}`;
9403
+
9404
+ // src/sessions-usage.ts
9405
+ var SESSION_STATUSES = ["rescheduling", "running", "idle", "terminated"];
9406
+ var USAGE_GROUP_BY = ["day", "model", "agent", "agent_version", "user_profile", "session"];
9407
+ function formatCents(amount) {
9408
+ if (amount === null || amount === void 0) return "-";
9409
+ const match = /^(-?)(\d+)$/.exec(amount);
9410
+ if (match === null) return amount;
9411
+ const sign = match[1] === "-" ? "-$" : "$";
9412
+ const digits = match[2].padStart(3, "0");
9413
+ return `${sign}${digits.slice(0, -2)}.${digits.slice(-2)}`;
9414
+ }
9415
+ function formatMicros(cost) {
9416
+ if (cost === null || cost === void 0) return "-";
9417
+ const match = /^(-?)(\d+)$/.exec(cost);
9418
+ if (match === null) return cost;
9419
+ const sign = match[1] === "-" ? "-$" : "$";
9420
+ const digits = match[2].padStart(7, "0");
9421
+ return `${sign}${digits.slice(0, -6)}.${digits.slice(-6)}`;
9422
+ }
9423
+ function formatCount(value) {
9424
+ return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
9425
+ }
9426
+ function isRealDate(year, month, day) {
9427
+ if (month < 1 || month > 12 || day < 1) return false;
9428
+ const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
9429
+ return day <= lastDay;
9430
+ }
9431
+ function normalizeInstant(value, boundary) {
9432
+ const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
9433
+ if (dateOnly !== null) {
9434
+ const [, year, month, day] = dateOnly;
9435
+ if (!isRealDate(Number(year), Number(month), Number(day))) return null;
9436
+ return boundary === "start" ? `${value}T00:00:00Z` : `${value}T23:59:59.999Z`;
9437
+ }
9438
+ const rfc3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(value);
9439
+ if (rfc3339 !== null) {
9440
+ const [, year, month, day, hour, minute, second] = rfc3339;
9441
+ if (!isRealDate(Number(year), Number(month), Number(day))) return null;
9442
+ if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59) return null;
9443
+ return value;
8667
9444
  }
8668
- const name = error.name;
8669
- const causeName = candidate.cause?.name;
8670
- if (name === "AbortError" || name === "TimeoutError" || name === "APIConnectionTimeoutError" || // El SDK envuelve el aborto propio (nuestro `AbortSignal.timeout`) en este error.
8671
- name === "APIUserAbortError" || causeName === "AbortError" || causeName === "TimeoutError" || candidate.cause?.code === "ABORT_ERR") {
8672
- return "the request timed out";
9445
+ return null;
9446
+ }
9447
+ function splitList(values) {
9448
+ const result = [];
9449
+ for (const value of values ?? []) {
9450
+ for (const part of value.split(",")) {
9451
+ const trimmed = part.trim();
9452
+ if (trimmed.length > 0 && !result.includes(trimmed)) result.push(trimmed);
9453
+ }
8673
9454
  }
8674
- const code = candidate.cause?.code;
8675
- return code ? `the request failed (${code})` : "the request failed";
9455
+ return result;
8676
9456
  }
8677
- var BASE_URL_HINT = "Set NOUTER_PLATFORM_BASE_URL or run `nouter-platform login`.";
8678
- var LOGIN_BASE_URL_HINT = "Set NOUTER_PLATFORM_BASE_URL before logging in.";
8679
- function isLoopbackHost(hostname2) {
8680
- const host = hostname2.toLowerCase();
9457
+ var SUMMARY_LIMIT = 80;
9458
+ function collapse(text) {
9459
+ return text.replace(/\s+/g, " ").trim();
9460
+ }
9461
+ function eventSummary(event) {
9462
+ if (event.type === "user.message" || event.type === "agent.message") {
9463
+ const text = collapse(
9464
+ (event.content ?? []).filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ")
9465
+ );
9466
+ if (text.length === 0) return "-";
9467
+ return text.length > SUMMARY_LIMIT ? `${text.slice(0, SUMMARY_LIMIT)}\u2026` : text;
9468
+ }
9469
+ if (event.type === "span.model_request_end") {
9470
+ return `${event.model_usage?.input_tokens ?? 0} in / ${event.model_usage?.output_tokens ?? 0} out`;
9471
+ }
9472
+ if (event.type === "span.outcome_evaluation_end") {
9473
+ return typeof event.result === "string" ? event.result : "-";
9474
+ }
9475
+ return "-";
9476
+ }
9477
+ function agentLabel(session) {
9478
+ if (session.agent?.id === void 0 || session.agent.version === void 0) return "-";
9479
+ return `${session.agent.id}@${session.agent.version}`;
9480
+ }
9481
+ function sessionRow(session) {
9482
+ return [
9483
+ session.id,
9484
+ session.status,
9485
+ agentLabel(session),
9486
+ session.user_profile_id ?? "-",
9487
+ session.created_at,
9488
+ formatCents(session.usage?.list_cost?.amount)
9489
+ ];
9490
+ }
9491
+ function lineOf(label2, value) {
9492
+ return `${`${label2}:`.padEnd(17)} ${value}`;
9493
+ }
9494
+ function createdByLabel(createdBy) {
9495
+ if (!createdBy) return "-";
9496
+ const type = createdBy.type ?? "user";
9497
+ const id = createdBy.id ?? "";
9498
+ const name = createdBy.name ? ` (${createdBy.name})` : "";
9499
+ return `${type} ${id}${name}`.trim();
9500
+ }
9501
+ function statsLabel(stats) {
9502
+ if (stats?.active_seconds === void 0 || stats.duration_seconds === void 0) return "-";
9503
+ return `${stats.active_seconds.toFixed(1)}s active / ${stats.duration_seconds.toFixed(1)}s total`;
9504
+ }
9505
+ function tokensLabel(usage) {
9506
+ if (usage === void 0) return "-";
9507
+ const cacheWrite = (usage.cache_creation?.ephemeral_1h_input_tokens ?? 0) + (usage.cache_creation?.ephemeral_5m_input_tokens ?? 0);
9508
+ return [
9509
+ `${formatCount(usage.input_tokens ?? 0)} in`,
9510
+ `${formatCount(usage.output_tokens ?? 0)} out`,
9511
+ `${formatCount(usage.cache_read_input_tokens ?? 0)} cache read`,
9512
+ `${formatCount(cacheWrite)} cache write`
9513
+ ].join(" / ");
9514
+ }
9515
+ function costLabel(usage) {
9516
+ const listCost = usage?.list_cost;
9517
+ if (listCost === null || listCost === void 0 || listCost.amount === void 0 || listCost.amount === null) {
9518
+ return "-";
9519
+ }
9520
+ return `${formatCents(listCost.amount)} ${listCost.currency ?? "USD"}`;
9521
+ }
9522
+ function sessionDetail(session) {
9523
+ return [
9524
+ lineOf("ID", session.id),
9525
+ lineOf("Title", session.title ?? "-"),
9526
+ lineOf("Status", session.status),
9527
+ lineOf("Agent", agentLabel(session)),
9528
+ lineOf("Environment", session.environment_id ?? "-"),
9529
+ lineOf("User profile", session.user_profile_id ?? "-"),
9530
+ lineOf("Created by", createdByLabel(session.created_by)),
9531
+ lineOf("Created", session.created_at),
9532
+ lineOf("Updated", session.updated_at ?? "-"),
9533
+ lineOf("Archived", session.archived_at ?? "-"),
9534
+ lineOf("Deployment", session.deployment_id ?? "-"),
9535
+ lineOf("Sandbox", session._oma?.sandbox_mode ?? "-"),
9536
+ lineOf("Conversation key", session.conversation_key ?? "-"),
9537
+ lineOf("Stats", statsLabel(session.stats)),
9538
+ lineOf("Tokens", tokensLabel(session.usage)),
9539
+ lineOf("Cost", costLabel(session.usage))
9540
+ ];
9541
+ }
9542
+ function eventRow(event) {
9543
+ return [event.processed_at ?? "-", event.type, event.id, eventSummary(event)];
9544
+ }
9545
+ function table(rows) {
9546
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
9547
+ return rows.map((row) => row.map((cell, column) => (cell ?? "").padEnd(widths[column])).join(" ").trimEnd()).join("\n");
9548
+ }
9549
+ var DIMENSIONS = {
9550
+ day: { title: "DAY", value: (row) => row.day ?? "-" },
9551
+ model: { title: "MODEL", value: (row) => row.model ?? "-" },
9552
+ agent: { title: "AGENT", value: (row) => row.agent_id ?? "-" },
9553
+ agent_version: {
9554
+ title: "AGENT VERSION",
9555
+ value: (row) => row.agent_version === null || row.agent_version === void 0 ? "(none)" : String(row.agent_version)
9556
+ },
9557
+ user_profile: { title: "USER", value: (row) => row.user_profile_id ?? "-" },
9558
+ session: { title: "SESSION", value: (row) => row.session_id ?? "-" }
9559
+ };
9560
+ function costCell(row) {
9561
+ if (row.cost_micros === null) return "-";
9562
+ return `${formatMicros(row.cost_micros)}${row.unpriced_requests > 0 ? "*" : ""}`;
9563
+ }
9564
+ function usageTable(report) {
9565
+ const dimensions = report.group_by.map((group) => DIMENSIONS[group]).filter((dimension) => dimension !== void 0);
9566
+ const header = [
9567
+ ...dimensions.map((dimension) => dimension.title),
9568
+ "REQUESTS",
9569
+ "ERRORS",
9570
+ "INPUT",
9571
+ "OUTPUT",
9572
+ "CACHE READ",
9573
+ "CACHE WRITE",
9574
+ "COST"
9575
+ ];
9576
+ const rows = report.rows.map((row) => [
9577
+ ...dimensions.map((dimension) => dimension.value(row)),
9578
+ formatCount(row.requests),
9579
+ formatCount(row.error_requests),
9580
+ formatCount(row.input_tokens),
9581
+ formatCount(row.output_tokens),
9582
+ formatCount(row.cache_read_input_tokens),
9583
+ formatCount(row.cache_creation_input_tokens),
9584
+ costCell(row)
9585
+ ]);
9586
+ const heading = `Usage ${report.from} to ${report.to} (UTC), grouped by ${report.group_by.join(", ")}.`;
9587
+ return `${heading}
9588
+
9589
+ ${table([header, ...rows])}`;
9590
+ }
9591
+ function unpricedTotal(report) {
9592
+ return report.rows.reduce((total, row) => total + row.unpriced_requests, 0);
9593
+ }
9594
+
9595
+ // src/identity-token.ts
9596
+ import { readFileSync as readFileSync3 } from "node:fs";
9597
+ var IdentityTokenError = class extends Error {
9598
+ constructor(message) {
9599
+ super(message);
9600
+ this.name = "IdentityTokenError";
9601
+ }
9602
+ };
9603
+ var NON_EMPTY = (value) => typeof value === "string" && value.length > 0;
9604
+ function identityTokenSourceFromEnv(env = process.env) {
9605
+ const value = env.NOUTER_PLATFORM_IDENTITY_TOKEN;
9606
+ if (NON_EMPTY(value)) return { kind: "value", token: value };
9607
+ const path = env.NOUTER_PLATFORM_IDENTITY_TOKEN_FILE;
9608
+ if (NON_EMPTY(path)) return { kind: "file", path };
9609
+ return null;
9610
+ }
9611
+ var PRINTABLE = /^[\x21-\x7e]+$/u;
9612
+ function clean(token) {
9613
+ const trimmed = token.trim();
9614
+ if (trimmed.length === 0) throw new IdentityTokenError("The identity token is empty.");
9615
+ if (!PRINTABLE.test(trimmed)) {
9616
+ throw new IdentityTokenError("The identity token has characters the CLI cannot use.");
9617
+ }
9618
+ return trimmed;
9619
+ }
9620
+ function createIdentityTokenReader(source, read = (path) => readFileSync3(path, "utf8")) {
9621
+ if (source.kind === "value") {
9622
+ return { read: () => clean(source.token) };
9623
+ }
9624
+ return {
9625
+ read() {
9626
+ let contents;
9627
+ try {
9628
+ contents = read(source.path);
9629
+ } catch {
9630
+ throw new IdentityTokenError(`Could not read the identity token file ${source.path}.`);
9631
+ }
9632
+ return clean(contents);
9633
+ }
9634
+ };
9635
+ }
9636
+
9637
+ // src/federation.ts
9638
+ var FederationError = class extends Error {
9639
+ constructor(message) {
9640
+ super(message);
9641
+ this.name = "FederationError";
9642
+ }
9643
+ };
9644
+ var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
9645
+ var REFRESH_MARGIN_SECONDS = 30;
9646
+ var MIN_EXPIRES_IN = 60;
9647
+ var MAX_EXPIRES_IN = 86400;
9648
+ var present = (value) => typeof value === "string" && value.length > 0;
9649
+ function federationSettingsFromEnv(env = process.env) {
9650
+ if (!present(env.NOUTER_PLATFORM_FEDERATION_RULE_ID)) return null;
9651
+ if (!present(env.NOUTER_PLATFORM_ORGANIZATION_ID)) {
9652
+ throw new FederationError(
9653
+ "NOUTER_PLATFORM_ORGANIZATION_ID is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
9654
+ );
9655
+ }
9656
+ const identityToken = identityTokenSourceFromEnv(env);
9657
+ if (identityToken === null) {
9658
+ throw new IdentityTokenError(
9659
+ "NOUTER_PLATFORM_IDENTITY_TOKEN or NOUTER_PLATFORM_IDENTITY_TOKEN_FILE is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
9660
+ );
9661
+ }
9662
+ return {
9663
+ ruleId: env.NOUTER_PLATFORM_FEDERATION_RULE_ID,
9664
+ organizationId: env.NOUTER_PLATFORM_ORGANIZATION_ID,
9665
+ ...present(env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID) && { serviceAccountId: env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID },
9666
+ ...present(env.NOUTER_PLATFORM_WORKSPACE_ID) && { workspaceId: env.NOUTER_PLATFORM_WORKSPACE_ID },
9667
+ identityToken
9668
+ };
9669
+ }
9670
+ function parseToken(payload) {
9671
+ if (typeof payload !== "object" || payload === null) return null;
9672
+ const body = payload;
9673
+ if (typeof body.access_token !== "string" || !body.access_token.startsWith("oma_oat_")) return null;
9674
+ if (body.token_type !== "Bearer") return null;
9675
+ if (typeof body.expires_in !== "number" || !Number.isInteger(body.expires_in) || body.expires_in < MIN_EXPIRES_IN || body.expires_in > MAX_EXPIRES_IN) {
9676
+ return null;
9677
+ }
9678
+ if (typeof body.scope !== "string" || body.scope.trim().length === 0) return null;
9679
+ return {
9680
+ accessToken: body.access_token,
9681
+ expiresIn: body.expires_in,
9682
+ scopes: body.scope.split(" ").filter((scope) => scope.length > 0)
9683
+ };
9684
+ }
9685
+ async function exchange(baseUrl, settings, assertion, fetch, timeoutMs) {
9686
+ let response;
9687
+ try {
9688
+ response = await fetch(`${baseUrl}/v1/oauth/token`, {
9689
+ method: "POST",
9690
+ headers: { "content-type": "application/json", accept: "application/json" },
9691
+ body: JSON.stringify({
9692
+ grant_type: GRANT_TYPE,
9693
+ assertion,
9694
+ federation_rule_id: settings.ruleId,
9695
+ organization_id: settings.organizationId,
9696
+ ...settings.serviceAccountId !== void 0 && { service_account_id: settings.serviceAccountId },
9697
+ ...settings.workspaceId !== void 0 && { workspace_id: settings.workspaceId }
9698
+ }),
9699
+ signal: AbortSignal.timeout(timeoutMs),
9700
+ // La aserción va en el cuerpo: si el host redirige (la consola detrás de un IdP), seguir el 3xx la llevaría a
9701
+ // otro origen. Se corta acá con el mismo mensaje que el cliente.
9702
+ redirect: "manual"
9703
+ });
9704
+ } catch {
9705
+ throw new FederationError("The federation exchange failed (network error).");
9706
+ }
9707
+ const notTheApi = notTheApiMessage(`${baseUrl}/v1/oauth/token`, response);
9708
+ if (notTheApi !== null) throw new FederationError(notTheApi);
9709
+ if (response.status === 401) {
9710
+ throw new FederationError("Authentication failed");
9711
+ }
9712
+ if (!response.ok) {
9713
+ throw new FederationError(`The federation exchange failed (the server answered ${response.status}).`);
9714
+ }
9715
+ let payload;
9716
+ try {
9717
+ payload = await response.json();
9718
+ } catch {
9719
+ throw new FederationError("The federation exchange returned an unexpected response.");
9720
+ }
9721
+ const token = parseToken(payload);
9722
+ if (token === null) throw new FederationError("The federation exchange returned an unexpected response.");
9723
+ return token;
9724
+ }
9725
+ function createFederationTokenProvider(options) {
9726
+ const now = options.now ?? Date.now;
9727
+ const reader = createIdentityTokenReader(options.settings.identityToken, options.readFile);
9728
+ let cached = null;
9729
+ return {
9730
+ async getToken() {
9731
+ const assertion = reader.read();
9732
+ const current = now();
9733
+ if (cached !== null && cached.assertion === assertion && current < cached.refreshAt) {
9734
+ return cached.token;
9735
+ }
9736
+ const token = await exchange(options.baseUrl, options.settings, assertion, options.fetch, options.timeoutMs);
9737
+ cached = {
9738
+ token,
9739
+ assertion,
9740
+ refreshAt: current + Math.max(token.expiresIn - REFRESH_MARGIN_SECONDS, 0) * 1e3
9741
+ };
9742
+ return token;
9743
+ }
9744
+ };
9745
+ }
9746
+
9747
+ // src/login-callback.ts
9748
+ import { timingSafeEqual } from "node:crypto";
9749
+ import { createServer } from "node:http";
9750
+ var LOGIN_CALLBACK_TIMEOUT_MS = 10 * 60 * 1e3;
9751
+ var MAX_BODY_BYTES = 16 * 1024;
9752
+ function statesMatch(expected, given) {
9753
+ if (given === null) return false;
9754
+ const left = Buffer.from(expected, "utf8");
9755
+ const right = Buffer.from(given, "utf8");
9756
+ return right.length === left.length && timingSafeEqual(right, left);
9757
+ }
9758
+ var LoginAccessDeniedError = class extends Error {
9759
+ constructor() {
9760
+ super("The login was canceled (access_denied).");
9761
+ this.name = "LoginAccessDeniedError";
9762
+ }
9763
+ };
9764
+ var LoginCallbackTimeoutError = class extends Error {
9765
+ constructor() {
9766
+ super("The login timed out after ten minutes.");
9767
+ this.name = "LoginCallbackTimeoutError";
9768
+ }
9769
+ };
9770
+ function startLoginCallback(options) {
9771
+ const timeoutMs = options.timeoutMs ?? LOGIN_CALLBACK_TIMEOUT_MS;
9772
+ let settled = false;
9773
+ let timer;
9774
+ let resolveResult = () => {
9775
+ };
9776
+ let rejectResult = () => {
9777
+ };
9778
+ const result = new Promise((resolve, reject) => {
9779
+ resolveResult = resolve;
9780
+ rejectResult = reject;
9781
+ });
9782
+ result.catch(() => {
9783
+ });
9784
+ const server = createServer((request, response) => {
9785
+ void handleRequest(request, response).catch(() => {
9786
+ sendHtml(response, 500, "The login callback could not read the request.");
9787
+ });
9788
+ });
9789
+ const stateMatches = (given) => statesMatch(options.state, given);
9790
+ const finish = (action) => {
9791
+ if (settled) return false;
9792
+ settled = true;
9793
+ if (timer) clearTimeout(timer);
9794
+ action();
9795
+ if (server.listening) server.close();
9796
+ return true;
9797
+ };
9798
+ async function handleRequest(request, response) {
9799
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
9800
+ if (url.pathname !== "/callback") {
9801
+ sendHtml(response, 404, "Not found.");
9802
+ return;
9803
+ }
9804
+ if (request.method === "POST") {
9805
+ const contentType = request.headers["content-type"] ?? "";
9806
+ if (!contentType.toLowerCase().startsWith("application/x-www-form-urlencoded")) {
9807
+ sendHtml(response, 415, "The callback only accepts an application/x-www-form-urlencoded form.");
9808
+ return;
9809
+ }
9810
+ const body = await readBody(request);
9811
+ const form = new URLSearchParams(body);
9812
+ if (!stateMatches(form.get("state"))) {
9813
+ sendHtml(response, 400, "Invalid state.");
9814
+ return;
9815
+ }
9816
+ if (form.get("error") === "access_denied") {
9817
+ if (finish(() => rejectResult(new LoginAccessDeniedError()))) {
9818
+ sendHtml(response, 200, "Login canceled. You can close this window.");
9819
+ } else {
9820
+ sendHtml(response, 409, "The login callback was already used.");
9821
+ }
9822
+ return;
9823
+ }
9824
+ const code = form.get("code");
9825
+ if (!code) {
9826
+ sendHtml(response, 400, "Missing code.");
9827
+ return;
9828
+ }
9829
+ const delivered = { code };
9830
+ if (finish(() => resolveResult(delivered))) {
9831
+ sendHtml(response, 200, "Login approved. You can close this window.");
9832
+ } else {
9833
+ sendHtml(response, 409, "The login callback was already used.");
9834
+ }
9835
+ return;
9836
+ }
9837
+ if (request.method === "GET") {
9838
+ sendHtml(response, 400, "The callback accepts the login result only as a POST form.");
9839
+ return;
9840
+ }
9841
+ sendHtml(response, 405, "Method not allowed.");
9842
+ }
9843
+ timer = setTimeout(() => {
9844
+ finish(() => rejectResult(new LoginCallbackTimeoutError()));
9845
+ }, timeoutMs);
9846
+ timer.unref?.();
9847
+ return new Promise((resolveServer, rejectServer) => {
9848
+ server.on("error", (error) => {
9849
+ settled = true;
9850
+ if (timer) clearTimeout(timer);
9851
+ rejectServer(error);
9852
+ });
9853
+ server.listen(0, "127.0.0.1", () => {
9854
+ const address = server.address();
9855
+ if (!address || typeof address === "string") {
9856
+ rejectServer(new Error("The login callback did not bind a TCP port."));
9857
+ return;
9858
+ }
9859
+ resolveServer({
9860
+ callbackUrl: `http://127.0.0.1:${address.port}/callback`,
9861
+ address: () => {
9862
+ const bound = server.address();
9863
+ return typeof bound === "object" && bound !== null ? { address: bound.address, port: bound.port } : null;
9864
+ },
9865
+ waitForResult: () => result,
9866
+ close: () => new Promise((resolveClose) => {
9867
+ settled = true;
9868
+ if (timer) clearTimeout(timer);
9869
+ if (!server.listening) {
9870
+ resolveClose();
9871
+ return;
9872
+ }
9873
+ server.close(() => resolveClose());
9874
+ server.closeAllConnections?.();
9875
+ })
9876
+ });
9877
+ });
9878
+ });
9879
+ }
9880
+ function sendHtml(response, status, message) {
9881
+ response.writeHead(status, {
9882
+ "content-type": "text/html; charset=utf-8",
9883
+ "cache-control": "no-store",
9884
+ "referrer-policy": "no-referrer",
9885
+ connection: "close"
9886
+ });
9887
+ response.end(`<!doctype html><meta charset="utf-8"><title>Nouter platform login</title><p>${message}</p>`);
9888
+ }
9889
+ async function readBody(request) {
9890
+ let body = "";
9891
+ for await (const chunk of request) {
9892
+ body += String(chunk);
9893
+ if (body.length > MAX_BODY_BYTES) {
9894
+ throw new Error("The login callback body is too large.");
9895
+ }
9896
+ }
9897
+ return body;
9898
+ }
9899
+
9900
+ // src/pkce.ts
9901
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
9902
+ function generateCodeVerifier() {
9903
+ return randomBytes2(32).toString("base64url");
9904
+ }
9905
+ function codeChallengeFor(verifier) {
9906
+ return createHash("sha256").update(verifier).digest("base64url");
9907
+ }
9908
+
9909
+ // src/index.ts
9910
+ function cliUserAgent() {
9911
+ return `nouter-platform-cli/${cliVersion()} node/${process.versions.node}`;
9912
+ }
9913
+ var REQUEST_TIMEOUT_MS = 3e4;
9914
+ var CliError = class extends Error {
9915
+ exitCode;
9916
+ /** El código estable de R9 que viaja como `error.code` con `--json`. */
9917
+ code;
9918
+ constructor(message, exitCode = 1, code) {
9919
+ super(message);
9920
+ this.name = "CliError";
9921
+ this.exitCode = exitCode;
9922
+ if (code !== void 0) this.code = code;
9923
+ }
9924
+ };
9925
+ function serverErrorType(error) {
9926
+ const candidate = error;
9927
+ const inner = candidate.error?.error?.type;
9928
+ if (typeof inner === "string") return inner;
9929
+ const outer = candidate.error?.type;
9930
+ return typeof outer === "string" ? outer : void 0;
9931
+ }
9932
+ var SESSION_LIMIT_CODES = /* @__PURE__ */ new Set(["SESSION_EXPIRED", "SESSION_IDLE", "SESSION_REVOKED"]);
9933
+ function apiFailure(error, fallback) {
9934
+ const typeName = serverErrorType(error);
9935
+ if (typeName !== void 0 && (SESSION_LIMIT_CODES.has(typeName) || typeName === "ELEVATION_REQUIRED")) {
9936
+ return new CliError(`${fallback}: ${describeApiFailure(error)}`, 77, typeName);
9937
+ }
9938
+ return new CliError(`${fallback}: ${describeApiFailure(error)}`);
9939
+ }
9940
+ function isCliSessionToken(value) {
9941
+ return value.startsWith("nps_");
9942
+ }
9943
+ function isElevationRequired(error) {
9944
+ const candidate = error;
9945
+ return candidate.status === 403 && serverErrorType(error) === "ELEVATION_REQUIRED";
9946
+ }
9947
+ function elevationCliError(error) {
9948
+ return new CliError(
9949
+ `This operation needs elevation and the request was not elevated. Run \`nouter-platform elevate\` and try again (${describeApiFailure(error)}).`,
9950
+ 77,
9951
+ "ELEVATION_REQUIRED"
9952
+ );
9953
+ }
9954
+ var BASE_URL_HINT = "Set NOUTER_PLATFORM_BASE_URL or run `nouter-platform login`.";
9955
+ var LOGIN_BASE_URL_HINT = "Set NOUTER_PLATFORM_BASE_URL before logging in.";
9956
+ function isLoopbackHost(hostname2) {
9957
+ const host = hostname2.toLowerCase();
8681
9958
  return host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
8682
9959
  }
8683
9960
  function normalizeBaseUrl(value) {
@@ -8694,6 +9971,15 @@ function normalizeBaseUrl(value) {
8694
9971
  }
8695
9972
  return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
8696
9973
  }
9974
+ function sanitizeHostname(raw) {
9975
+ const clean2 = raw.replace(
9976
+ /[\u0000-\u001F\u007F-\u009F\u061C\u200B-\u200F\u2028-\u202E\u2066-\u2069\uFEFF]/g,
9977
+ ""
9978
+ );
9979
+ const trimmed = clean2.trim();
9980
+ if (trimmed.length === 0) return "unknown";
9981
+ return trimmed.slice(0, 253);
9982
+ }
8697
9983
  function requireBaseUrl(stored, hint = BASE_URL_HINT) {
8698
9984
  const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
8699
9985
  const candidate = envBase && envBase.length > 0 ? envBase : stored?.baseUrl;
@@ -8741,146 +10027,624 @@ function federationFailure(error) {
8741
10027
  if (error instanceof FederationError || error instanceof IdentityTokenError) throw new CliError(error.message);
8742
10028
  throw error;
8743
10029
  }
8744
- async function resolveAuth(deps) {
8745
- const stored = readConfig({ warn: deps.writeStderr });
8746
- const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
8747
- const envKey = environmentApiKey();
8748
- const federationConfigured = typeof process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID === "string" && process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID.length > 0;
8749
- if (envKey !== null) {
8750
- if (federationConfigured) {
8751
- deps.writeStderr(
8752
- `Warning: ${envKey.name} is set and wins over the federation credentials; unset it to use NOUTER_PLATFORM_FEDERATION_RULE_ID.`
8753
- );
8754
- }
8755
- return { baseUrl: requireBaseUrl(stored), credential: envKey.value, transport: "api-key" };
10030
+ async function resolveAuth(deps) {
10031
+ const stored = readConfig();
10032
+ const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
10033
+ const envKey = environmentApiKey();
10034
+ const federationConfigured = typeof process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID === "string" && process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID.length > 0;
10035
+ if (envKey !== null) {
10036
+ if (federationConfigured) {
10037
+ deps.writeStderr(
10038
+ `Warning: ${envKey.name} is set and wins over the federation credentials; unset it to use NOUTER_PLATFORM_FEDERATION_RULE_ID.`
10039
+ );
10040
+ }
10041
+ return { baseUrl: requireBaseUrl(stored), credential: envKey.value, transport: "api-key" };
10042
+ }
10043
+ if (federationConfigured) {
10044
+ const settings = federationSettingsOrNull();
10045
+ if (settings !== null) {
10046
+ const baseUrl = requireBaseUrl(stored);
10047
+ const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
10048
+ return { baseUrl, credential: token.accessToken, transport: "bearer" };
10049
+ }
10050
+ }
10051
+ if (!stored) {
10052
+ throw new CliError("Not authenticated. Run `nouter-platform login --api-key` or set NOUTER_PLATFORM_API_KEY.");
10053
+ }
10054
+ const session = isCliSessionToken(stored.apiKey);
10055
+ if (stored.baseUrl === null) {
10056
+ throw new CliError(
10057
+ "The stored config has no API base URL, so the key's host is unknown. Run `nouter-platform login` again against your API URL, or set NOUTER_PLATFORM_API_KEY."
10058
+ );
10059
+ }
10060
+ if (session && stored.clientId !== void 0 && stored.clientId !== CLI_CLIENT_ID) {
10061
+ throw new CliError(
10062
+ `The stored CLI session belongs to the client ${stored.clientId}, not ${CLI_CLIENT_ID}. Run \`nouter-platform login\` again.`,
10063
+ 77,
10064
+ "WRONG_INSTALLATION"
10065
+ );
10066
+ }
10067
+ const storedBaseUrl = normalizeBaseUrl(stored.baseUrl);
10068
+ if (envBase && envBase.length > 0) {
10069
+ const envBaseUrl = normalizeBaseUrl(envBase);
10070
+ if (envBaseUrl !== storedBaseUrl) {
10071
+ if (session) {
10072
+ throw new CliError(
10073
+ `The stored CLI session belongs to the installation ${storedBaseUrl}, not ${envBaseUrl}. Run \`nouter-platform login\` against ${envBaseUrl}.`,
10074
+ 77,
10075
+ "WRONG_INSTALLATION"
10076
+ );
10077
+ }
10078
+ throw new CliError(
10079
+ `The stored API key was saved for ${storedBaseUrl}, but NOUTER_PLATFORM_BASE_URL points to ${envBaseUrl}. Run \`nouter-platform login\` against ${envBaseUrl} to store a key for it, or set NOUTER_PLATFORM_API_KEY.`
10080
+ );
10081
+ }
10082
+ return { baseUrl: envBaseUrl, credential: stored.apiKey, transport: session ? "bearer" : "api-key" };
10083
+ }
10084
+ return { baseUrl: storedBaseUrl, credential: stored.apiKey, transport: session ? "bearer" : "api-key" };
10085
+ }
10086
+ var notTheApiMiddleware = async (request, next) => {
10087
+ const response = await next({ ...request, redirect: "manual" });
10088
+ const message = notTheApiMessage(request.url, response);
10089
+ if (message !== null) throw new CliError(message);
10090
+ return response;
10091
+ };
10092
+ function clientFor(auth, deps, options = {}) {
10093
+ const common = {
10094
+ baseURL: auth.baseUrl,
10095
+ fetch: deps.fetch,
10096
+ userAgent: cliUserAgent(),
10097
+ middleware: [notTheApiMiddleware],
10098
+ ...options.maxRetries !== void 0 && { maxRetries: options.maxRetries }
10099
+ };
10100
+ return auth.transport === "bearer" ? new NouterPlatform({ ...common, authToken: auth.credential }) : new NouterPlatform({ ...common, apiKey: auth.credential });
10101
+ }
10102
+ function apiKeyAuth(baseUrl, apiKey) {
10103
+ return { baseUrl, credential: apiKey, transport: "api-key" };
10104
+ }
10105
+ async function fetchMe(auth, deps) {
10106
+ try {
10107
+ return await clientFor(auth, deps).platform.request({
10108
+ method: "get",
10109
+ path: "/v1/oma/me",
10110
+ signal: AbortSignal.timeout(deps.requestTimeoutMs)
10111
+ });
10112
+ } catch (error) {
10113
+ if (error instanceof CliError) throw error;
10114
+ throw apiFailure(error, "Could not read the account");
10115
+ }
10116
+ }
10117
+ function organizationOf(me) {
10118
+ const tenant = me.tenant ?? me.tenants?.[0];
10119
+ if (!tenant) return null;
10120
+ const name = tenant.name;
10121
+ const id = tenant.id;
10122
+ if (name && id) return `${name} (${id})`;
10123
+ return name ?? id ?? null;
10124
+ }
10125
+ function roleOf(me) {
10126
+ if (typeof me.role === "string" && me.role.length > 0) return me.role;
10127
+ return me.tenants?.[0]?.role ?? null;
10128
+ }
10129
+ function loginBaseUrl(deps) {
10130
+ const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
10131
+ const stored = envBase && envBase.length > 0 ? null : readConfig();
10132
+ try {
10133
+ return requireBaseUrl(stored, LOGIN_BASE_URL_HINT);
10134
+ } catch (error) {
10135
+ if (error instanceof CliError && !error.message.includes("NOUTER_PLATFORM_BASE_URL")) {
10136
+ throw new CliError(`${error.message} ${LOGIN_BASE_URL_HINT}`);
10137
+ }
10138
+ throw error;
10139
+ }
10140
+ }
10141
+ function remoteSessionSignal(env, platform) {
10142
+ if (typeof env.SSH_CONNECTION === "string" && env.SSH_CONNECTION.length > 0) return "SSH_CONNECTION";
10143
+ if (typeof env.SSH_TTY === "string" && env.SSH_TTY.length > 0) return "SSH_TTY";
10144
+ if (env.CODESPACES === "true") return "CODESPACES";
10145
+ if (platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return "no DISPLAY or WAYLAND_DISPLAY";
10146
+ return null;
10147
+ }
10148
+ function resolveLoginMode(args, env, platform) {
10149
+ if (args.includes("--browser")) return { mode: "loopback", signal: null };
10150
+ if (args.includes("--paste")) return { mode: "paste", signal: null };
10151
+ const signal = remoteSessionSignal(env, platform);
10152
+ return signal === null ? { mode: "loopback", signal: null } : { mode: "paste", signal };
10153
+ }
10154
+ function loginEnvironment(deps) {
10155
+ return deps.env ?? process.env;
10156
+ }
10157
+ function loginPlatform(deps) {
10158
+ return deps.platform ?? process.platform;
10159
+ }
10160
+ function announceRemoteSession(signal, deps) {
10161
+ deps.writeStderr(
10162
+ `Remote session detected (${signal}): using paste mode. Run \`nouter-platform login --browser\` to force the browser flow.`
10163
+ );
10164
+ }
10165
+ async function loginWithApiKey(deps) {
10166
+ const baseUrl = loginBaseUrl(deps);
10167
+ const apiKey = (await deps.readStdin()).trim();
10168
+ if (apiKey.length === 0) {
10169
+ throw new CliError("No API key on stdin. Pipe it in: `printf '%s' \"$KEY\" | nouter-platform login --api-key`.");
10170
+ }
10171
+ if (!/^[\x21-\x7e]+$/.test(apiKey)) {
10172
+ throw new CliError("The API key has characters the CLI cannot use. Pipe it in again.");
10173
+ }
10174
+ const me = await fetchMe(apiKeyAuth(baseUrl, apiKey), deps);
10175
+ writeConfig({ baseUrl, apiKey });
10176
+ deps.writeStdout(`Logged in to ${organizationOf(me) ?? "the organization"}.`);
10177
+ return 0;
10178
+ }
10179
+ async function cliJsonRequest(deps, url, init) {
10180
+ const headers = { accept: "application/json" };
10181
+ if (init.body !== void 0) headers["content-type"] = "application/json";
10182
+ if (init.token !== void 0) headers.authorization = `Bearer ${init.token}`;
10183
+ let response;
10184
+ try {
10185
+ response = await deps.fetch(url, {
10186
+ method: init.method,
10187
+ headers,
10188
+ ...init.body !== void 0 && { body: JSON.stringify(init.body) },
10189
+ signal: AbortSignal.timeout(deps.requestTimeoutMs)
10190
+ });
10191
+ } catch (error) {
10192
+ throw new CliError(`The request failed: ${describeApiFailure(error)}`, 75, "LOGIN_TIMEOUT");
10193
+ }
10194
+ const text = await response.text();
10195
+ let body = null;
10196
+ if (text.length > 0) {
10197
+ try {
10198
+ body = JSON.parse(text);
10199
+ } catch {
10200
+ body = text;
10201
+ }
10202
+ }
10203
+ return { status: response.status, body };
10204
+ }
10205
+ function bodyField(body, name) {
10206
+ if (typeof body !== "object" || body === null) return void 0;
10207
+ return body[name];
10208
+ }
10209
+ function loginApiError(status, body, fallback) {
10210
+ const type = bodyField(bodyField(body, "error"), "type");
10211
+ const message = bodyField(bodyField(body, "error"), "message");
10212
+ const detail = message && message.length > 0 ? message : `the server answered ${status}`;
10213
+ if (type !== void 0 && (SESSION_LIMIT_CODES.has(type) || type === "ELEVATION_REQUIRED")) {
10214
+ return new CliError(`${fallback}: ${detail}`, 77, type);
10215
+ }
10216
+ if (status >= 500 || status === 429) return new CliError(`${fallback}: ${detail}`, 75, "LOGIN_TIMEOUT");
10217
+ return new CliError(`${fallback}: ${detail}`, 1);
10218
+ }
10219
+ async function startAuthorization(baseUrl, deps, body, token) {
10220
+ const answer = await cliJsonRequest(deps, `${baseUrl}/v1/oma/cli/authorize/start`, {
10221
+ method: "POST",
10222
+ body,
10223
+ ...token !== void 0 && { token }
10224
+ });
10225
+ const requestId = bodyField(answer.body, "request_id");
10226
+ if (answer.status !== 200 || typeof requestId !== "string" || requestId.length === 0) {
10227
+ throw loginApiError(answer.status, answer.body, "Could not start the login");
10228
+ }
10229
+ return requestId;
10230
+ }
10231
+ async function redeemCode(baseUrl, deps, code, verifier) {
10232
+ const answer = await cliJsonRequest(deps, `${baseUrl}/v1/oma/cli/sessions`, {
10233
+ method: "POST",
10234
+ body: { code, code_verifier: verifier }
10235
+ });
10236
+ const sessionId = bodyField(answer.body, "session_id");
10237
+ if (answer.status === 200 && typeof sessionId === "string") {
10238
+ if (bodyField(answer.body, "elevated") === true) return { kind: "elevated", sessionId };
10239
+ const token = bodyField(answer.body, "token");
10240
+ if (typeof token === "string" && token.length > 0) return { kind: "session", token, sessionId };
10241
+ }
10242
+ const type = bodyField(bodyField(answer.body, "error"), "type");
10243
+ if (type === "ELEVATION_REQUIRED") {
10244
+ throw new CliError(
10245
+ "This CLI session needs a fresh console login to elevate. Run `nouter-platform elevate` and sign in again.",
10246
+ 77,
10247
+ "ELEVATION_REQUIRED"
10248
+ );
10249
+ }
10250
+ if (answer.status === 400) {
10251
+ throw new CliError(
10252
+ "The authorization code is invalid, expired, or already used. Run `nouter-platform login` again.",
10253
+ 75,
10254
+ "LOGIN_TIMEOUT"
10255
+ );
10256
+ }
10257
+ throw loginApiError(answer.status, answer.body, "Could not redeem the login code");
10258
+ }
10259
+ function consoleUrlFor(baseUrl, requestId, state, callback) {
10260
+ const url = new URL("/cli/login", baseUrl);
10261
+ url.searchParams.set("request_id", requestId);
10262
+ url.searchParams.set("state", state);
10263
+ if (callback !== void 0) url.searchParams.set("callback", callback);
10264
+ return url.toString();
10265
+ }
10266
+ async function awaitPastedCode(deps, state) {
10267
+ deps.writeStdout("Paste code here if prompted >");
10268
+ const readSecret = deps.readSecret ?? deps.readStdin;
10269
+ const pasted = (await readSecret()).trim();
10270
+ const hash = pasted.lastIndexOf("#");
10271
+ if (hash <= 0 || hash === pasted.length - 1) {
10272
+ throw new CliError(
10273
+ "The pasted code is not in the code#state form. Copy it again from the page that this command opened.",
10274
+ 64,
10275
+ "STATE_MISMATCH"
10276
+ );
10277
+ }
10278
+ const code = pasted.slice(0, hash);
10279
+ const pastedState = pasted.slice(hash + 1);
10280
+ if (!statesMatch(state, pastedState)) {
10281
+ throw new CliError(
10282
+ "The pasted code belongs to another login attempt. Copy it again from the page that this command opened.",
10283
+ 64,
10284
+ "STATE_MISMATCH"
10285
+ );
10286
+ }
10287
+ return code;
10288
+ }
10289
+ function previousBaseUrlOf(previous) {
10290
+ if (previous === null || previous.baseUrl === null) return null;
10291
+ try {
10292
+ return normalizeBaseUrl(previous.baseUrl);
10293
+ } catch {
10294
+ return null;
10295
+ }
10296
+ }
10297
+ async function revokeStoredSession(baseUrl, deps, token) {
10298
+ try {
10299
+ await cliJsonRequest(deps, `${baseUrl}/v1/oma/cli/sessions/current`, { method: "DELETE", token });
10300
+ } catch {
10301
+ }
10302
+ }
10303
+ async function loginWithCode(argv, deps) {
10304
+ const baseUrl = loginBaseUrl(deps);
10305
+ const previous = readConfig();
10306
+ const choice = resolveLoginMode(argv, loginEnvironment(deps), loginPlatform(deps));
10307
+ if (choice.signal !== null) announceRemoteSession(choice.signal, deps);
10308
+ const verifier = generateCodeVerifier();
10309
+ const requestId = await startAuthorization(baseUrl, deps, {
10310
+ code_challenge: codeChallengeFor(verifier),
10311
+ code_challenge_method: "S256",
10312
+ hostname: sanitizeHostname(hostname()),
10313
+ mode: choice.mode,
10314
+ purpose: "login"
10315
+ });
10316
+ const state = randomBytes3(32).toString("base64url");
10317
+ let code;
10318
+ if (choice.mode === "loopback") {
10319
+ const callback = await startLoginCallback({ state, timeoutMs: LOGIN_CALLBACK_TIMEOUT_MS });
10320
+ let consoleUrl;
10321
+ try {
10322
+ consoleUrl = consoleUrlFor(baseUrl, requestId, state, callback.callbackUrl);
10323
+ } catch (error) {
10324
+ await callback.close();
10325
+ throw error;
10326
+ }
10327
+ try {
10328
+ deps.writeStdout(`Open this URL to approve the login:
10329
+ ${consoleUrl}`);
10330
+ deps.openBrowser(consoleUrl);
10331
+ code = (await callback.waitForResult()).code;
10332
+ } catch (error) {
10333
+ if (error instanceof LoginCallbackTimeoutError) {
10334
+ throw new CliError("The login timed out after ten minutes. Run `nouter-platform login` again.", 75, "LOGIN_TIMEOUT");
10335
+ }
10336
+ throw error;
10337
+ } finally {
10338
+ await callback.close();
10339
+ }
10340
+ } else {
10341
+ deps.writeStdout(`Open this URL to approve the login:
10342
+ ${consoleUrlFor(baseUrl, requestId, state)}`);
10343
+ deps.openBrowser(consoleUrlFor(baseUrl, requestId, state));
10344
+ code = await awaitPastedCode(deps, state);
10345
+ }
10346
+ const outcome = await redeemCode(baseUrl, deps, code, verifier);
10347
+ if (outcome.kind !== "session" || outcome.token === void 0) {
10348
+ throw new CliError("The server did not return a CLI session. Run `nouter-platform login` again.", 75, "LOGIN_TIMEOUT");
10349
+ }
10350
+ writeConfig({
10351
+ baseUrl,
10352
+ apiKey: outcome.token,
10353
+ iss: baseUrl,
10354
+ clientId: CLI_CLIENT_ID,
10355
+ sessionId: outcome.sessionId
10356
+ });
10357
+ const previousBaseUrl = previousBaseUrlOf(previous);
10358
+ if (previous !== null && previousBaseUrl === baseUrl && isCliSessionToken(previous.apiKey) && previous.apiKey !== outcome.token) {
10359
+ await revokeStoredSession(previousBaseUrl, deps, previous.apiKey);
10360
+ } else if (previous !== null && previousBaseUrl !== null && previousBaseUrl !== baseUrl) {
10361
+ deps.writeStderr(
10362
+ `The previous session of ${new URL(previousBaseUrl).host} was not revoked; revoke it from that console.`
10363
+ );
10364
+ }
10365
+ const organization = await fetchMe(
10366
+ { baseUrl, credential: outcome.token, transport: "bearer" },
10367
+ deps
10368
+ ).then((me) => organizationOf(me)).catch(() => null);
10369
+ deps.writeStdout(`Logged in to ${organization ?? "the organization"}.`);
10370
+ return 0;
10371
+ }
10372
+ function login(argv, deps) {
10373
+ const rejectedValue = argv.some((argument) => argument.startsWith("--api-key="));
10374
+ const allowed = MANUAL_FLAGS.login;
10375
+ const unknown = argv.filter((argument) => !allowed.includes(argument));
10376
+ if (rejectedValue || unknown.length > 0) {
10377
+ throw new CliError(
10378
+ "The API key must come from stdin: use `nouter-platform login --api-key` with no value."
10379
+ );
10380
+ }
10381
+ const withApiKey = argv.includes("--api-key");
10382
+ const withBrowser = argv.includes("--browser");
10383
+ const withPaste = argv.includes("--paste");
10384
+ const chosen = [withApiKey, withBrowser, withPaste].filter(Boolean).length;
10385
+ if (chosen > 1) {
10386
+ throw new CliError("Choose one way to log in: `--api-key` (from stdin), `--browser` or `--paste`.");
10387
+ }
10388
+ if (withApiKey) return loginWithApiKey(deps);
10389
+ return loginWithCode(argv, deps);
10390
+ }
10391
+ var SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
10392
+ var SESSION_IDLE_MS = 24 * 60 * 60 * 1e3;
10393
+ function isoTime(value) {
10394
+ return typeof value === "number" ? new Date(value).toISOString() : "";
10395
+ }
10396
+ function requireCliSession(auth) {
10397
+ if (!isCliSessionToken(auth.credential)) {
10398
+ throw new CliError(
10399
+ "This command needs a CLI session. Run `nouter-platform login` first; a machine key cannot manage sessions.",
10400
+ 77,
10401
+ "SESSION_REQUIRED"
10402
+ );
10403
+ }
10404
+ }
10405
+ async function currentSession(auth, deps) {
10406
+ const id = readConfig()?.sessionId;
10407
+ if (id === void 0) return null;
10408
+ try {
10409
+ const answer = await cliJsonRequest(deps, `${auth.baseUrl}/v1/oma/cli/sessions`, {
10410
+ method: "GET",
10411
+ token: auth.credential
10412
+ });
10413
+ if (answer.status !== 200) return null;
10414
+ const sessions = bodyField(answer.body, "sessions") ?? [];
10415
+ return sessions.find((session) => session.id === id) ?? null;
10416
+ } catch {
10417
+ return null;
10418
+ }
10419
+ }
10420
+ async function sessionsList(deps, json) {
10421
+ const auth = await resolveAuth(deps);
10422
+ requireCliSession(auth);
10423
+ const answer = await cliJsonRequest(deps, `${auth.baseUrl}/v1/oma/cli/sessions`, {
10424
+ method: "GET",
10425
+ token: auth.credential
10426
+ });
10427
+ if (answer.status !== 200) throw loginApiError(answer.status, answer.body, "Could not list the CLI sessions");
10428
+ const sessions = bodyField(answer.body, "sessions") ?? [];
10429
+ if (json) {
10430
+ deps.writeStdout(JSON.stringify(sessions, null, 2));
10431
+ return 0;
10432
+ }
10433
+ if (sessions.length === 0) {
10434
+ deps.writeStdout("No CLI sessions.");
10435
+ return 0;
10436
+ }
10437
+ deps.writeStdout(
10438
+ table([
10439
+ ["ID", "HOSTNAME", "MODE", "CREATED", "LAST USED", "ELEVATED UNTIL"],
10440
+ ...sessions.map((session) => [
10441
+ session.id,
10442
+ session.hostname,
10443
+ session.mode,
10444
+ isoTime(session.created_at),
10445
+ isoTime(session.last_used_at),
10446
+ isoTime(session.elevated_until)
10447
+ ])
10448
+ ])
10449
+ );
10450
+ return 0;
10451
+ }
10452
+ async function sessionsRevoke(deps, id, json) {
10453
+ const auth = await resolveAuth(deps);
10454
+ requireCliSession(auth);
10455
+ const answer = await cliJsonRequest(deps, `${auth.baseUrl}/v1/oma/cli/sessions/${encodeURIComponent(id)}`, {
10456
+ method: "DELETE",
10457
+ token: auth.credential
10458
+ });
10459
+ if (answer.status === 404) throw new CliError("CLI session not found.", 1);
10460
+ if (answer.status < 200 || answer.status >= 300) {
10461
+ throw loginApiError(answer.status, answer.body, "Could not revoke the CLI session");
8756
10462
  }
8757
- if (federationConfigured) {
8758
- const settings = federationSettingsOrNull();
8759
- if (settings !== null) {
8760
- const baseUrl = requireBaseUrl(stored);
8761
- const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
8762
- return { baseUrl, credential: token.accessToken, transport: "bearer" };
8763
- }
10463
+ if (json) {
10464
+ deps.writeStdout(JSON.stringify(answer.body, null, 2));
10465
+ return 0;
8764
10466
  }
8765
- if (!stored) {
8766
- throw new CliError("Not authenticated. Run `nouter-platform login --api-key` or set NOUTER_PLATFORM_API_KEY.");
10467
+ deps.writeStdout(`Revoked CLI session ${id}.`);
10468
+ return 0;
10469
+ }
10470
+ async function authSessionsCommand(argv, deps) {
10471
+ const [subcommand, ...args] = argv;
10472
+ if (subcommand === "list") {
10473
+ const options = parseOptions(args, specFor("auth sessions list"));
10474
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform auth sessions list [--json]");
10475
+ return sessionsList(deps, options.booleans.has("--json"));
8767
10476
  }
8768
- if (stored.baseUrl === null) {
8769
- throw new CliError(
8770
- "The stored config has no API base URL, so the key's host is unknown. Run `nouter-platform login` again against your API URL, or set NOUTER_PLATFORM_API_KEY."
8771
- );
10477
+ if (subcommand === "revoke") {
10478
+ const options = parseOptions(args, specFor("auth sessions revoke"));
10479
+ const id = options.positionals[0];
10480
+ if (id === void 0 || options.positionals.length > 1) {
10481
+ throw new CliError("Usage: nouter-platform auth sessions revoke <session-id> [--json]");
10482
+ }
10483
+ return sessionsRevoke(deps, id, options.booleans.has("--json"));
8772
10484
  }
8773
- const storedBaseUrl = normalizeBaseUrl(stored.baseUrl);
8774
- if (envBase && envBase.length > 0) {
8775
- const envBaseUrl = normalizeBaseUrl(envBase);
8776
- if (envBaseUrl !== storedBaseUrl) {
8777
- throw new CliError(
8778
- `The stored API key was saved for ${storedBaseUrl}, but NOUTER_PLATFORM_BASE_URL points to ${envBaseUrl}. Run \`nouter-platform login\` against ${envBaseUrl} to store a key for it, or set NOUTER_PLATFORM_API_KEY.`
8779
- );
10485
+ return usageError("auth sessions list|revoke <session-id>", deps);
10486
+ }
10487
+ async function elevateSession(auth, deps, choice) {
10488
+ requireCliSession(auth);
10489
+ if (choice.signal !== null) announceRemoteSession(choice.signal, deps);
10490
+ const verifier = generateCodeVerifier();
10491
+ const requestId = await startAuthorization(
10492
+ auth.baseUrl,
10493
+ deps,
10494
+ {
10495
+ code_challenge: codeChallengeFor(verifier),
10496
+ code_challenge_method: "S256",
10497
+ hostname: sanitizeHostname(hostname()),
10498
+ mode: choice.mode,
10499
+ purpose: "elevate"
10500
+ },
10501
+ auth.credential
10502
+ );
10503
+ const state = randomBytes3(32).toString("base64url");
10504
+ let code;
10505
+ if (choice.mode === "loopback") {
10506
+ const callback = await startLoginCallback({ state, timeoutMs: LOGIN_CALLBACK_TIMEOUT_MS });
10507
+ try {
10508
+ const consoleUrl = consoleUrlFor(auth.baseUrl, requestId, state, callback.callbackUrl);
10509
+ deps.writeStdout(`Open this URL to confirm it's you:
10510
+ ${consoleUrl}`);
10511
+ deps.openBrowser(consoleUrl);
10512
+ code = (await callback.waitForResult()).code;
10513
+ } catch (error) {
10514
+ if (error instanceof LoginCallbackTimeoutError) {
10515
+ throw new CliError("The elevation timed out after ten minutes. Run `nouter-platform elevate` again.", 75, "LOGIN_TIMEOUT");
10516
+ }
10517
+ throw error;
10518
+ } finally {
10519
+ await callback.close();
8780
10520
  }
8781
- return { baseUrl: envBaseUrl, credential: stored.apiKey, transport: "api-key" };
10521
+ } else {
10522
+ const consoleUrl = consoleUrlFor(auth.baseUrl, requestId, state);
10523
+ deps.writeStdout(`Open this URL to confirm it's you:
10524
+ ${consoleUrl}`);
10525
+ deps.openBrowser(consoleUrl);
10526
+ code = await awaitPastedCode(deps, state);
8782
10527
  }
8783
- return { baseUrl: storedBaseUrl, credential: stored.apiKey, transport: "api-key" };
10528
+ const outcome = await redeemCode(auth.baseUrl, deps, code, verifier);
10529
+ if (outcome.kind !== "elevated") {
10530
+ throw new CliError("The server did not elevate the session. Run `nouter-platform elevate` again.", 75, "ELEVATION_REQUIRED");
10531
+ }
10532
+ deps.writeStdout("Elevated for two hours.");
10533
+ return 0;
8784
10534
  }
8785
- function clientFor(auth, deps, options = {}) {
8786
- const common = {
8787
- baseURL: auth.baseUrl,
8788
- fetch: deps.fetch,
8789
- userAgent: USER_AGENT,
8790
- ...options.maxRetries !== void 0 && { maxRetries: options.maxRetries }
8791
- };
8792
- return auth.transport === "bearer" ? new NouterPlatform({ ...common, authToken: auth.credential }) : new NouterPlatform({ ...common, apiKey: auth.credential });
10535
+ async function elevateCommand(argv, deps) {
10536
+ const options = parseOptions(argv, specFor("elevate"));
10537
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform elevate [--browser|--paste]");
10538
+ const auth = await resolveAuth(deps);
10539
+ return elevateSession(auth, deps, resolveLoginMode(argv, loginEnvironment(deps), loginPlatform(deps)));
8793
10540
  }
8794
- function apiKeyAuth(baseUrl, apiKey) {
8795
- return { baseUrl, credential: apiKey, transport: "api-key" };
10541
+ function interactiveTerminal(deps) {
10542
+ if (deps.isInteractive !== void 0) return deps.isInteractive();
10543
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
8796
10544
  }
8797
- async function fetchMe(auth, deps) {
10545
+ async function elevatedRequest(auth, deps, request) {
10546
+ const client = clientFor(auth, deps);
8798
10547
  try {
8799
- return await clientFor(auth, deps).platform.request({
8800
- method: "get",
8801
- path: "/v1/oma/me",
8802
- signal: AbortSignal.timeout(deps.requestTimeoutMs)
8803
- });
10548
+ return await request(client);
8804
10549
  } catch (error) {
8805
- throw new CliError(`Could not read the account: ${describeApiFailure(error)}`);
10550
+ if (!isElevationRequired(error)) throw error;
10551
+ if (!interactiveTerminal(deps) || !isCliSessionToken(auth.credential)) throw elevationCliError(error);
10552
+ deps.writeStderr("This operation needs elevation; confirming it's you...");
10553
+ await elevateSession(auth, deps, resolveLoginMode([], loginEnvironment(deps), loginPlatform(deps)));
10554
+ try {
10555
+ return await request(client);
10556
+ } catch (retryError) {
10557
+ if (isElevationRequired(retryError)) throw elevationCliError(retryError);
10558
+ throw retryError;
10559
+ }
8806
10560
  }
8807
10561
  }
8808
- function organizationOf(me) {
8809
- const tenant = me.tenant ?? me.tenants?.[0];
8810
- if (!tenant) return null;
8811
- const name = tenant.name;
8812
- const id = tenant.id;
8813
- if (name && id) return `${name} (${id})`;
8814
- return name ?? id ?? null;
8815
- }
8816
- function roleOf(me) {
8817
- if (typeof me.role === "string" && me.role.length > 0) return me.role;
8818
- return me.tenants?.[0]?.role ?? null;
10562
+ function isDeadSessionBody(body) {
10563
+ const type = bodyField(bodyField(body, "error"), "type");
10564
+ return type === "SESSION_EXPIRED" || type === "SESSION_REVOKED";
8819
10565
  }
8820
- function loginBaseUrl(deps) {
10566
+ async function logoutCommand(argv, deps) {
10567
+ const options = parseOptions(argv, specFor("logout"));
10568
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform logout [--all]");
10569
+ const all = options.booleans.has("--all");
10570
+ let stored;
8821
10571
  try {
8822
- return requireBaseUrl(readConfig({ warn: deps.writeStderr }), LOGIN_BASE_URL_HINT);
10572
+ stored = readConfig();
8823
10573
  } catch (error) {
8824
- if (error instanceof CliError && !error.message.includes("NOUTER_PLATFORM_BASE_URL")) {
8825
- throw new CliError(`${error.message} ${LOGIN_BASE_URL_HINT}`);
8826
- }
10574
+ if (!(error instanceof ConfigStorageError)) throw error;
10575
+ clearConfig();
8827
10576
  throw error;
8828
10577
  }
8829
- }
8830
- async function loginWithApiKey(deps) {
8831
- const baseUrl = loginBaseUrl(deps);
8832
- const apiKey = (await deps.readStdin()).trim();
8833
- if (apiKey.length === 0) {
8834
- throw new CliError("No API key on stdin. Pipe it in: `printf '%s' \"$KEY\" | nouter-platform login --api-key`.");
10578
+ if (stored === null) {
10579
+ deps.writeStdout("No stored key.");
10580
+ return 0;
8835
10581
  }
8836
- if (!/^[\x21-\x7e]+$/.test(apiKey)) {
8837
- throw new CliError("The API key has characters the CLI cannot use. Pipe it in again.");
10582
+ let failure = null;
10583
+ let otherSessionsNotRevoked = false;
10584
+ if (stored.baseUrl !== null && isCliSessionToken(stored.apiKey)) {
10585
+ const path = all ? "/v1/oma/cli/sessions" : "/v1/oma/cli/sessions/current";
10586
+ try {
10587
+ const baseUrl = normalizeBaseUrl(stored.baseUrl);
10588
+ const answer = await cliJsonRequest(deps, `${baseUrl}${path}`, { method: "DELETE", token: stored.apiKey });
10589
+ if (answer.status === 401 && isDeadSessionBody(answer.body)) {
10590
+ if (all) otherSessionsNotRevoked = true;
10591
+ } else if (answer.status < 200 || answer.status >= 300) {
10592
+ failure = `the server answered ${answer.status}`;
10593
+ }
10594
+ } catch (error) {
10595
+ failure = error instanceof CliError ? error.message : describeApiFailure(error);
10596
+ }
8838
10597
  }
8839
- const me = await fetchMe(apiKeyAuth(baseUrl, apiKey), deps);
8840
- writeConfig({ baseUrl, apiKey });
8841
- deps.writeStdout(`Logged in to ${organizationOf(me) ?? "the organization"}.`);
10598
+ clearConfig();
10599
+ if (otherSessionsNotRevoked) {
10600
+ deps.writeStderr(
10601
+ "Your stored session had already ended, so other CLI sessions were not revoked. Revoke them in the console (Settings \u2192 Profile \u2192 CLI sessions)."
10602
+ );
10603
+ return 2;
10604
+ }
10605
+ if (failure !== null) {
10606
+ const expires = new Date(Date.now() + SESSION_TTL_MS).toISOString();
10607
+ deps.writeStderr(
10608
+ `The server session could not be revoked; it expires on ${expires} or revoke it with \`nouter-platform auth sessions revoke\`.`
10609
+ );
10610
+ return 2;
10611
+ }
10612
+ if (all && !isCliSessionToken(stored.apiKey)) {
10613
+ deps.writeStdout("Removed the stored machine key. Revoke it in the console when you no longer need it.");
10614
+ return 0;
10615
+ }
10616
+ deps.writeStdout(all ? "Logged out of every CLI session." : "Logged out.");
8842
10617
  return 0;
8843
10618
  }
8844
- async function loginWithBrowser(deps) {
8845
- const baseUrl = loginBaseUrl(deps);
8846
- const state = randomBytes(32).toString("base64url");
8847
- const callback = await startLoginCallback({ state, timeoutMs: LOGIN_CALLBACK_TIMEOUT_MS });
8848
- try {
8849
- const consoleUrl = new URL("/cli/login", baseUrl);
8850
- consoleUrl.searchParams.set("callback", callback.callbackUrl);
8851
- consoleUrl.searchParams.set("state", state);
8852
- consoleUrl.searchParams.set("hostname", hostname());
8853
- deps.writeStdout(`Open this URL to approve the login:
8854
- ${consoleUrl.toString()}`);
8855
- deps.openBrowser(consoleUrl.toString());
8856
- const delivered = await callback.waitForResult();
8857
- const me = await fetchMe(apiKeyAuth(baseUrl, delivered.token), deps);
8858
- writeConfig({ baseUrl, apiKey: delivered.token });
8859
- const organization = delivered.tenantName ?? organizationOf(me) ?? "the organization";
8860
- deps.writeStdout(`Logged in to ${organization}.`);
10619
+ async function whoamiCommand(argv, deps) {
10620
+ const options = parseOptions(argv, specFor("whoami"));
10621
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform whoami [--json]");
10622
+ const auth = await resolveAuth(deps);
10623
+ const me = await fetchMe(auth, deps);
10624
+ const session = isCliSessionToken(auth.credential) ? await currentSession(auth, deps) : null;
10625
+ const sessionView = session === null ? null : {
10626
+ id: session.id,
10627
+ mode: session.mode,
10628
+ created_at: session.created_at,
10629
+ expires_at: session.created_at + SESSION_TTL_MS,
10630
+ last_used_at: session.last_used_at,
10631
+ idle_cutoff: (session.last_used_at ?? session.created_at) + SESSION_IDLE_MS,
10632
+ elevated_until: session.elevated_until
10633
+ };
10634
+ if (options.booleans.has("--json")) {
10635
+ deps.writeStdout(JSON.stringify({ ...me, installation: auth.baseUrl, session: sessionView }, null, 2));
8861
10636
  return 0;
8862
- } finally {
8863
- await callback.close();
8864
10637
  }
8865
- }
8866
- function login(argv, deps) {
8867
- const rejectedValue = argv.some((argument) => argument.startsWith("--api-key="));
8868
- const unknown = argv.filter((argument) => argument !== "--api-key" && argument !== "--browser");
8869
- if (rejectedValue || unknown.length > 0) {
8870
- throw new CliError(
8871
- "The API key must come from stdin: use `nouter-platform login --api-key` with no value."
10638
+ printWhoami(me, deps);
10639
+ deps.writeStdout(`Installation: ${auth.baseUrl}`);
10640
+ if (sessionView !== null) {
10641
+ deps.writeStdout(`Session expires at: ${isoTime(sessionView.expires_at)}`);
10642
+ deps.writeStdout(`Idle cutoff: ${isoTime(sessionView.idle_cutoff)}`);
10643
+ deps.writeStdout(
10644
+ `Elevated until: ${sessionView.elevated_until === null ? "(not elevated)" : isoTime(sessionView.elevated_until)}`
8872
10645
  );
8873
10646
  }
8874
- const withApiKey = argv.includes("--api-key");
8875
- const withBrowser = argv.includes("--browser");
8876
- if (withApiKey && withBrowser) {
8877
- throw new CliError("Choose one way to log in: `--api-key` (from stdin) or `--browser`.");
8878
- }
8879
- if (withApiKey) return loginWithApiKey(deps);
8880
- if (withBrowser) return loginWithBrowser(deps);
8881
- throw new CliError(
8882
- "`login` needs a way to authenticate: `--api-key` (the key comes from stdin) or `--browser`."
8883
- );
10647
+ return 0;
8884
10648
  }
8885
10649
  function printWhoami(me, deps) {
8886
10650
  deps.writeStdout(`Organization: ${organizationOf(me) ?? "(none)"}`);
@@ -8888,10 +10652,6 @@ function printWhoami(me, deps) {
8888
10652
  const scopes = Array.isArray(me.scopes) ? me.scopes : [];
8889
10653
  deps.writeStdout(`Scopes: ${scopes.length > 0 ? scopes.join(", ") : "(the server does not report scopes)"}`);
8890
10654
  }
8891
- function table(rows) {
8892
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
8893
- return rows.map((row) => row.map((cell, column) => (cell ?? "").padEnd(widths[column])).join(" ").trimEnd()).join("\n");
8894
- }
8895
10655
  function modelOf(agent) {
8896
10656
  const model = agent.model;
8897
10657
  if (typeof model === "string") return model;
@@ -8987,6 +10747,271 @@ async function getEnvironment(id, deps) {
8987
10747
  throw new CliError(`Could not read environment ${id}: ${describeApiFailure(error)}`);
8988
10748
  }
8989
10749
  }
10750
+ async function collectPages(fetchPage, params) {
10751
+ const items = [];
10752
+ const seen = /* @__PURE__ */ new Set();
10753
+ let page;
10754
+ for (; ; ) {
10755
+ if (page !== void 0) params.page = page;
10756
+ const result = await fetchPage(params);
10757
+ items.push(...result.data);
10758
+ const next = result.next_page;
10759
+ if (next === null || next === void 0) return items;
10760
+ if (seen.has(next)) {
10761
+ throw new CliError("The server returned the same page cursor twice; stopped to avoid an endless loop.");
10762
+ }
10763
+ seen.add(next);
10764
+ page = next;
10765
+ }
10766
+ }
10767
+ async function listSessions(args, deps) {
10768
+ const options = parseOptions(args, specFor("sessions list"));
10769
+ if (options.positionals.length > 0) {
10770
+ throw new CliError("Usage: nouter-platform sessions list [--agent <agent-id>] [--status <status>] ...");
10771
+ }
10772
+ const agentId = lastOption(options, "--agent");
10773
+ const agentVersionRaw = lastOption(options, "--agent-version");
10774
+ let agentVersion;
10775
+ if (agentVersionRaw !== void 0) {
10776
+ if (!/^\d+$/.test(agentVersionRaw) || Number(agentVersionRaw) < 1) {
10777
+ throw new CliError("The option --agent-version must be a positive integer.");
10778
+ }
10779
+ if (agentId === void 0) throw new CliError("The option --agent-version needs --agent.");
10780
+ agentVersion = Number(agentVersionRaw);
10781
+ }
10782
+ const statuses = splitList(options.values.get("--status"));
10783
+ for (const status of statuses) {
10784
+ if (!SESSION_STATUSES.includes(status)) {
10785
+ throw new CliError(`The option --status must be one of ${SESSION_STATUSES.join(", ")}.`);
10786
+ }
10787
+ }
10788
+ const sinceRaw = lastOption(options, "--since");
10789
+ const since = sinceRaw === void 0 ? void 0 : normalizeInstant(sinceRaw, "start");
10790
+ if (sinceRaw !== void 0 && since === null) {
10791
+ throw new CliError("The option --since must be YYYY-MM-DD or RFC 3339.");
10792
+ }
10793
+ const untilRaw = lastOption(options, "--until");
10794
+ const until = untilRaw === void 0 ? void 0 : normalizeInstant(untilRaw, "end");
10795
+ if (untilRaw !== void 0 && until === null) {
10796
+ throw new CliError("The option --until must be YYYY-MM-DD or RFC 3339.");
10797
+ }
10798
+ const order = lastOption(options, "--order");
10799
+ if (order !== void 0 && order !== "asc" && order !== "desc") {
10800
+ throw new CliError("The option --order must be asc or desc.");
10801
+ }
10802
+ const params = { limit: 100 };
10803
+ if (agentId !== void 0) params.agent_id = agentId;
10804
+ if (agentVersion !== void 0) params.agent_version = agentVersion;
10805
+ const userProfileId = lastOption(options, "--user-profile");
10806
+ if (userProfileId !== void 0) params.user_profile_id = userProfileId;
10807
+ if (statuses.length > 0) params.statuses = statuses;
10808
+ if (since !== void 0 && since !== null) params["created_at[gte]"] = since;
10809
+ if (until !== void 0 && until !== null) params["created_at[lte]"] = until;
10810
+ if (order !== void 0) params.order = order;
10811
+ if (options.booleans.has("--include-archived")) params.include_archived = true;
10812
+ const auth = await resolveAuth(deps);
10813
+ try {
10814
+ const client = clientFor(auth, deps);
10815
+ const sessions = await collectPages(
10816
+ (query) => client.beta.sessions.list(query),
10817
+ params
10818
+ );
10819
+ if (options.booleans.has("--json")) {
10820
+ deps.writeStdout(JSON.stringify(sessions, null, 2));
10821
+ return 0;
10822
+ }
10823
+ if (sessions.length === 0) {
10824
+ deps.writeStdout("No sessions.");
10825
+ return 0;
10826
+ }
10827
+ deps.writeStdout(
10828
+ table([["ID", "STATUS", "AGENT", "USER", "CREATED", "COST"], ...sessions.map((session) => sessionRow(session))])
10829
+ );
10830
+ return 0;
10831
+ } catch (error) {
10832
+ if (error instanceof CliError) throw error;
10833
+ throw new CliError(`Could not list sessions: ${describeApiFailure(error)}`);
10834
+ }
10835
+ }
10836
+ async function getSession(args, deps) {
10837
+ const options = parseOptions(args, specFor("sessions get"));
10838
+ const id = options.positionals[0];
10839
+ if (id === void 0 || options.positionals.length > 1) {
10840
+ throw new CliError("Usage: nouter-platform sessions get <session-id> [--json]");
10841
+ }
10842
+ const auth = await resolveAuth(deps);
10843
+ try {
10844
+ const session = await clientFor(auth, deps).beta.sessions.retrieve(id);
10845
+ if (options.booleans.has("--json")) {
10846
+ deps.writeStdout(JSON.stringify(session, null, 2));
10847
+ return 0;
10848
+ }
10849
+ for (const line of sessionDetail(session)) deps.writeStdout(line);
10850
+ return 0;
10851
+ } catch (error) {
10852
+ if (error instanceof CliError) throw error;
10853
+ throw new CliError(`Could not read session ${id}: ${describeApiFailure(error)}`);
10854
+ }
10855
+ }
10856
+ async function listSessionEvents(args, deps) {
10857
+ const options = parseOptions(args, specFor("sessions events"));
10858
+ const id = options.positionals[0];
10859
+ if (id === void 0 || options.positionals.length > 1) {
10860
+ throw new CliError("Usage: nouter-platform sessions events <session-id> [--type <event-type>] ...");
10861
+ }
10862
+ const types = splitList(options.values.get("--type"));
10863
+ const sinceRaw = lastOption(options, "--since");
10864
+ const since = sinceRaw === void 0 ? void 0 : normalizeInstant(sinceRaw, "start");
10865
+ if (sinceRaw !== void 0 && since === null) {
10866
+ throw new CliError("The option --since must be YYYY-MM-DD or RFC 3339.");
10867
+ }
10868
+ const untilRaw = lastOption(options, "--until");
10869
+ const until = untilRaw === void 0 ? void 0 : normalizeInstant(untilRaw, "end");
10870
+ if (untilRaw !== void 0 && until === null) {
10871
+ throw new CliError("The option --until must be YYYY-MM-DD or RFC 3339.");
10872
+ }
10873
+ const order = lastOption(options, "--order") ?? "asc";
10874
+ if (order !== "asc" && order !== "desc") {
10875
+ throw new CliError("The option --order must be asc or desc.");
10876
+ }
10877
+ const params = { limit: 100, order };
10878
+ if (types.length > 0) params.types = types;
10879
+ if (since !== void 0 && since !== null) params["created_at[gte]"] = since;
10880
+ if (until !== void 0 && until !== null) params["created_at[lte]"] = until;
10881
+ const auth = await resolveAuth(deps);
10882
+ try {
10883
+ const client = clientFor(auth, deps);
10884
+ const events = await collectPages(
10885
+ (query) => client.beta.sessions.events.list(id, query),
10886
+ params
10887
+ );
10888
+ if (options.booleans.has("--json")) {
10889
+ deps.writeStdout(JSON.stringify(events, null, 2));
10890
+ return 0;
10891
+ }
10892
+ if (events.length === 0) {
10893
+ deps.writeStdout("No events.");
10894
+ return 0;
10895
+ }
10896
+ deps.writeStdout(
10897
+ table([["PROCESSED_AT", "TYPE", "ID", "SUMMARY"], ...events.map((event) => eventRow(event))])
10898
+ );
10899
+ return 0;
10900
+ } catch (error) {
10901
+ if (error instanceof CliError) throw error;
10902
+ throw new CliError(`Could not list the events of session ${id}: ${describeApiFailure(error)}`);
10903
+ }
10904
+ }
10905
+ async function sessionsCommand(argv, deps) {
10906
+ const [subcommand, ...args] = argv;
10907
+ if (subcommand === "list") return await listSessions(args, deps);
10908
+ if (subcommand === "get") return await getSession(args, deps);
10909
+ if (subcommand === "events") return await listSessionEvents(args, deps);
10910
+ return usageError("sessions list|get <session-id>|events <session-id>", deps);
10911
+ }
10912
+ async function usageCommand(argv, deps) {
10913
+ const options = parseOptions(argv, specFor("usage"));
10914
+ if (options.positionals.length > 0) {
10915
+ throw new CliError("Usage: nouter-platform usage [--days 7|30|90] [--group-by <dimension>] [--json]");
10916
+ }
10917
+ const daysRaw = lastOption(options, "--days");
10918
+ if (daysRaw !== void 0 && daysRaw !== "7" && daysRaw !== "30" && daysRaw !== "90") {
10919
+ throw new CliError("The option --days must be 7, 30 or 90.");
10920
+ }
10921
+ const sinceRaw = lastOption(options, "--since");
10922
+ const untilRaw = lastOption(options, "--until");
10923
+ const hasRange = sinceRaw !== void 0 || untilRaw !== void 0;
10924
+ if (daysRaw !== void 0 && hasRange) {
10925
+ throw new CliError("Use --days or --since/--until, not both.");
10926
+ }
10927
+ const since = sinceRaw === void 0 ? void 0 : normalizeInstant(sinceRaw, "start");
10928
+ if (since === null) {
10929
+ throw new CliError("The option --since must be YYYY-MM-DD or RFC 3339.");
10930
+ }
10931
+ const until = untilRaw === void 0 ? void 0 : normalizeInstant(untilRaw, "end");
10932
+ if (until === null) {
10933
+ throw new CliError("The option --until must be YYYY-MM-DD or RFC 3339.");
10934
+ }
10935
+ if (since !== void 0 && until !== void 0 && Date.parse(since) > Date.parse(until)) {
10936
+ throw new CliError("The option --since must not be after --until.");
10937
+ }
10938
+ const groupBy = splitList(options.values.get("--group-by"));
10939
+ const dimensions = groupBy.length === 0 ? ["day"] : groupBy;
10940
+ for (const dimension of dimensions) {
10941
+ if (!USAGE_GROUP_BY.includes(dimension)) {
10942
+ throw new CliError(`The option --group-by must be one of ${USAGE_GROUP_BY.join(", ")}.`);
10943
+ }
10944
+ }
10945
+ if (dimensions.length > 5) {
10946
+ throw new CliError("The option --group-by takes at most 5 dimensions.");
10947
+ }
10948
+ const params = {
10949
+ group_by: dimensions,
10950
+ limit: integerOption(options, "--limit", 1, 1e4) ?? 1e3
10951
+ };
10952
+ if (hasRange) {
10953
+ if (sinceRaw !== void 0) params.starting_at = sinceRaw;
10954
+ if (untilRaw !== void 0) params.ending_at = untilRaw;
10955
+ } else {
10956
+ params.days = daysRaw ?? "30";
10957
+ }
10958
+ const userProfileId = lastOption(options, "--user-profile");
10959
+ if (userProfileId !== void 0) params.user_profile_id = userProfileId;
10960
+ const page = lastOption(options, "--page");
10961
+ if (page !== void 0) params.page = page;
10962
+ const auth = await resolveAuth(deps);
10963
+ try {
10964
+ const report = await clientFor(auth, deps).platform.usage.list(params);
10965
+ const view = report;
10966
+ if (options.booleans.has("--json")) {
10967
+ deps.writeStdout(JSON.stringify(report, null, 2));
10968
+ } else {
10969
+ deps.writeStdout(usageTable(view));
10970
+ if (view.rows.some((row) => row.cost_micros !== null && row.unpriced_requests > 0)) {
10971
+ deps.writeStdout(`* partial: ${unpricedTotal(view)} requests without a price.`);
10972
+ }
10973
+ }
10974
+ if (view.next_page !== void 0 && view.next_page !== null) {
10975
+ deps.writeStderr(`Next page: ${nextPageCommand(params, view.next_page)}`);
10976
+ }
10977
+ return 0;
10978
+ } catch (error) {
10979
+ if (error instanceof CliError) throw error;
10980
+ throw new CliError(`Could not read the usage: ${describeApiFailure(error)}`);
10981
+ }
10982
+ }
10983
+ function nextPageCommand(params, cursor) {
10984
+ const parts = ["nouter-platform", "usage"];
10985
+ const groupBy = params.group_by ?? [];
10986
+ if (groupBy.length > 0 && !(groupBy.length === 1 && groupBy[0] === "day")) {
10987
+ parts.push("--group-by", groupBy.join(","));
10988
+ }
10989
+ const hasRange = params.starting_at !== void 0 || params.ending_at !== void 0;
10990
+ if (hasRange) {
10991
+ if (params.starting_at !== void 0) parts.push("--since", shellQuote(params.starting_at));
10992
+ if (params.ending_at !== void 0) parts.push("--until", shellQuote(params.ending_at));
10993
+ } else if (params.days !== void 0 && params.days !== "30") {
10994
+ parts.push("--days", params.days);
10995
+ }
10996
+ if (params.user_profile_id !== void 0) {
10997
+ parts.push("--user-profile", shellQuote(params.user_profile_id));
10998
+ }
10999
+ if (params.limit !== void 0 && params.limit !== 1e3) parts.push("--limit", String(params.limit));
11000
+ parts.push("--page", shellQuote(cursor));
11001
+ return parts.join(" ");
11002
+ }
11003
+ function shellQuote(value) {
11004
+ if (/^[A-Za-z0-9._~:@%+=,/-]+$/.test(value)) return value;
11005
+ return `'${value.replace(/'/g, "'\\''")}'`;
11006
+ }
11007
+ var MANUAL_FLAGS = {
11008
+ login: ["--api-key", "--browser", "--paste"],
11009
+ "agents list": ["--json"],
11010
+ "agents get": [],
11011
+ "environments list": ["--json"],
11012
+ "environments get": [],
11013
+ apply: ["--file", "-f", "--dry-run", "--rotate-secrets"]
11014
+ };
8990
11015
  function parseOptions(args, spec) {
8991
11016
  const values = /* @__PURE__ */ new Map();
8992
11017
  const booleans = /* @__PURE__ */ new Set();
@@ -9066,7 +11091,7 @@ function matchSummary(match) {
9066
11091
  async function serviceAccountsCommand(argv, deps) {
9067
11092
  const [subcommand, ...args] = argv;
9068
11093
  if (subcommand === "list") {
9069
- const options = parseOptions(args, { values: [], booleans: ["--include-archived", "--json"] });
11094
+ const options = parseOptions(args, specFor("service-accounts list"));
9070
11095
  if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform service-accounts list [--include-archived] [--json]");
9071
11096
  const auth = await resolveAuth(deps);
9072
11097
  try {
@@ -9103,7 +11128,7 @@ async function serviceAccountsCommand(argv, deps) {
9103
11128
  }
9104
11129
  }
9105
11130
  if (subcommand === "create") {
9106
- const options = parseOptions(args, { values: ["--name", "--organization-role"], booleans: ["--json"] });
11131
+ const options = parseOptions(args, specFor("service-accounts create"));
9107
11132
  const name = requiredOption(options, "--name");
9108
11133
  const role = requiredOption(options, "--organization-role");
9109
11134
  if (role !== "developer" && role !== "admin") {
@@ -9125,22 +11150,22 @@ async function serviceAccountsCommand(argv, deps) {
9125
11150
  }
9126
11151
  }
9127
11152
  if (subcommand === "archive") {
9128
- const options = parseOptions(args, { values: [], booleans: [] });
11153
+ const options = parseOptions(args, specFor("service-accounts archive"));
9129
11154
  const id = options.positionals[0];
9130
11155
  if (id === void 0 || options.positionals.length > 1) {
9131
11156
  throw new CliError("Usage: nouter-platform service-accounts archive <service-account-id>");
9132
11157
  }
9133
11158
  const auth = await resolveAuth(deps);
9134
11159
  try {
9135
- const account = await clientFor(auth, deps).platform.request({
11160
+ const account = await elevatedRequest(auth, deps, (client) => client.platform.request({
9136
11161
  method: "post",
9137
11162
  path: `/v1/oma/service_accounts/${id}/archive`
9138
- });
11163
+ }));
9139
11164
  deps.writeStdout(`Archived service account ${account.id}.`);
9140
11165
  return 0;
9141
11166
  } catch (error) {
9142
11167
  if (error instanceof CliError) throw error;
9143
- throw new CliError(`Could not archive service account ${id}: ${describeApiFailure(error)}`);
11168
+ throw apiFailure(error, `Could not archive service account ${id}`);
9144
11169
  }
9145
11170
  }
9146
11171
  return usageError("service-accounts list|create|archive", deps);
@@ -9148,7 +11173,7 @@ async function serviceAccountsCommand(argv, deps) {
9148
11173
  async function federationIssuersCommand(argv, deps) {
9149
11174
  const [subcommand, ...args] = argv;
9150
11175
  if (subcommand === "list") {
9151
- const options = parseOptions(args, { values: [], booleans: ["--include-archived", "--json"] });
11176
+ const options = parseOptions(args, specFor("federation issuers list"));
9152
11177
  if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform federation issuers list [--include-archived] [--json]");
9153
11178
  const auth = await resolveAuth(deps);
9154
11179
  try {
@@ -9186,10 +11211,7 @@ async function federationIssuersCommand(argv, deps) {
9186
11211
  }
9187
11212
  }
9188
11213
  if (subcommand === "create") {
9189
- const options = parseOptions(args, {
9190
- values: ["--name", "--provider", "--issuer-url", "--jwks-url", "--check-jti", "--max-token-lifetime"],
9191
- booleans: ["--json"]
9192
- });
11214
+ const options = parseOptions(args, specFor("federation issuers create"));
9193
11215
  const name = requiredOption(options, "--name");
9194
11216
  const provider = requiredOption(options, "--provider");
9195
11217
  if (provider !== "github" && provider !== "gcp" && provider !== "aws" && provider !== "custom") {
@@ -9219,22 +11241,22 @@ async function federationIssuersCommand(argv, deps) {
9219
11241
  }
9220
11242
  }
9221
11243
  if (subcommand === "archive") {
9222
- const options = parseOptions(args, { values: [], booleans: [] });
11244
+ const options = parseOptions(args, specFor("federation issuers archive"));
9223
11245
  const id = options.positionals[0];
9224
11246
  if (id === void 0 || options.positionals.length > 1) {
9225
11247
  throw new CliError("Usage: nouter-platform federation issuers archive <issuer-id>");
9226
11248
  }
9227
11249
  const auth = await resolveAuth(deps);
9228
11250
  try {
9229
- const issuer = await clientFor(auth, deps).platform.request({
11251
+ const issuer = await elevatedRequest(auth, deps, (client) => client.platform.request({
9230
11252
  method: "post",
9231
11253
  path: `/v1/oma/federation_issuers/${id}/archive`
9232
- });
11254
+ }));
9233
11255
  deps.writeStdout(`Archived federation issuer ${issuer.id}.`);
9234
11256
  return 0;
9235
11257
  } catch (error) {
9236
11258
  if (error instanceof CliError) throw error;
9237
- throw new CliError(`Could not archive federation issuer ${id}: ${describeApiFailure(error)}`);
11259
+ throw apiFailure(error, `Could not archive federation issuer ${id}`);
9238
11260
  }
9239
11261
  }
9240
11262
  return usageError("federation issuers list|create|archive", deps);
@@ -9242,10 +11264,7 @@ async function federationIssuersCommand(argv, deps) {
9242
11264
  async function federationRulesCommand(argv, deps) {
9243
11265
  const [subcommand, ...args] = argv;
9244
11266
  if (subcommand === "list") {
9245
- const options = parseOptions(args, {
9246
- values: ["--issuer"],
9247
- booleans: ["--include-archived", "--json"]
9248
- });
11267
+ const options = parseOptions(args, specFor("federation rules list"));
9249
11268
  if (options.positionals.length > 0) {
9250
11269
  throw new CliError("Usage: nouter-platform federation rules list [--issuer <issuer-id>] [--include-archived] [--json]");
9251
11270
  }
@@ -9288,20 +11307,7 @@ async function federationRulesCommand(argv, deps) {
9288
11307
  }
9289
11308
  }
9290
11309
  if (subcommand === "create") {
9291
- const options = parseOptions(args, {
9292
- values: [
9293
- "--name",
9294
- "--issuer",
9295
- "--service-account",
9296
- "--subject-prefix",
9297
- "--audience",
9298
- "--claim",
9299
- "--workspace",
9300
- "--scopes",
9301
- "--token-lifetime"
9302
- ],
9303
- booleans: ["--all-workspaces", "--json"]
9304
- });
11310
+ const options = parseOptions(args, specFor("federation rules create"));
9305
11311
  const name = requiredOption(options, "--name");
9306
11312
  const issuerId = requiredOption(options, "--issuer");
9307
11313
  const serviceAccountId = requiredOption(options, "--service-account");
@@ -9358,28 +11364,28 @@ async function federationRulesCommand(argv, deps) {
9358
11364
  }
9359
11365
  }
9360
11366
  if (subcommand === "archive") {
9361
- const options = parseOptions(args, { values: [], booleans: [] });
11367
+ const options = parseOptions(args, specFor("federation rules archive"));
9362
11368
  const id = options.positionals[0];
9363
11369
  if (id === void 0 || options.positionals.length > 1) {
9364
11370
  throw new CliError("Usage: nouter-platform federation rules archive <rule-id>");
9365
11371
  }
9366
11372
  const auth = await resolveAuth(deps);
9367
11373
  try {
9368
- const rule = await clientFor(auth, deps).platform.request({
11374
+ const rule = await elevatedRequest(auth, deps, (client) => client.platform.request({
9369
11375
  method: "post",
9370
11376
  path: `/v1/oma/federation_rules/${id}/archive`
9371
- });
11377
+ }));
9372
11378
  deps.writeStdout(`Archived federation rule ${rule.id}.`);
9373
11379
  return 0;
9374
11380
  } catch (error) {
9375
11381
  if (error instanceof CliError) throw error;
9376
- throw new CliError(`Could not archive federation rule ${id}: ${describeApiFailure(error)}`);
11382
+ throw apiFailure(error, `Could not archive federation rule ${id}`);
9377
11383
  }
9378
11384
  }
9379
11385
  return usageError("federation rules list|create|archive", deps);
9380
11386
  }
9381
11387
  async function federationTokenCommand(argv, deps) {
9382
- const options = parseOptions(argv, { values: [], booleans: ["--json"] });
11388
+ const options = parseOptions(argv, specFor("federation token"));
9383
11389
  if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform federation token [--json]");
9384
11390
  const settings = federationSettingsOrNull();
9385
11391
  if (settings === null) {
@@ -9387,7 +11393,7 @@ async function federationTokenCommand(argv, deps) {
9387
11393
  "The federation is not configured: set NOUTER_PLATFORM_FEDERATION_RULE_ID, NOUTER_PLATFORM_ORGANIZATION_ID and NOUTER_PLATFORM_IDENTITY_TOKEN or NOUTER_PLATFORM_IDENTITY_TOKEN_FILE."
9388
11394
  );
9389
11395
  }
9390
- const stored = readConfig({ warn: deps.writeStderr });
11396
+ const stored = readConfig();
9391
11397
  const baseUrl = requireBaseUrl(stored);
9392
11398
  const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
9393
11399
  if (options.booleans.has("--json")) {
@@ -9409,7 +11415,7 @@ async function federationTokenCommand(argv, deps) {
9409
11415
  return 0;
9410
11416
  }
9411
11417
  function authStatus(deps) {
9412
- const stored = readConfig({ warn: deps.writeStderr });
11418
+ const stored = readConfig();
9413
11419
  const envKey = environmentApiKey();
9414
11420
  const rule = process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID;
9415
11421
  const organization = process.env.NOUTER_PLATFORM_ORGANIZATION_ID;
@@ -9472,16 +11478,17 @@ async function applyCommand(argv, deps) {
9472
11478
  const inputs = [];
9473
11479
  let dryRun = false;
9474
11480
  let rotateSecrets = false;
11481
+ const [fileFlag, shortFileFlag, dryRunFlag, rotateSecretsFlag] = MANUAL_FLAGS.apply;
9475
11482
  for (let index = 0; index < argv.length; index += 1) {
9476
11483
  const argument = argv[index];
9477
- if (argument === "-f" || argument === "--file") {
11484
+ if (argument === shortFileFlag || argument === fileFlag) {
9478
11485
  const input = argv[index + 1];
9479
11486
  if (input === void 0 || input.startsWith("-")) return applyUsage(deps);
9480
11487
  inputs.push(input);
9481
11488
  index += 1;
9482
- } else if (argument === "--dry-run") {
11489
+ } else if (argument === dryRunFlag) {
9483
11490
  dryRun = true;
9484
- } else if (argument === "--rotate-secrets") {
11491
+ } else if (argument === rotateSecretsFlag) {
9485
11492
  rotateSecrets = true;
9486
11493
  } else {
9487
11494
  return applyUsage(deps);
@@ -9504,6 +11511,7 @@ async function applyCommand(argv, deps) {
9504
11511
  environments: await client.listEnvironments()
9505
11512
  };
9506
11513
  } catch (error) {
11514
+ if (error instanceof CliError) throw error;
9507
11515
  throw new CliError(`Could not read the current agents and environments: ${describeApiFailure(error)}`);
9508
11516
  }
9509
11517
  let plan;
@@ -9527,15 +11535,24 @@ function printHelp(deps) {
9527
11535
  "Usage: nouter-platform <command> [options]",
9528
11536
  "",
9529
11537
  "Commands:",
9530
- " login --api-key (key from stdin) or --browser",
9531
- " logout Remove the stored API key (local only; revoke it in the console)",
9532
- " whoami Show the organization, role and scopes",
9533
- " auth status: show which credential the CLI would use",
11538
+ " login Log in through the browser or a pasted code, or store an API key (--api-key)",
11539
+ " logout Revoke the CLI session and remove the stored credential (--all: every session)",
11540
+ " whoami Show the organization, role and scopes (--json)",
11541
+ " auth status | sessions list|revoke <session-id>",
11542
+ " version Show the CLI version and the SDK version it ships",
9534
11543
  " agents list | get <agent-id>",
9535
11544
  " environments list | get <environment-id>",
11545
+ " sessions list | get <session-id> | events <session-id>",
11546
+ " usage Show the usage and the cost by day, model, agent, person or session",
9536
11547
  " service-accounts list | create | archive",
9537
11548
  " federation issuers list|create|archive | rules list|create|archive | token",
11549
+ " elevate Confirm it's you for two hours (--browser | --paste)",
9538
11550
  " apply Apply agents and environments from files",
11551
+ ...feedbackHelpLines(),
11552
+ "",
11553
+ "Options:",
11554
+ " -h, --help Show this help",
11555
+ " -v, --version Show the version",
9539
11556
  "",
9540
11557
  "Environment:",
9541
11558
  " NOUTER_PLATFORM_API_KEY API key; wins over the stored key and the federation",
@@ -9549,6 +11566,35 @@ function printHelp(deps) {
9549
11566
  ].join("\n")
9550
11567
  );
9551
11568
  }
11569
+ function manifestAt(path) {
11570
+ try {
11571
+ return JSON.parse(readFileSync4(path, "utf8"));
11572
+ } catch {
11573
+ return null;
11574
+ }
11575
+ }
11576
+ function cliVersion() {
11577
+ return manifestAt(fileURLToPath(new URL("../package.json", import.meta.url)))?.version ?? "unknown";
11578
+ }
11579
+ function sdkVersion() {
11580
+ let directory;
11581
+ try {
11582
+ directory = dirname(fileURLToPath(import.meta.resolve("@nouter/platform")));
11583
+ } catch {
11584
+ return "unknown";
11585
+ }
11586
+ for (let depth = 0; depth < 8; depth += 1) {
11587
+ const manifest = manifestAt(join3(directory, "package.json"));
11588
+ if (manifest?.name === "@nouter/platform" && typeof manifest.version === "string") return manifest.version;
11589
+ const parent = dirname(directory);
11590
+ if (parent === directory) break;
11591
+ directory = parent;
11592
+ }
11593
+ return "unknown";
11594
+ }
11595
+ function versionLine() {
11596
+ return `nouter-platform-cli ${cliVersion()} (sdk ${sdkVersion()})`;
11597
+ }
9552
11598
  function usageError(command, deps) {
9553
11599
  deps.writeStderr(`Usage: nouter-platform ${command} ...`);
9554
11600
  return 1;
@@ -9559,35 +11605,48 @@ async function dispatch(argv, deps) {
9559
11605
  printHelp(deps);
9560
11606
  return 0;
9561
11607
  }
11608
+ if (command === "--version" || command === "-v") {
11609
+ deps.writeStdout(versionLine());
11610
+ return 0;
11611
+ }
9562
11612
  switch (command) {
9563
11613
  case "login":
9564
11614
  return await login(rest, deps);
9565
11615
  case "logout":
9566
- deps.writeStdout(clearConfig() ? "Logged out." : "No stored key.");
9567
- return 0;
9568
- case "whoami": {
9569
- const auth = await resolveAuth(deps);
9570
- printWhoami(await fetchMe(auth, deps), deps);
9571
- return 0;
9572
- }
11616
+ return await logoutCommand(rest, deps);
11617
+ case "whoami":
11618
+ return await whoamiCommand(rest, deps);
11619
+ case "elevate":
11620
+ return await elevateCommand(rest, deps);
9573
11621
  case "agents": {
9574
11622
  const [subcommand, ...args] = rest;
9575
- const json = args.includes("--json") || rest.includes("--json");
11623
+ const jsonFlag = MANUAL_FLAGS["agents list"][0];
11624
+ const json = subcommand === "list" && (args.includes(jsonFlag) || rest.includes(jsonFlag));
9576
11625
  if (subcommand === "list") return await listAgents(deps, json);
9577
11626
  if (subcommand === "get" && args[0]) return await getAgent(args[0], deps);
9578
11627
  return usageError("agents list|get <agent-id>", deps);
9579
11628
  }
9580
11629
  case "environments": {
9581
11630
  const [subcommand, ...args] = rest;
9582
- const json = args.includes("--json") || rest.includes("--json");
11631
+ const jsonFlag = MANUAL_FLAGS["environments list"][0];
11632
+ const json = subcommand === "list" && (args.includes(jsonFlag) || rest.includes(jsonFlag));
9583
11633
  if (subcommand === "list") return await listEnvironments(deps, json);
9584
11634
  if (subcommand === "get" && args[0]) return await getEnvironment(args[0], deps);
9585
11635
  return usageError("environments list|get <environment-id>", deps);
9586
11636
  }
9587
11637
  case "auth": {
9588
11638
  if (rest.length === 1 && rest[0] === "status") return authStatus(deps);
9589
- return usageError("auth status", deps);
9590
- }
11639
+ if (rest[0] === "sessions") return await authSessionsCommand(rest.slice(1), deps);
11640
+ return usageError("auth status | sessions list|revoke <session-id>", deps);
11641
+ }
11642
+ case "sessions":
11643
+ return await sessionsCommand(rest, deps);
11644
+ case "usage":
11645
+ return await usageCommand(rest, deps);
11646
+ case "version":
11647
+ if (rest.length > 0) return usageError("version", deps);
11648
+ deps.writeStdout(versionLine());
11649
+ return 0;
9591
11650
  case "service-accounts":
9592
11651
  return await serviceAccountsCommand(rest, deps);
9593
11652
  case "federation": {
@@ -9599,26 +11658,78 @@ async function dispatch(argv, deps) {
9599
11658
  }
9600
11659
  case "apply":
9601
11660
  return await applyCommand(rest, deps);
11661
+ case "feedback":
11662
+ return await feedbackCommand(rest, {
11663
+ CliError,
11664
+ resolveAuth: () => resolveAuth(deps),
11665
+ userAgent: cliUserAgent(),
11666
+ writeStdout: deps.writeStdout,
11667
+ writeStderr: deps.writeStderr,
11668
+ fetch: deps.fetch,
11669
+ requestTimeoutMs: deps.requestTimeoutMs
11670
+ });
9602
11671
  default:
9603
11672
  deps.writeStderr(`Unknown command: ${command}`);
9604
11673
  deps.writeStderr("Run `nouter-platform --help` for the command list.");
9605
11674
  return 1;
9606
11675
  }
9607
11676
  }
11677
+ async function readAllStdin() {
11678
+ const chunks = [];
11679
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
11680
+ return Buffer.concat(chunks).toString("utf8");
11681
+ }
11682
+ async function readSecretFromTty() {
11683
+ const stdin = process.stdin;
11684
+ if (!stdin.isTTY) return await readAllStdin();
11685
+ return await new Promise((resolve) => {
11686
+ const wasRaw = Boolean(stdin.isRaw);
11687
+ stdin.setRawMode(true);
11688
+ stdin.resume();
11689
+ stdin.setEncoding("utf8");
11690
+ let value = "";
11691
+ const settle = (result) => {
11692
+ stdin.setRawMode(wasRaw);
11693
+ stdin.pause();
11694
+ stdin.removeListener("data", onData);
11695
+ process.stdout.write("\n");
11696
+ resolve(result);
11697
+ };
11698
+ const onData = (chunk) => {
11699
+ for (const char of chunk) {
11700
+ if (char === "\r" || char === "\n") {
11701
+ settle(value);
11702
+ return;
11703
+ }
11704
+ if (char === "") {
11705
+ stdin.setRawMode(wasRaw);
11706
+ stdin.pause();
11707
+ process.exit(130);
11708
+ }
11709
+ if (char === "\x7F") {
11710
+ value = value.slice(0, -1);
11711
+ continue;
11712
+ }
11713
+ value += char;
11714
+ }
11715
+ };
11716
+ stdin.on("data", onData);
11717
+ });
11718
+ }
9608
11719
  function defaultDependencies() {
9609
11720
  return {
9610
11721
  writeStdout: (text) => process.stdout.write(`${text}
9611
11722
  `),
9612
11723
  writeStderr: (text) => process.stderr.write(`${text}
9613
11724
  `),
9614
- readStdin: async () => {
9615
- const chunks = [];
9616
- for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
9617
- return Buffer.concat(chunks).toString("utf8");
9618
- },
11725
+ readStdin: readAllStdin,
11726
+ readSecret: readSecretFromTty,
9619
11727
  fetch: globalThis.fetch,
9620
11728
  openBrowser: openInBrowser,
9621
- requestTimeoutMs: REQUEST_TIMEOUT_MS
11729
+ requestTimeoutMs: REQUEST_TIMEOUT_MS,
11730
+ env: process.env,
11731
+ platform: process.platform,
11732
+ isInteractive: () => Boolean(process.stdin.isTTY && process.stdout.isTTY)
9622
11733
  };
9623
11734
  }
9624
11735
  function openInBrowser(url, options = {}) {
@@ -9658,19 +11769,33 @@ function scrubArgv() {
9658
11769
  }
9659
11770
  async function main(argv, overrides = {}) {
9660
11771
  const deps = { ...defaultDependencies(), ...overrides };
11772
+ const json = argv.includes("--json");
11773
+ const reportError = (message, code) => {
11774
+ if (json) {
11775
+ const envelope = { error: { message } };
11776
+ if (code !== void 0) envelope.error.code = code;
11777
+ deps.writeStderr(JSON.stringify(envelope));
11778
+ } else {
11779
+ deps.writeStderr(message);
11780
+ }
11781
+ };
9661
11782
  scrubArgv();
9662
11783
  try {
9663
11784
  return await dispatch(argv, deps);
9664
11785
  } catch (error) {
9665
11786
  if (error instanceof LoginAccessDeniedError) {
9666
- deps.writeStderr(error.message);
11787
+ reportError(error.message);
9667
11788
  return 1;
9668
11789
  }
11790
+ if (error instanceof ConfigStorageError) {
11791
+ reportError(error.message, error.code);
11792
+ return error.exitCode;
11793
+ }
9669
11794
  if (error instanceof CliError) {
9670
- deps.writeStderr(error.message);
11795
+ reportError(error.message, error.code);
9671
11796
  return error.exitCode;
9672
11797
  }
9673
- deps.writeStderr(error.message || "Unexpected error.");
11798
+ reportError(error.message || "Unexpected error.");
9674
11799
  return 1;
9675
11800
  }
9676
11801
  }