kenso 0.1.45 → 0.1.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kenso.js CHANGED
@@ -531,15 +531,21 @@ var init_http = __esm({
531
531
  return { status: res.status, body: parsed2, headers: res.headers, requestId };
532
532
  }
533
533
  }
534
- /** Follows pagination.nextCursor while pagination.hasMore and yields every data[] item. */
534
+ /**
535
+ * Follows pagination.nextCursor while pagination.hasMore and yields every data[] item. The cursor goes in the query
536
+ * string, or with `cursorIn: "body"` (a POST search) in the JSON body beside the request's own keys.
537
+ */
535
538
  async *paginate(req, opts) {
536
539
  const seen = /* @__PURE__ */ new Set();
540
+ const inBody = opts?.cursorIn === "body";
537
541
  let cursor2;
538
542
  for (; ; ) {
539
543
  const query = { ...req.query };
540
544
  if (opts?.pageSize !== void 0) query.limit = opts.pageSize;
541
- if (cursor2 !== void 0) query.cursor = cursor2;
542
- const res = await this.request({ ...req, query });
545
+ if (cursor2 !== void 0 && !inBody) query.cursor = cursor2;
546
+ const page = { ...req, query };
547
+ if (cursor2 !== void 0 && inBody) page.body = { ...asRecord2(req.body), cursor: cursor2 };
548
+ const res = await this.request(page);
543
549
  const body = res.body;
544
550
  if (Array.isArray(body)) {
545
551
  yield* body;
@@ -2413,7 +2419,7 @@ var VERSION;
2413
2419
  var init_version = __esm({
2414
2420
  "src/core/version.ts"() {
2415
2421
  "use strict";
2416
- VERSION = true ? "0.1.45" : "0.0.0-dev";
2422
+ VERSION = true ? "0.1.47" : "0.0.0-dev";
2417
2423
  }
2418
2424
  });
2419
2425
 
@@ -2668,6 +2674,11 @@ var init_confirm = __esm({
2668
2674
 
2669
2675
  // src/core/input.ts
2670
2676
  import { readFile } from "node:fs/promises";
2677
+ function fileUnreadable(path, err, field = "file", hintOverride) {
2678
+ const code = err?.code;
2679
+ const [message, hint] = code === "ENOENT" ? [`${path} does not exist.`, "Check the name and the folder: a relative path starts in the current folder."] : code === "EISDIR" ? [`${path} is a folder.`, "Name a file inside it."] : code === "EACCES" || code === "EPERM" ? [`No permission to read ${path}.`, "Check the file's permissions, or copy it somewhere you can read."] : [`Cannot read ${path}${code ? ` (${code})` : ""}.`, "Check that the file exists and that you can open it."];
2680
+ return new KensoError({ code: "file_unreadable", message, exitCode: ExitCode.Usage, field, hint: hintOverride ?? hint });
2681
+ }
2671
2682
  async function readStream(stream, maxBytes = DEFAULT_MAX_BYTES) {
2672
2683
  const chunks = [];
2673
2684
  let size = 0;
@@ -2692,13 +2703,7 @@ async function readDataArg(value, stdin) {
2692
2703
  try {
2693
2704
  text3 = await readFile(path, "utf8");
2694
2705
  } catch (err) {
2695
- const code = err.code;
2696
- throw new KensoError({
2697
- code: "file_unreadable",
2698
- message: `Cannot read ${path}${code ? ` (${code})` : ""}.`,
2699
- exitCode: ExitCode.Usage,
2700
- field: "file"
2701
- });
2706
+ throw fileUnreadable(path, err);
2702
2707
  }
2703
2708
  } else {
2704
2709
  source = "the inline value";
@@ -2723,6 +2728,74 @@ var init_input = __esm({
2723
2728
  }
2724
2729
  });
2725
2730
 
2731
+ // src/core/secret-flags.ts
2732
+ import { readFile as readFile2 } from "node:fs/promises";
2733
+ function isSecretFlag(name, type) {
2734
+ return type === "string" && SECRET_NAME.test(name);
2735
+ }
2736
+ function readValue(flag, source, text3) {
2737
+ const value = text3.replace(/\r?\n$/, "");
2738
+ if (value === "") throw usageError(`--${flag} read nothing from ${source}.`, { field: flag, hint: `Put the value in ${source}, or pass env:NAME.` });
2739
+ return value;
2740
+ }
2741
+ function checkSecretSources(flags, secretFlags) {
2742
+ const fromStdin = secretFlags.filter((flag) => flags[flag] === "-");
2743
+ if (fromStdin.length > 0 && flags.each !== void 0) {
2744
+ throw usageError(`--each cannot read --${fromStdin[0]} from stdin: a resumed run could not read it again.`, { field: fromStdin[0], hint: OTHER_FORMS });
2745
+ }
2746
+ const readers = [...fromStdin, ...flags.data === "-" ? ["data"] : []].map((flag) => `--${flag}`);
2747
+ if (readers.length > 1) throw usageError(`Only one flag can read stdin, and ${readers.join(" and ")} both pass -.`, { field: fromStdin[0], hint: OTHER_FORMS });
2748
+ }
2749
+ async function readSecretFlag(ctx, flag, raw) {
2750
+ if (raw === "-") {
2751
+ const stdin = ctx.stdin ?? process.stdin;
2752
+ if (stdin.isTTY === true) {
2753
+ throw usageError(`--${flag} - reads stdin, but stdin is a terminal.`, { field: flag, hint: `Pipe the value in: printf '%s' "$VALUE" | kenso ... --${flag} -. Or pass @file or env:NAME.` });
2754
+ }
2755
+ return readValue(flag, "stdin", await readStream(stdin));
2756
+ }
2757
+ if (raw.startsWith("@") && !raw.startsWith("@@") && raw.length > 1) {
2758
+ const path = raw.slice(1);
2759
+ let text3;
2760
+ try {
2761
+ text3 = await readFile2(path, "utf8");
2762
+ } catch (err) {
2763
+ throw fileUnreadable(path, err, flag, `--${flag} @path reads a file. A value that itself starts with @ is written @@, for example @@Spring2026.`);
2764
+ }
2765
+ return readValue(flag, path, text3);
2766
+ }
2767
+ if (raw.startsWith("env:") && raw.length > 4) {
2768
+ const name = raw.slice(4);
2769
+ const value = ctx.env[name];
2770
+ if (!value) {
2771
+ throw usageError(`--${flag} reads the environment variable ${name}, which is not set or is empty.`, {
2772
+ field: flag,
2773
+ hint: `Set ${name} first, or pass the value with - (stdin) or @file.`
2774
+ });
2775
+ }
2776
+ return value;
2777
+ }
2778
+ ctx.output.warn(`--${flag} typed on the command line lands in shell history. Next time pass - (stdin), @file or env:NAME.`);
2779
+ return raw.startsWith("@@") ? raw.slice(1) : raw;
2780
+ }
2781
+ function maskSecrets(body, secrets) {
2782
+ if (secrets.size === 0 || body === null || typeof body !== "object" || Array.isArray(body)) return body;
2783
+ const out = { ...body };
2784
+ for (const key of secrets) if (typeof out[key] === "string") out[key] = "***";
2785
+ return out;
2786
+ }
2787
+ var SECRET_NAME, SECRET_HELP, OTHER_FORMS;
2788
+ var init_secret_flags = __esm({
2789
+ "src/core/secret-flags.ts"() {
2790
+ "use strict";
2791
+ init_errors();
2792
+ init_input();
2793
+ SECRET_NAME = /(^|-)(password|secret|token|api-key)$/;
2794
+ SECRET_HELP = "Pass -, @file or env:NAME to keep it out of shell history.";
2795
+ OTHER_FORMS = "Pass it as @file or env:NAME instead.";
2796
+ }
2797
+ });
2798
+
2726
2799
  // node_modules/.pnpm/csv-stringify@6.9.0/node_modules/csv-stringify/lib/utils/get.js
2727
2800
  var charCodeOfDot, reEscapeChar, rePropName, reIsDeepProp, reIsPlainProp, getTag, isSymbol, isKey, stringToPath, castPath, toKey, get;
2728
2801
  var init_get = __esm({
@@ -3428,7 +3501,7 @@ var init_sync = __esm({
3428
3501
  // src/batch/results.ts
3429
3502
  import { createHash } from "node:crypto";
3430
3503
  import { readFileSync as readFileSync4 } from "node:fs";
3431
- import { readFile as readFile2 } from "node:fs/promises";
3504
+ import { readFile as readFile3 } from "node:fs/promises";
3432
3505
  import { join as join3 } from "node:path";
3433
3506
  function filesOf(dir) {
3434
3507
  return {
@@ -3478,7 +3551,7 @@ async function readResults(path) {
3478
3551
  const results = /* @__PURE__ */ new Map();
3479
3552
  let text3;
3480
3553
  try {
3481
- text3 = await readFile2(path, "utf8");
3554
+ text3 = await readFile3(path, "utf8");
3482
3555
  } catch {
3483
3556
  return results;
3484
3557
  }
@@ -3556,7 +3629,7 @@ var init_results = __esm({
3556
3629
  // src/batch/runs.ts
3557
3630
  import { randomBytes } from "node:crypto";
3558
3631
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync2 } from "node:fs";
3559
- import { readdir, readFile as readFile3, realpath, rename, unlink, writeFile } from "node:fs/promises";
3632
+ import { readdir, readFile as readFile4, realpath, rename, unlink, writeFile } from "node:fs/promises";
3560
3633
  import { join as join4, resolve } from "node:path";
3561
3634
  function runsRoot(env = process.env) {
3562
3635
  const override2 = env.KENSO_RUNS_DIR?.trim();
@@ -3622,7 +3695,7 @@ async function writeRunRecord(record) {
3622
3695
  await writeJsonAtomic(join4(dir, "run.json"), rest);
3623
3696
  }
3624
3697
  async function readJson(path) {
3625
- return JSON.parse(await readFile3(path, "utf8"));
3698
+ return JSON.parse(await readFile4(path, "utf8"));
3626
3699
  }
3627
3700
  function asRecord3(value) {
3628
3701
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -5938,7 +6011,7 @@ var init_sync2 = __esm({
5938
6011
 
5939
6012
  // src/batch/input.ts
5940
6013
  import { createHash as createHash2 } from "node:crypto";
5941
- import { readFile as readFile4, stat } from "node:fs/promises";
6014
+ import { readFile as readFile5, stat } from "node:fs/promises";
5942
6015
  import { extname, resolve as resolve3 } from "node:path";
5943
6016
  function tooLarge(source) {
5944
6017
  return usageError(`${source} is larger than 200 MB, the most the CLI reads in one run.`, {
@@ -5963,18 +6036,12 @@ async function readRaw(pathOrDash, stdin) {
5963
6036
  const path = resolve3(pathOrDash);
5964
6037
  try {
5965
6038
  const info = await stat(path);
5966
- if (info.isDirectory()) throw usageError(`${pathOrDash} is a directory, not a file.`, { field: "file" });
6039
+ if (info.isDirectory()) throw fileUnreadable(pathOrDash, { code: "EISDIR" });
5967
6040
  if (info.size > MAX_INPUT_BYTES) throw tooLarge(pathOrDash);
5968
- return { path, bytes: await readFile4(path) };
6041
+ return { path, bytes: await readFile5(path) };
5969
6042
  } catch (err) {
5970
6043
  if (err instanceof KensoError) throw err;
5971
- const code = err.code;
5972
- throw new KensoError({
5973
- code: "file_unreadable",
5974
- message: `Cannot read ${pathOrDash}${code ? ` (${code})` : ""}.`,
5975
- exitCode: ExitCode.Usage,
5976
- field: "file"
5977
- });
6044
+ throw fileUnreadable(pathOrDash, err);
5978
6045
  }
5979
6046
  }
5980
6047
  function stripBom(text3) {
@@ -5986,6 +6053,9 @@ function detectFormat(path, text3) {
5986
6053
  if (ext === ".jsonl" || ext === ".ndjson") return "jsonl";
5987
6054
  return stripBom(text3).trimStart().startsWith("{") ? "jsonl" : "csv";
5988
6055
  }
6056
+ function badFile(message, hint) {
6057
+ return new KensoError({ code: "file_unreadable", message, exitCode: ExitCode.Usage, field: "file", hint });
6058
+ }
5989
6059
  function parseCsv(text3, source) {
5990
6060
  let headers = [];
5991
6061
  let records;
@@ -6001,10 +6071,10 @@ function parseCsv(text3, source) {
6001
6071
  trim: false
6002
6072
  });
6003
6073
  } catch (err) {
6004
- const line = err.lines;
6005
- throw usageError(`${source} is not valid CSV${line ? ` (line ${line})` : ""}: ${err instanceof Error ? err.message : String(err)}`, {
6006
- field: "file"
6007
- });
6074
+ const { code, lines } = err;
6075
+ const where = lines ? `${source} line ${lines}` : source;
6076
+ const problem = code ? CSV_PROBLEMS[code] : void 0;
6077
+ throw badFile(problem ? `${where}: ${problem}.` : `${where} is not valid CSV.`, "Check the quotes and commas there, or export the sheet again as CSV.");
6008
6078
  }
6009
6079
  const rows = records.map((record) => {
6010
6080
  const row = {};
@@ -6024,11 +6094,11 @@ function parseJsonl(text3, source) {
6024
6094
  let value;
6025
6095
  try {
6026
6096
  value = JSON.parse(line);
6027
- } catch (err) {
6028
- throw usageError(`${source} line ${i + 1} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, { field: "file" });
6097
+ } catch {
6098
+ throw badFile(`${source} line ${i + 1} is not valid JSON.`, 'JSONL needs one complete JSON object per line, such as {"email":"a@b.co"}.');
6029
6099
  }
6030
6100
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
6031
- throw usageError(`${source} line ${i + 1} is not a JSON object. JSONL needs one object per line.`, { field: "file" });
6101
+ throw badFile(`${source} line ${i + 1} is not a JSON object.`, 'JSONL needs one complete JSON object per line, such as {"email":"a@b.co"}.');
6032
6102
  }
6033
6103
  for (const key of Object.keys(value)) {
6034
6104
  if (!seen.has(key)) {
@@ -6089,14 +6159,24 @@ async function readIds(pathOrDash, opts) {
6089
6159
  }
6090
6160
  return ids2;
6091
6161
  }
6092
- var MAX_INPUT_BYTES;
6162
+ var MAX_INPUT_BYTES, CSV_PROBLEMS;
6093
6163
  var init_input2 = __esm({
6094
6164
  "src/batch/input.ts"() {
6095
6165
  "use strict";
6096
6166
  init_sync2();
6097
6167
  init_errors();
6098
6168
  init_exit_codes();
6169
+ init_input();
6099
6170
  MAX_INPUT_BYTES = 200 * 1024 * 1024;
6171
+ CSV_PROBLEMS = {
6172
+ CSV_QUOTE_NOT_CLOSED: "a quote is not closed",
6173
+ CSV_INVALID_CLOSING_QUOTE: "a quoted cell has more text after its closing quote",
6174
+ CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE: "a quoted cell has more text after its closing quote",
6175
+ CSV_RECORD_INCONSISTENT_COLUMNS: "the row has a different number of cells than the header",
6176
+ CSV_RECORD_INCONSISTENT_FIELDS_LENGTH: "the row has a different number of cells than the header",
6177
+ CSV_OPTION_COLUMNS_MISSING_NAME: "a header cell is empty",
6178
+ CSV_MAX_RECORD_SIZE: "the row is too long"
6179
+ };
6100
6180
  }
6101
6181
  });
6102
6182
 
@@ -6216,18 +6296,18 @@ async function sendRow(item, ctx) {
6216
6296
  return { results: [{ row: item.row, status, reason: code, error }] };
6217
6297
  }
6218
6298
  }
6219
- function preview(request) {
6299
+ function preview(request, op) {
6220
6300
  if (!request) return void 0;
6221
6301
  return {
6222
6302
  method: request.method,
6223
6303
  path: request.path,
6224
6304
  ...request.query ? { query: request.query } : {},
6225
- ...request.body !== void 0 ? { body: request.body } : {},
6305
+ ...request.body !== void 0 ? { body: maskSecrets(request.body, new Set(secretParams(op).map((s) => s.name))) } : {},
6226
6306
  ...request.form ? { form: [...request.form.keys()] } : {}
6227
6307
  };
6228
6308
  }
6229
6309
  async function runEach(ctx, op, values, file, opts = {}) {
6230
- const args = eachArgs(op, values, file);
6310
+ const args = eachArgs(op, opts.argValues ?? values, file);
6231
6311
  const applyCommand = commandLine(op, args, ctx, ["--yes"]);
6232
6312
  if (op.method !== "GET" && ctx.flags.yes !== true && ctx.flags.dryRun !== true) {
6233
6313
  throw usageError(`--each sends one ${op.method} per row: add --yes to send them, or --dry-run to see the plan first.`, { field: "yes", next: applyCommand });
@@ -6259,7 +6339,7 @@ async function runEach(ctx, op, values, file, opts = {}) {
6259
6339
  execChunk: (chunk, chunkCtx) => sendRow(chunk[0], chunkCtx),
6260
6340
  invalid,
6261
6341
  dryRun: ctx.flags.dryRun === true,
6262
- dryRunExtra: { operationId: op.id, firstRequest: preview(items[0]?.request) },
6342
+ dryRunExtra: { operationId: op.id, firstRequest: preview(items[0]?.request, op) },
6263
6343
  applyCommand
6264
6344
  },
6265
6345
  ctx
@@ -6274,6 +6354,7 @@ var init_each = __esm({
6274
6354
  init_input2();
6275
6355
  init_errors();
6276
6356
  init_exit_codes();
6357
+ init_secret_flags();
6277
6358
  init_execute();
6278
6359
  DEFAULT_CONCURRENCY2 = 4;
6279
6360
  SERIAL_PER_PATH = "contacts.create";
@@ -6292,7 +6373,8 @@ __export(execute_exports, {
6292
6373
  isDestructive: () => isDestructive,
6293
6374
  operationExamples: () => operationExamples,
6294
6375
  operationFlags: () => operationFlags,
6295
- operationToCommand: () => operationToCommand
6376
+ operationToCommand: () => operationToCommand,
6377
+ secretParams: () => secretParams
6296
6378
  });
6297
6379
  import { readFileSync as readFileSync5 } from "node:fs";
6298
6380
  import { basename } from "node:path";
@@ -6416,8 +6498,7 @@ function readUpload(path, field) {
6416
6498
  try {
6417
6499
  return { blob: new Blob([readFileSync5(file)]), name: basename(file) };
6418
6500
  } catch (err) {
6419
- const code = err.code;
6420
- throw new KensoError({ code: "file_unreadable", message: `Cannot read ${file}${code ? ` (${code})` : ""}.`, exitCode: ExitCode.Usage, field: "file" });
6501
+ throw fileUnreadable(file, err);
6421
6502
  }
6422
6503
  }
6423
6504
  function formValue(value) {
@@ -6426,7 +6507,7 @@ function formValue(value) {
6426
6507
  function buildRequest(op, values) {
6427
6508
  const routeNames = new Set(op.routeParams.map((p) => p.name));
6428
6509
  const queryNames = new Set(op.queryParams.map((p) => p.name));
6429
- if (op.list) {
6510
+ if (op.list && op.method !== "POST") {
6430
6511
  queryNames.add("limit");
6431
6512
  queryNames.add("cursor");
6432
6513
  }
@@ -6504,7 +6585,7 @@ async function collectValues(ctx, op, flags) {
6504
6585
  } else if (f.type === "integer" || f.type === "number") {
6505
6586
  value = parseNumber(String(raw), f.flag, f.type === "integer");
6506
6587
  } else {
6507
- value = String(raw);
6588
+ value = f.location === "body" && isSecretFlag(f.flag, f.type) ? await readSecretFlag(ctx, f.flag, String(raw)) : String(raw);
6508
6589
  }
6509
6590
  if (value === void 0) continue;
6510
6591
  if (f.location === "body" && paramNames.has(f.param.name)) bodyOnly[f.param.name] = value;
@@ -6544,14 +6625,15 @@ function sameCommand(ctx, op, flags) {
6544
6625
  for (const [name, value] of globals) if (value !== void 0) parts2.push(`--${name}`, shellQuote2(value));
6545
6626
  return parts2.join(" ");
6546
6627
  }
6547
- function describeRequest(req) {
6628
+ function describeRequest(req, op) {
6629
+ const secrets = new Set(secretParams(op).map((s) => s.name));
6548
6630
  const out = { method: req.method, path: req.path };
6549
6631
  if (req.query) out.query = req.query;
6550
- if (req.body !== void 0) out.body = req.body;
6632
+ if (req.body !== void 0) out.body = maskSecrets(req.body, secrets);
6551
6633
  if (req.form) {
6552
6634
  const form = {};
6553
6635
  for (const [key, value] of req.form.entries()) {
6554
- const shown = typeof value === "string" ? value : { file: value.name, bytes: value.size };
6636
+ const shown = typeof value === "string" ? secrets.has(key) ? "***" : value : { file: value.name, bytes: value.size };
6555
6637
  const previous = form[key];
6556
6638
  form[key] = previous === void 0 ? shown : Array.isArray(previous) ? [...previous, shown] : [previous, shown];
6557
6639
  }
@@ -6567,26 +6649,39 @@ function eachConcurrency(raw) {
6567
6649
  }
6568
6650
  return value;
6569
6651
  }
6652
+ function secretParams(op) {
6653
+ return operationFlags(op).flatMap((f) => f.param && f.location === "body" && isSecretFlag(f.flag, f.type) ? [{ flag: f.flag, name: f.param.name }] : []);
6654
+ }
6570
6655
  async function runOperation(ctx, op, flags) {
6656
+ const secrets = secretParams(op);
6657
+ checkSecretSources(flags, secrets.map((s) => s.flag));
6571
6658
  const values = await collectValues(ctx, op, flags);
6572
6659
  if (typeof flags.each === "string") {
6573
6660
  const { runEach: runEach2 } = await Promise.resolve().then(() => (init_each(), each_exports));
6574
- return runEach2(ctx, op, values, flags.each, { concurrency: eachConcurrency(flags.concurrency) });
6661
+ const typed = Object.fromEntries(secrets.flatMap((s) => typeof flags[s.flag] === "string" ? [[s.name, flags[s.flag]]] : []));
6662
+ return runEach2(ctx, op, values, flags.each, { concurrency: eachConcurrency(flags.concurrency), argValues: { ...values, ...typed } });
6575
6663
  }
6576
6664
  const req = buildRequest(op, values);
6577
6665
  if (ctx.flags.dryRun) {
6578
- ctx.output.object({ dryRun: true, operationId: op.id, request: describeRequest(req) });
6666
+ ctx.output.object({ dryRun: true, operationId: op.id, request: describeRequest(req, op) });
6579
6667
  return ExitCode.Ok;
6580
6668
  }
6581
6669
  if (isDestructive(op)) await confirmDestructive(ctx, `${commandOf(op)} sends ${req.method} ${req.path}`, `${sameCommand(ctx, op, flags)} --yes`);
6582
6670
  req.signal = ctx.signal;
6583
6671
  if (op.list && flags.all === true) {
6584
- await ctx.output.list(ctx.client.paginate(req));
6672
+ if (isRecord3(req.body) && Array.isArray(req.body.countBy) && req.body.countBy.length > 0) {
6673
+ throw usageError("--all prints rows, not counts. Ask for countBy on one page (--limit 1), or leave it out.", { field: "all" });
6674
+ }
6675
+ await ctx.output.list(ctx.client.paginate(req, op.method === "POST" ? { cursorIn: "body" } : void 0));
6585
6676
  return ExitCode.Ok;
6586
6677
  }
6587
6678
  const res = await ctx.client.request(req);
6588
6679
  if (res.status === 204 || res.body === null || res.body === "") return ExitCode.Ok;
6589
6680
  if (op.list && isRecord3(res.body) && Array.isArray(res.body.data)) {
6681
+ if (res.body.counts !== void 0) {
6682
+ ctx.output.object({ data: res.body.data, pagination: res.body.pagination, counts: res.body.counts });
6683
+ return ExitCode.Ok;
6684
+ }
6590
6685
  await ctx.output.list(res.body.data);
6591
6686
  const pagination = isRecord3(res.body.pagination) ? res.body.pagination : void 0;
6592
6687
  const next = pagination?.nextCursor;
@@ -6629,10 +6724,11 @@ function operationToCommand(op) {
6629
6724
  for (const f of operationFlags(op)) {
6630
6725
  const shown = helpFlagText(f);
6631
6726
  cut ||= shown.cut;
6727
+ const text3 = f.location === "body" && isSecretFlag(f.flag, f.type) ? `${shown.text} ${SECRET_HELP}` : shown.text;
6632
6728
  const spec = {
6633
6729
  type: f.type === "boolean" ? "boolean" : "string",
6634
6730
  // The dispatcher would enforce `required` before --each rows can fill it, so the command checks it instead.
6635
- description: f.required ? `${shown.text} (required)` : shown.text
6731
+ description: f.required ? `${text3} (required)` : text3
6636
6732
  };
6637
6733
  if (f.multiple) spec.multiple = true;
6638
6734
  if (FOOTER_FLAGS.has(f.flag) && !f.param) spec.helpHidden = true;
@@ -6683,6 +6779,7 @@ var init_execute = __esm({
6683
6779
  init_exit_codes();
6684
6780
  init_http();
6685
6781
  init_input();
6782
+ init_secret_flags();
6686
6783
  DATA_KEY = "$data";
6687
6784
  SCALAR_TYPES = /* @__PURE__ */ new Set(["string", "integer", "number", "boolean"]);
6688
6785
  FLAG_ALIASES = [
@@ -7117,7 +7214,7 @@ var init_agents = __esm({
7117
7214
  var auth_default;
7118
7215
  var init_auth = __esm({
7119
7216
  "docs/auth.md"() {
7120
- auth_default = '# Authentication\n\nThe CLI calls the Kenso API with a Kenso API key (`ken_` plus 43 characters). It sends the key as `Authorization: Bearer <key>` and never prints it, logs it or puts it in an error.\n\n`kenso login`, `kenso logout` and `kenso whoami` are the same commands as `kenso auth login`, `kenso auth logout` and `kenso auth status`.\n\n## Log in with an API key\n\n1. In app.ken.so, go to Settings > Integrations > API keys and create a key.\n2. Pipe it to `kenso auth login --with-key`. The key is read from stdin, never from a flag, so it stays out of your shell history and process list.\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso auth login --with-key --profile client-a --workspace 1234 < key.txt\n```\n\nThe CLI checks the key with `GET /v1/me`, then saves it to `~/.kenso/config.json` (file mode 0600, folder mode 0700). It prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","workspaceCount":1}\n```\n\nWhen the key reaches several workspaces and you did not pass `--workspace`, no workspace is saved and the output carries `"next":"kenso workspace list --search <name>"`. A key in the wrong format exits 2 (`invalid_key_format`). A key Kenso rejects exits 3.\n\n## Browser login\n\n```bash\nkenso auth login\nkenso auth login --no-browser --device-name "build box"\n```\n\nBrowser login is available to every workspace. The CLI prints a link and a code on stderr. You open the link, sign in to app.ken.so, check that the code matches the one in your terminal, pick the workspace to start in and approve. The CLI then saves a new API key to the profile and prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","keyExpiresAt":"2027-02-02T06:26:59Z"}\n```\n\nThe key is the same kind you create in the app. It is named `Kenso CLI - <device name>` (`--device-name`, else `kenso-cli on <hostname>`), lasts 90 days, and shows in your API key list at Settings > Integrations > API keys, where you can revoke it. The CLI opens the browser itself only when no coding agent is detected and the machine has a display. An agent prints the link and asks you to open it. The login expires after 10 minutes (`login_expired`, exit 3), and a denied login exits 3 with `access_denied`. If the API answers that browser login is off (`browser_login_unavailable`, exit 3, `"next":"kenso auth login --with-key"`), log in with an API key as above.\n\n## CI, scripts and agents: use the environment\n\nYou do not need to log in on a machine that has the key in its environment:\n\n```bash\nexport KENSO_API_KEY=ken_...\nexport KENSO_WORKSPACE_ID=1234\nkenso auth status\n```\n\n`KENSO_API_KEY` wins over any saved profile. Store it as a secret in your CI or agent platform, never in a file in the repo.\n\n## Workspaces\n\nA key reaches every workspace its user belongs to. Each command runs in one workspace, picked in this order:\n\n1. `--workspace <id>` on the command\n2. `KENSO_WORKSPACE_ID`\n3. the workspace saved in the profile (`kenso workspace use`)\n\n```bash\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --workspace 5678\n```\n\n`workspace list` prints one page and says on stderr when there are more: add `--all` for every page. A command that needs a workspace when none is picked fails with `workspace_required` (exit 2) and `"next":"kenso workspace list --search <name>"`.\n\n## Profiles\n\nA profile holds a key, a workspace, an optional API URL and the email. Use one per client or per key:\n\n```bash\nkenso auth login --with-key --profile client-a < client-a-key.txt\nkenso campaigns list --profile client-a\nKENSO_PROFILE=client-a kenso auth status\n```\n\nThe profile is `--profile`, else `KENSO_PROFILE`, else the active one (the last one you logged in to).\n\n## Check the setup\n\n```bash\nkenso auth status\nkenso doctor\n```\n\n`auth status` prints who the key belongs to and when it expires, and warns on stderr when that is within 14 days:\n\n```json\n{"email":"you@acme.io","workspaceCount":3,"activeWorkspace":{"id":"1234","name":"Acme"},"keyExpiresAt":"2027-01-31T00:00:00Z","keySource":"profile","profile":"default"}\n```\n\n`doctor` prints the version, Node, the config folder, the profile, the key source, the API URL, the workspace and the detected agent, then four checks: `node_version`, `config_permissions`, `api_reachable` and `key_valid`. It exits 0 when every check passes, 3 when the key is missing or rejected, else 1.\n\n## Log out\n\n```bash\nkenso auth logout\nkenso auth logout --profile client-a\n```\n\nThis removes the profile and its key from this machine. The key itself stays valid until you revoke it at Settings > Integrations > API keys.\n\n## Where things live\n\n| What | Default | Override |\n|---|---|---|\n| Config file with profiles and keys | `~/.kenso/config.json` | `KENSO_CONFIG_DIR` |\n| Run folders | `~/.kenso/runs/` | `KENSO_RUNS_DIR` |\n| Cached workspace features (1 hour) | `~/.kenso/cache/` | follows `KENSO_CONFIG_DIR` |\n| Last update check (once every 7 days) | `~/.kenso/update-check.json` | follows `KENSO_CONFIG_DIR`; `KENSO_NO_UPDATE_NOTIFIER=1` turns the check off |\n| API | `https://api.ken.so` | `KENSO_API_URL` |\n| MCP (for `kenso mcp`) | `https://mcp.ken.so/mcp` | `KENSO_MCP_URL` |\n\n`--verbose` prints each request line to stderr with the key redacted.\n';
7217
+ auth_default = '# Authentication\n\nThe CLI calls the Kenso API with a Kenso API key (`ken_` plus 43 characters). It sends the key as `Authorization: Bearer <key>` and never prints it, logs it or puts it in an error.\n\n`kenso login`, `kenso logout` and `kenso whoami` are the same commands as `kenso auth login`, `kenso auth logout` and `kenso auth status`.\n\n## Log in with an API key\n\n1. In app.ken.so, go to Settings > Integrations > API keys and create a key.\n2. Pipe it to `kenso auth login --with-key`. The key is read from stdin, never from a flag, so it stays out of your shell history and process list.\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso auth login --with-key --profile client-a --workspace 1234 < key.txt\n```\n\nThe CLI checks the key with `GET /v1/me`, then saves it to `~/.kenso/config.json` (file mode 0600, folder mode 0700). It prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","workspaceCount":1}\n```\n\nWhen the key reaches several workspaces and you did not pass `--workspace`, no workspace is saved and the output carries `"next":"kenso workspace list --search <name>"`. A key in the wrong format exits 2 (`invalid_key_format`). A key Kenso rejects exits 3.\n\n## Browser login\n\n```bash\nkenso auth login\nkenso auth login --no-browser --device-name "build box"\n```\n\nBrowser login is available to every workspace. The CLI prints a link and a code on stderr. You open the link, sign in to app.ken.so, check that the code matches the one in your terminal, pick the workspace to start in and approve. The CLI then saves a new API key to the profile and prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","keyExpiresAt":"2027-02-02T06:26:59Z"}\n```\n\nThe key is the same kind you create in the app. It is named `Kenso CLI - <device name>` (`--device-name`, else `kenso-cli on <hostname>`), lasts 90 days, and shows in your API key list at Settings > Integrations > API keys, where you can revoke it. The CLI opens the browser itself only when no coding agent is detected and the machine has a display. An agent prints the link and asks you to open it. The login expires after 10 minutes (`login_expired`, exit 3), and a denied login exits 3 with `access_denied`. If the API answers that browser login is off (`browser_login_unavailable`, exit 3, `"next":"kenso auth login --with-key"`), log in with an API key as above.\n\n## CI, scripts and agents: use the environment\n\nYou do not need to log in on a machine that has the key in its environment:\n\n```bash\nexport KENSO_API_KEY=ken_...\nexport KENSO_WORKSPACE_ID=1234\nkenso auth status\n```\n\n`KENSO_API_KEY` wins over any saved profile. Store it as a secret in your CI or agent platform, never in a file in the repo.\n\n## Workspaces\n\nA key reaches every workspace its user belongs to. Each command runs in one workspace, picked in this order:\n\n1. `--workspace <id>` on the command\n2. `KENSO_WORKSPACE_ID`\n3. the workspace saved in the profile (`kenso workspace use`)\n\n```bash\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --workspace 5678\n```\n\n`workspace list` prints one page and says on stderr when there are more: add `--all` for every page. A command that needs a workspace when none is picked fails with `workspace_required` (exit 2) and `"next":"kenso workspace list --search <name>"`.\n\n## Profiles\n\nA profile holds a key, a workspace, an optional API URL and the email. Use one per client or per key:\n\n```bash\nkenso auth login --with-key --profile client-a < client-a-key.txt\nkenso campaigns list --profile client-a\nKENSO_PROFILE=client-a kenso auth status\n```\n\nThe profile is `--profile`, else `KENSO_PROFILE`, else the active one (the last one you logged in to).\n\n## Check the setup\n\n```bash\nkenso auth status\nkenso doctor\n```\n\n`auth status` prints who the key belongs to and when it expires, and warns on stderr when that is within 14 days:\n\n```json\n{"email":"you@acme.io","workspaceCount":3,"activeWorkspace":{"id":"1234","name":"Acme"},"keyExpiresAt":"2027-01-31T00:00:00Z","keySource":"profile","profile":"default"}\n```\n\n`doctor` prints the version, Node, the config folder, the profile, the key source, the API URL, the workspace and the detected agent, then four checks: `node_version`, `config_permissions`, `api_reachable` and `key_valid`. It exits 0 when every check passes, 3 when the key is missing or rejected, else 1.\n\n## Log out\n\n```bash\nkenso auth logout\nkenso auth logout --profile client-a\nkenso auth logout --keep-key\n```\n\nThis removes the profile and its key from this machine. When browser login made the key, logout revokes it first, so it stops working everywhere; `--keep-key` leaves it valid. If the revoke fails (no network, or the key was already revoked), logout warns and still removes the profile. A key you saved with `--with-key` was made by you in the app, so logout leaves it valid: revoke it at Settings > Integrations > API keys. The output adds `revoked: true` or `false`.\n\n## Where things live\n\n| What | Default | Override |\n|---|---|---|\n| Config file with profiles and keys | `~/.kenso/config.json` | `KENSO_CONFIG_DIR` |\n| Run folders | `~/.kenso/runs/` | `KENSO_RUNS_DIR` |\n| Cached workspace features (1 hour) | `~/.kenso/cache/` | follows `KENSO_CONFIG_DIR` |\n| Last update check (once every 7 days) | `~/.kenso/update-check.json` | follows `KENSO_CONFIG_DIR`; `KENSO_NO_UPDATE_NOTIFIER=1` turns the check off |\n| API | `https://api.ken.so` | `KENSO_API_URL` |\n| MCP (for `kenso mcp`) | `https://mcp.ken.so/mcp` | `KENSO_MCP_URL` |\n\n`--verbose` prints each request line to stderr with the key redacted.\n';
7121
7218
  }
7122
7219
  });
7123
7220
 
@@ -7125,7 +7222,7 @@ var init_auth = __esm({
7125
7222
  var batch_default;
7126
7223
  var init_batch = __esm({
7127
7224
  "docs/batch.md"() {
7128
- batch_default = '# Batch runs\n\nA batch command takes a file, sends its rows to Kenso in chunks, and prints one JSON summary. Every input row gets one line in a results file, every run can be resumed, and nothing is written until you pass `--yes`.\n\nThe batch commands:\n\n- `contacts import`, `update`, `remove`, `restore`, `pause`, `resume`, `tag`, `untag` ([Leads](leads.md))\n- `people import` and `accounts import` ([CRM](crm.md), beta)\n- `studio fill` ([Studio](studio.md), beta)\n- any generated command run with `--each <file>`, once per row (see below)\n\n## Plan, then apply\n\nWithout `--yes` a batch command plans and changes nothing. `--dry-run` asks for the plan explicitly. `--yes` applies. Passing both is a usage error. Two exceptions to the plan below: `studio fill` without `--yes` prints its credit estimate and `next`, with no run or `plan.json` ([Studio](studio.md)), and a non-GET `--each` without `--yes` or `--dry-run` is a usage error (exit 2) rather than a plan.\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThe dry run parses and checks every row, may call read-only endpoints (a campaign read, a credit estimate, a contacts search for `--where`), writes `plan.json`, and prints the plan:\n\n```json\n{"run":"r_ubqu7wtx","dryRun":true,"command":"contacts remove","rows":3,"valid":3,"invalid":0,"chunks":1,"chunkSize":1000,"source":"ids","count":3,"firstIds":[11,12,13],"next":"kenso contacts remove --ids ids.txt --yes","plan":"/home/you/.kenso/runs/r_ubqu7wtx/plan.json"}\n```\n\nEvery plan has `run`, `dryRun`, `command`, `rows`, `valid`, `invalid`, `chunks`, `chunkSize`, `next` (the exact command that applies it) and `plan` (the file), plus fields of its own command. It adds `invalidRows` when rows were refused, `chunksDone` when it continues an unfinished run, and `alreadyDone: true` when the apply would change nothing.\n\n## The summary\n\nAn applied run prints one JSON object:\n\n```json\n{"run":"r_ubqu7wtx","rows":3,"ok":2,"created":0,"updated":0,"skipped":{},"failed":0,"notFound":1,"invalid":0,"changed":2,"results":"/home/you/.kenso/runs/r_ubqu7wtx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_ubqu7wtx/results.ndjson","resumed":false,"durationMs":412,"undo":"kenso contacts restore --run r_ubqu7wtx"}\n```\n\n| Field | Meaning |\n|---|---|\n| `run` | The run id: `r_` and 8 characters |\n| `rows` | Input rows |\n| `ok`, `created`, `updated` | Rows that succeeded, by kind |\n| `skipped` | Rows Kenso left alone on purpose, counted by reason, for example `{"duplicate":12}` |\n| `failed`, `notFound`, `invalid` | Rows that did not go through: refused or errored, id not found, refused locally |\n| `changed` | Rows this invocation changed. 0 when a rerun had nothing left to do |\n| `results`, `resultsNdjson` | Absolute paths of the results files |\n| `invalidRows` | Path of `invalid.csv`, when rows were refused locally |\n| `resumed` | True when this invocation continued an earlier run |\n| `durationMs` | Wall time of this invocation |\n| `pending` | Rows without a result yet, when the run did not finish |\n| `stopped` | `{code, message, hint}` when a stop condition ended the run (for example `limit_reached`) |\n| `interrupted` | True after Ctrl-C |\n| `next` | `kenso runs resume <runId>` when the run can continue |\n\nCommands add their own fields: `contacts import` adds `campaignId` and `notSendable`, `contacts remove` adds `undo`, `people import` adds `matched`, `addedToAccounts` and `emailFindsQueued`, `accounts import` adds `researchQueued` and `researchWaitingCredits`, `studio fill` adds `templateId`, `runs` and the estimate.\n\nExit codes: 0 when every row succeeded or was skipped, 5 when some rows are `failed`, `not_found` or `invalid`, 6 when a limit stopped the run, 130 after Ctrl-C. The full table is in [Output and errors](output-and-errors.md).\n\n## The run folder\n\nEach run keeps its files in `~/.kenso/runs/<runId>/` (`KENSO_RUNS_DIR` moves the root), or in `--out <dir>` when you pass it. A run in `--out` is also linked under the runs folder, so `kenso runs` finds it. The folder is mode 0700 and its files 0600.\n\n| File | What it holds |\n|---|---|\n| `run.json` | The command, its arguments, the input path and SHA-256, the workspace, the chunk plan and the status (`planned`, `running`, `done`, `failed`, `interrupted`) |\n| `state.json` | The chunks done so far, rewritten after every chunk |\n| `results.csv` | One line per input row: `row,status,id,reason,error`, then extra columns such as `email` or `sendable` |\n| `results.ndjson` | The same rows as JSON lines |\n| `invalid.csv` | Rows refused before sending, with the reason |\n| `plan.json` | The last dry run\'s plan |\n| `summary.json` | The last summary printed |\n\n`row` is the 1-based number of the data row in the input (the CSV header is not counted). `status` is one of `created`, `updated`, `ok`, `skipped`, `failed`, `not_found` or `invalid`.\n\n```bash\nkenso runs list\nkenso runs list --limit 5 -o json\nkenso runs show r_ubqu7wtx\n```\n\n## Rerun and resume\n\nA run is identified by its command, its arguments, the SHA-256 of its input file, the workspace and the chunk size. `--yes`, `--dry-run`, `--wait`, `--concurrency` and the output flags are not part of it. Running the same command again on the same file:\n\n- **continues an unfinished run** (interrupted, stopped or crashed): finished chunks are skipped and the summary says `"resumed":true`.\n- **answers from a finished run where every row succeeded:** it prints that run\'s summary with `"changed":0` and `"alreadyDone":true`, sends no writes and exits 0 (a command may still read first: `contacts import` reads the campaign, and `contacts update --match email` looks up the campaign\'s contacts).\n- **starts a new run** when the last one finished with failed or invalid rows, or when the file changed. Lead, people and account writes match existing records (an email in a campaign, a person by email or LinkedIn URL, an account by domain), so sending a row twice never creates a duplicate.\n\n`kenso runs resume <runId>` does the same from the run id: it rebuilds the command from `run.json` and runs it with `--yes` from the folder it started in. It refuses when the input was stdin, or the file is gone or changed. Two processes cannot work on one run: the second gets `run_in_progress` (exit 7).\n\n```bash\nkenso runs resume r_ubqu7wtx\n```\n\n`studio fill` is the exception: a fill charges for every page it builds, so it never fills the same ids twice. See [Studio](studio.md).\n\n## Ctrl-C\n\nThe first Ctrl-C cancels the requests in flight and starts no new chunks. The CLI writes the state and prints the summary with `"interrupted":true` and `"next":"kenso runs resume <runId>"`, then exits 130. A chunk that did not finish is sent again when you resume, which is safe because the writes match existing records. A second Ctrl-C quits at once.\n\n## Chunks, concurrency and rate limits\n\n| Command | Rows per call | At once |\n|---|---|---|\n| `contacts import` | 1,000 | 1 per campaign |\n| `contacts update`, `remove`, `restore`, `pause`, `resume` | 1,000 | 4 (`--concurrency`) |\n| `contacts tag`, `untag` | 1 per call, 25 per chunk | 4 chunks (`--concurrency`) |\n| `people import` | 200 | 4 (`--concurrency`) |\n| `accounts import` | 100 | 4 (`--concurrency`) |\n| `studio fill` | 500 ids per fill run | 1 |\n| `--each` | 1 | 4 (`--concurrency`) |\n\n`--concurrency` takes 1 to 16. When the API\'s `RateLimit-Remaining` header drops below 10, the CLI sends one chunk at a time until it is back above 30.\n\nRetries:\n\n- **429:** the CLI waits for `Retry-After` (at least 1 second, at most 60 seconds per wait) and tries again, with up to 15 minutes of waiting per command. After that it exits 6 (`rate_limited`).\n- **502, 503, 504 and network errors:** up to 3 retries with backoff, for GET, PUT, PATCH and DELETE, and for the POST routes the CLI knows are safe to repeat.\n- **`contacts import`:** no quick retry. After a 5xx or a dropped connection it waits 130 seconds, longer than the gateway\'s request timeout, and resends the chunk once.\n- **`contacts remove`:** after a 5xx or a dropped connection it waits 2 seconds and resends once. Ids the first call already removed are reported `ok` (reason `already_removed`), so the undo still restores them.\n- **Other 4xx answers:** never retried. The row or chunk is marked `failed` with the API\'s code.\n\nKenso answers a bulk call with 200 even when some items fail, so the CLI reads each item\'s result and never trusts the HTTP status alone.\n\n## Progress\n\nProgress goes to stderr, at most one line every 2 seconds (`chunk 7/20, 7000 rows, 6 failed`), and only when stderr is a terminal or you pass `--progress`. An agent gets only the summary.\n\n## Run any API operation once per row: --each\n\nEvery generated command takes `--each <file>`, a CSV or JSONL file or `-` for stdin. The command runs once per row through the same engine: one results line per row, resume, `--concurrency`. Row keys fill the route, query and body by API name (`accountId`) or flag name (`account-id`). A blank cell is left out and the literal `null` sends null. A GET runs right away; any other method needs `--yes` or `--dry-run`.\n\n```bash\nkenso accounts update --each stages.csv --dry-run\nkenso accounts update --each stages.csv --yes --concurrency 8\n```\n\nWith `stages.csv`:\n\n```csv\naccountId,stage,overwritePinned\n501,engaged,true\n502,customer,true\n```\n\nEach row is `ok` on a 2xx answer (with the created or returned id), `not_found` on 404, `failed` otherwise, or `invalid` when a required value is missing.\n\n## The token-saving pattern for agents\n\n1. Pass a file path, never the rows: `--file leads.csv`.\n2. Run `--dry-run`, read the plan, then run its `next`.\n3. Read the summary. If `failed`, `notFound` and `invalid` are 0, you are done.\n4. Otherwise read only the problem rows, for example `grep -E \'^[0-9]+,(failed|not_found|invalid),\' results.csv | head -50`, or `invalid.csv`.\n';
7225
+ batch_default = '# Batch runs\n\nA batch command takes a file, sends its rows to Kenso in chunks, and prints one JSON summary. Every input row gets one line in a results file, every run can be resumed, and nothing is written until you pass `--yes`.\n\nThe batch commands:\n\n- `contacts import`, `update`, `remove`, `restore`, `pause`, `resume`, `tag`, `untag` ([Leads](leads.md))\n- `people import` and `accounts import` ([CRM](crm.md), beta)\n- `studio fill` ([Studio](studio.md), beta)\n- any generated command run with `--each <file>`, once per row (see below)\n\n## Plan, then apply\n\nWithout `--yes` a batch command plans and changes nothing. `--dry-run` asks for the plan explicitly. `--yes` applies. Passing both is a usage error. Two exceptions to the plan below: `studio fill` without `--yes` prints its credit estimate and `next`, with no run or `plan.json` ([Studio](studio.md)), and a non-GET `--each` without `--yes` or `--dry-run` is a usage error (exit 2) rather than a plan.\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThe dry run parses and checks every row, may call read-only endpoints (a campaign read, a credit estimate, a contacts search for `--where`), writes `plan.json`, and prints the plan:\n\n```json\n{"run":"r_ubqu7wtx","dryRun":true,"command":"contacts remove","rows":3,"valid":3,"invalid":0,"chunks":1,"chunkSize":1000,"source":"ids","count":3,"firstIds":[11,12,13],"next":"kenso contacts remove --ids ids.txt --yes","plan":"/home/you/.kenso/runs/r_ubqu7wtx/plan.json"}\n```\n\nEvery plan has `run`, `dryRun`, `command`, `rows`, `valid`, `invalid`, `chunks`, `chunkSize`, `next` (the exact command that applies it) and `plan` (the file), plus fields of its own command. It adds `invalidRows` when rows were refused, `chunksDone` when it continues an unfinished run, and `alreadyDone: true` when the apply would change nothing.\n\nA file the CLI cannot read stops the run before anything is planned, with `file_unreadable` (exit 2), the line at fault and a hint: `leads.csv line 3: a quote is not closed.`, `leads.csv does not exist.`, `rows.jsonl line 7 is not valid JSON.`\n\n## The summary\n\nAn applied run prints one JSON object:\n\n```json\n{"run":"r_ubqu7wtx","rows":3,"ok":2,"created":0,"updated":0,"skipped":{},"failed":0,"notFound":1,"invalid":0,"changed":2,"results":"/home/you/.kenso/runs/r_ubqu7wtx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_ubqu7wtx/results.ndjson","resumed":false,"durationMs":412,"undo":"kenso contacts restore --run r_ubqu7wtx"}\n```\n\n| Field | Meaning |\n|---|---|\n| `run` | The run id: `r_` and 8 characters |\n| `rows` | Input rows |\n| `ok`, `created`, `updated` | Rows that succeeded, by kind |\n| `skipped` | Rows Kenso left alone on purpose, counted by reason, for example `{"duplicate":12}` |\n| `failed`, `notFound`, `invalid` | Rows that did not go through: refused or errored, id not found, refused locally |\n| `changed` | Rows this invocation changed. 0 when a rerun had nothing left to do |\n| `results`, `resultsNdjson` | Absolute paths of the results files |\n| `invalidRows` | Path of `invalid.csv`, when rows were refused locally |\n| `resumed` | True when this invocation continued an earlier run |\n| `durationMs` | Wall time of this invocation |\n| `pending` | Rows without a result yet, when the run did not finish |\n| `stopped` | `{code, message, hint}` when a stop condition ended the run (for example `limit_reached`) |\n| `interrupted` | True after Ctrl-C |\n| `next` | `kenso runs resume <runId>` when the run can continue |\n\nCommands add their own fields: `contacts import` adds `campaignId` and `notSendable`, `contacts remove` adds `undo`, `people import` adds `matched`, `addedToAccounts` and `emailFindsQueued`, `accounts import` adds `researchQueued` and `researchWaitingCredits`, `studio fill` adds `templateId`, `runs` and the estimate.\n\nExit codes: 0 when every row succeeded or was skipped, 5 when some rows are `failed`, `not_found` or `invalid`, 6 when a limit stopped the run, 130 after Ctrl-C. The full table is in [Output and errors](output-and-errors.md).\n\n## The run folder\n\nEach run keeps its files in `~/.kenso/runs/<runId>/` (`KENSO_RUNS_DIR` moves the root), or in `--out <dir>` when you pass it. A run in `--out` is also linked under the runs folder, so `kenso runs` finds it. The folder is mode 0700 and its files 0600.\n\n| File | What it holds |\n|---|---|\n| `run.json` | The command, its arguments, the input path and SHA-256, the workspace, the chunk plan and the status (`planned`, `running`, `done`, `failed`, `interrupted`) |\n| `state.json` | The chunks done so far, rewritten after every chunk |\n| `results.csv` | One line per input row: `row,status,id,reason,error`, then extra columns such as `email` or `sendable` |\n| `results.ndjson` | The same rows as JSON lines |\n| `invalid.csv` | Rows refused before sending, with the reason |\n| `plan.json` | The last dry run\'s plan |\n| `summary.json` | The last summary printed |\n\n`row` is the 1-based number of the data row in the input (the CSV header is not counted). `status` is one of `created`, `updated`, `ok`, `skipped`, `failed`, `not_found` or `invalid`.\n\n```bash\nkenso runs list\nkenso runs list --limit 5 -o json\nkenso runs show r_ubqu7wtx\n```\n\n## Rerun and resume\n\nA run is identified by its command, its arguments, the SHA-256 of its input file, the workspace and the chunk size. `--yes`, `--dry-run`, `--wait`, `--concurrency` and the output flags are not part of it. Running the same command again on the same file:\n\n- **continues an unfinished run** (interrupted, stopped or crashed): finished chunks are skipped and the summary says `"resumed":true`.\n- **answers from a finished run where every row succeeded:** it prints that run\'s summary with `"changed":0` and `"alreadyDone":true`, sends no writes and exits 0 (a command may still read first: `contacts import` reads the campaign, and `contacts update --match email` looks up the campaign\'s contacts).\n- **starts a new run** when the last one finished with failed or invalid rows, or when the file changed. Lead, people and account writes match existing records (an email in a campaign, a person by email or LinkedIn URL, an account by domain), so sending a row twice never creates a duplicate.\n\n`kenso runs resume <runId>` does the same from the run id: it rebuilds the command from `run.json` and runs it with `--yes` from the folder it started in. It refuses when the input was stdin, or the file is gone or changed. Two processes cannot work on one run: the second gets `run_in_progress` (exit 7).\n\n```bash\nkenso runs resume r_ubqu7wtx\n```\n\n`studio fill` is the exception: a fill charges for every page it builds, so it never fills the same ids twice. See [Studio](studio.md).\n\n## Ctrl-C\n\nThe first Ctrl-C cancels the requests in flight and starts no new chunks. The CLI writes the state and prints the summary with `"interrupted":true` and `"next":"kenso runs resume <runId>"`, then exits 130. A chunk that did not finish is sent again when you resume, which is safe because the writes match existing records. A second Ctrl-C quits at once.\n\n## Chunks, concurrency and rate limits\n\n| Command | Rows per call | At once |\n|---|---|---|\n| `contacts import` | 1,000 | 1 per campaign |\n| `contacts update`, `remove`, `restore`, `pause`, `resume` | 1,000 | 4 (`--concurrency`) |\n| `contacts tag`, `untag` | 1 per call, 25 per chunk | 4 chunks (`--concurrency`) |\n| `people import` | 200 | 4 (`--concurrency`) |\n| `accounts import` | 100 | 4 (`--concurrency`) |\n| `studio fill` | 500 ids per fill run | 1 |\n| `--each` | 1 | 4 (`--concurrency`) |\n\n`--concurrency` takes 1 to 16. When the API\'s `RateLimit-Remaining` header drops below 10, the CLI sends one chunk at a time until it is back above 30.\n\nRetries:\n\n- **429:** the CLI waits for `Retry-After` (at least 1 second, at most 60 seconds per wait) and tries again, with up to 15 minutes of waiting per command. After that it exits 6 (`rate_limited`).\n- **502, 503, 504 and network errors:** up to 3 retries with backoff, for GET, PUT, PATCH and DELETE, and for the POST routes the CLI knows are safe to repeat.\n- **`contacts import`:** no quick retry. After a 5xx or a dropped connection it waits 130 seconds, longer than the gateway\'s request timeout, and resends the chunk once.\n- **`contacts remove`:** after a 5xx or a dropped connection it waits 2 seconds and resends once. Ids the first call already removed are reported `ok` (reason `already_removed`), so the undo still restores them.\n- **Other 4xx answers:** never retried. The row or chunk is marked `failed` with the API\'s code.\n\nKenso answers a bulk call with 200 even when some items fail, so the CLI reads each item\'s result and never trusts the HTTP status alone.\n\n## Progress\n\nProgress goes to stderr, at most one line every 2 seconds (`chunk 7/20, 7000 rows, 6 failed`), and only when stderr is a terminal or you pass `--progress`. An agent gets only the summary.\n\n## Run any API operation once per row: --each\n\nEvery generated command takes `--each <file>`, a CSV or JSONL file or `-` for stdin. The command runs once per row through the same engine: one results line per row, resume, `--concurrency`. Row keys fill the route, query and body by API name (`accountId`) or flag name (`account-id`). A blank cell is left out and the literal `null` sends null. A GET runs right away; any other method needs `--yes` or `--dry-run`.\n\n```bash\nkenso accounts update --each stages.csv --dry-run\nkenso accounts update --each stages.csv --yes --concurrency 8\n```\n\nWith `stages.csv`:\n\n```csv\naccountId,stage,overwritePinned\n501,engaged,true\n502,customer,true\n```\n\nEach row is `ok` on a 2xx answer (with the created or returned id), `not_found` on 404, `failed` otherwise, or `invalid` when a required value is missing.\n\n## The token-saving pattern for agents\n\n1. Pass a file path, never the rows: `--file leads.csv`.\n2. Run `--dry-run`, read the plan, then run its `next`.\n3. Read the summary. If `failed`, `notFound` and `invalid` are 0, you are done.\n4. Otherwise read only the problem rows, for example `grep -E \'^[0-9]+,(failed|not_found|invalid),\' results.csv | head -50`, or `invalid.csv`.\n';
7129
7226
  }
7130
7227
  });
7131
7228
 
@@ -7149,7 +7246,7 @@ var init_leads = __esm({
7149
7246
  var output_and_errors_default;
7150
7247
  var init_output_and_errors = __esm({
7151
7248
  "docs/output-and-errors.md"() {
7152
- output_and_errors_default = '# Output and errors\n\nEvery command follows one contract, so a script or an agent can parse any of them the same way.\n\n## stdout and stderr\n\n- **stdout carries data only.** Progress, warnings, notices and errors go to stderr.\n- No colors, spinners or pagers. On a terminal you get readable tables; in a pipe you get JSON.\n- A batch command (an import, update, remove, tag or `--each` write) takes `--yes`; without it, the command plans or refuses.\n- A command that deletes, archives or removes, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive` or `kenso api DELETE /v1/tags/7`, needs `--yes` too. Without it, a person at a terminal is asked to confirm; anywhere else (a pipe, a script, CI, a coding agent) it sends nothing and fails with `confirmation_required`, whose `next` is the same command with `--yes`.\n- Any other single write, such as `kenso tags create` or a write through `kenso api` or `kenso mcp call`, sends at once: add `--dry-run` to print the request first (it sends nothing), then run the command without it.\n- A command with no dry run, such as `kenso contacts export`, `kenso auth logout` or `kenso workspace use`, refuses `--dry-run` with `usage_error` (exit 2) and does nothing. Its help ends with `No --dry-run`, and `kenso describe <resource> <action>` shows `"dryRun": false`.\n\n## Formats\n\n| What the command returns | stdout is a terminal | stdout is a pipe or file |\n|---|---|---|\n| One object | key-value lines | compact JSON on one line |\n| A list | a table (first 8 scalar fields, cells cut at 60 characters) | NDJSON: one JSON object per line |\n| A batch run | key-value lines | one JSON summary object |\n| No content (HTTP 204) | nothing | nothing |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table` or `ids`. `--json` is the same as `-o json`.\n\n- `-o json` on a list prints one JSON array. On a terminal, `-o json` pretty-prints an object.\n- `-o ids` prints one id per line, ready for `--ids -`. Items without an `id` are skipped with one warning.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso contacts list --campaign-id 812 --all -o ids\n```\n\n## Shape the output\n\n- `--fields a,b.c` keeps only those fields (dots reach into nested objects).\n- `--query <JMESPath>` filters or reshapes in-process, so you need no `jq`. On a list it sees the whole list. There is no `--jq`: `--query` takes JMESPath, not jq syntax.\n- Neither applies to a batch summary, which always prints in full.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\n```\n\n## Lists and pages\n\nA list command prints one page. When there are more, it prints the command for the next page on stderr, for example `next: kenso tags list --limit 1 --cursor MQ`. `--all` follows every page and streams the items. `--limit` sets the page size and `--cursor` starts at a cursor.\n\n```bash\nkenso tags list --limit 50\nkenso tags list --all\n```\n\n## Errors\n\nWhen stderr is not a terminal, an error is one JSON line on stderr:\n\n```json\n{"error":{"code":"unknown_flag","message":"Unknown flag --fiel for kenso contacts import.","field":"fiel","hint":"did you mean --file?","next":"kenso contacts import --help"}}\n```\n\n| Key | Always there | Meaning |\n|---|---|---|\n| `code` | yes | A stable snake_case code to branch on |\n| `message` | yes | One sentence for a person |\n| `field` | no | The flag or input field at fault |\n| `hint` | no | What to change |\n| `next` | no | The exact command to run next, such as `kenso auth login`, `kenso workspace list --search <name>` or the same command with `--yes` |\n| `httpStatus` | no | The API\'s HTTP status, when the API answered |\n| `requestId` | no | The API\'s request id: quote it when you contact Kenso support |\n\nOn a terminal the same error prints as text: `Error: <message>`, then `field:`, `hint:`, `next:` and `requestId:` lines. The key never appears in an error.\n\n### How API errors map\n\nThe CLI looks at the HTTP status first, then at the API\'s own `error.code`, which wins when present.\n\n| HTTP status | Default code | Exit |\n|---|---|---|\n| 400, 422 | `validation_failed` | 2 |\n| 401 | `unauthorized` (`next`: `kenso auth login`) | 3 |\n| 403 | `forbidden`: the key\'s user or role cannot do this in this workspace | 3 |\n| 404 | `not_found` | 4 |\n| 409 | `conflict` | 7 |\n| 429 | `rate_limited`, after the CLI waited and retried | 6 |\n| 5xx | `server_error`, after retries where they are safe | 8 |\n| anything else | `http_error` | 1 |\n\nTwo API codes change the exit code: `workspace_required` exits 2 with `"next":"kenso workspace list --search <name>"`, and `limit_reached` (the plan\'s or the campaign\'s lead limit) exits 6.\n\n### Errors from the CLI itself\n\n| Code | Exit | When |\n|---|---|---|\n| `usage_error` | 2 | A required flag or argument is missing, two flags conflict (`--yes` with `--dry-run`), or `--dry-run` on a command that has no dry run |\n| `unknown_command` | 2 | No such command; `hint` suggests the closest one |\n| `unknown_flag`, `invalid_flag`, `invalid_flag_value`, `unexpected_argument` | 2 | A flag or argument the command does not take |\n| `invalid_query` | 2 | `--query` is not valid JMESPath |\n| `confirmation_required` | 2 | A delete, archive or remove ran without `--yes` where nobody can confirm: nothing was sent; `next` adds `--yes` |\n| `cancelled` | 2 | A person answered no to the confirmation: nothing was sent |\n| `file_unreadable` | 2 | An input file is missing or cannot be parsed |\n| `config_invalid` | 2 | `~/.kenso/config.json` is not valid JSON: fix or delete it |\n| `feature_not_enabled` | 2 | Every action of the resource is a beta command your workspace has not enabled |\n| `invalid_key_format`, `key_required` | 2 | `auth login --with-key` read something that is not a Kenso key, or stdin is a terminal instead of a pipe |\n| `invalid_workspace_id` | 2 | `kenso workspace use` got an id that is not a positive whole number |\n| `unknown_topic` | 2 | `kenso docs` got a topic it does not have; `hint` lists the topics |\n| `file_unwritable` | 2 or 1 | An output file cannot be written: `contacts export --out` (2), `skill install` (1) |\n| `no_api_key` | 3 | No key in `KENSO_API_KEY` or the profile (`next`: `kenso auth login`) |\n| `browser_login_unavailable`, `access_denied`, `login_expired` | 3 | Browser login is off, was denied, or timed out |\n| `run_not_found` | 4 | `kenso runs show` or `resume` got an unknown run id |\n| `docs_not_found` | 4 | `kenso docs reference` before the reference was generated (a source checkout without `pnpm build`) |\n| `run_in_progress`, `already_filled` | 7 | Another process is working on the run, or `studio fill` already ran with this file and these flags |\n| `skill_exists` | 7 | `kenso skill install` found a different `SKILL.md`; `next` adds `--force` to replace it |\n| `job_timeout`, `job_failed`, `job_canceled` | 1 | `kenso jobs wait` (or a command that waits on a job) ran out of time, or the job failed or was canceled |\n| `mcp_tool_error` | 1 | `kenso mcp call`: the MCP tool answered with an error |\n| `unsafe_path` | 1 | `studio pull` refused a file path that would land outside `--dir` |\n| `network_error` | 8 | The API could not be reached after retries |\n| `upload_failed`, `download_failed` | 8 or 1 | A signed upload or download of a Studio file failed: 8 when storage was unreachable or answered 5xx, 1 on a 4xx (often an expired link: run the command again) |\n| `pull_incomplete` | 8 | `studio pull`: a file came back with neither text nor a download link |\n| `unexpected_response` | 1 or 8 | The API answered something the CLI could not read |\n| `unexpected_error` | 1 | A bug: run again with `--verbose` and report it |\n| `interrupted` | 130 | Ctrl-C |\n\n## Exit codes\n\n| Code | Meaning |\n|---|---|\n| 0 | OK, including a batch where every row succeeded or was skipped |\n| 1 | Unexpected error |\n| 2 | Usage or input error: a bad flag, a bad file, a validation error |\n| 3 | Auth: no key, an invalid, revoked or expired key, or HTTP 401 or 403 |\n| 4 | Not found |\n| 5 | Partial: the batch finished and some rows failed, were not found or were invalid. See `results.csv` |\n| 6 | Rate limited after retries, or a plan or campaign lead limit stopped the run (`limit_reached`) |\n| 7 | Conflict or invalid state (HTTP 409), or a run another process holds |\n| 8 | Server error after retries (5xx), or the API is unreachable |\n| 9 | Answer refused: a Kenso sandbox run stopped because an answer held a credential or something shaped like one |\n| 130 | Interrupted. A batch run can be resumed: see its `next` |\n\nSkipped rows (duplicates, blocklisted, already contacted) are not failures: a batch with only created, updated and skipped rows exits 0.\n\n## Flags\n\n- Command flags go after the command: `kenso contacts import --campaign 812`. Global flags can go anywhere.\n- A boolean flag takes `--flag`, `--no-flag`, `--flag=true` and `--flag=false`.\n- `--help` on any command prints its flags, arguments and examples. `kenso describe <resource> <action>` prints the same as JSON, with the body schema.\n\n## Beta commands\n\nCommands that need a workspace feature flag (CRM, Studio and others) are beta. Help and `kenso describe` hide the ones your workspace has not enabled and say how many they hid; `--all-commands` shows them. Calling a hidden command still works: Kenso decides. `kenso <resource>` on a resource whose every action is hidden answers `feature_not_enabled` (exit 2) and names the flags it needs.\n\n```bash\nkenso --help --all-commands\nkenso describe --all-commands\n```\n\n## What the CLI sends\n\nEvery API call carries `Authorization: Bearer <key>`, `Ken-Version: 1.1`, `X-Ken-Workspace-Id` (when a workspace is picked), `User-Agent: kenso-cli/<version> (node <version>; <platform>)` and `X-Ken-Client: Kenso CLI`. When a coding agent runs the CLI, `X-Ken-Client` names it (`Kenso CLI via Claude Code`) and writes carry `X-Ken-Actor: agent`, so Kenso\'s activity log shows who made a change.\n';
7249
+ output_and_errors_default = '# Output and errors\n\nEvery command follows one contract, so a script or an agent can parse any of them the same way.\n\n## stdout and stderr\n\n- **stdout carries data only.** Progress, warnings, notices and errors go to stderr.\n- No colors, spinners or pagers. On a terminal you get readable tables; in a pipe you get JSON.\n- A batch command (an import, update, remove, tag or `--each` write) takes `--yes`; without it, the command plans or refuses.\n- A command that deletes, archives or removes, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive` or `kenso api DELETE /v1/tags/7`, needs `--yes` too. Without it, a person at a terminal is asked to confirm; anywhere else (a pipe, a script, CI, a coding agent) it sends nothing and fails with `confirmation_required`, whose `next` is the same command with `--yes`.\n- Any other single write, such as `kenso tags create` or a write through `kenso api` or `kenso mcp call`, sends at once: add `--dry-run` to print the request first (it sends nothing), then run the command without it.\n- A command with no dry run, such as `kenso contacts export`, `kenso auth logout` or `kenso workspace use`, refuses `--dry-run` with `usage_error` (exit 2) and does nothing. Its help ends with `No --dry-run`, and `kenso describe <resource> <action>` shows `"dryRun": false`.\n\n## Formats\n\n| What the command returns | stdout is a terminal | stdout is a pipe or file |\n|---|---|---|\n| One object | key-value lines | compact JSON on one line |\n| A list | a table (first 8 scalar fields, cells cut at 60 characters) | NDJSON: one JSON object per line |\n| A batch run | key-value lines | one JSON summary object |\n| No content (HTTP 204) | nothing | nothing |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table` or `ids`. `--json` is the same as `-o json`.\n\n- `-o json` on a list prints one JSON array. On a terminal, `-o json` pretty-prints an object.\n- `-o ids` prints one id per line, ready for `--ids -`. Items without an `id` are skipped with one warning.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso contacts list --campaign-id 812 --all -o ids\n```\n\n## Shape the output\n\n- `--fields a,b.c` keeps only those fields (dots reach into nested objects).\n- `--query <JMESPath>` filters or reshapes in-process, so you need no `jq`. On a list it sees the whole list. There is no `--jq`: `--query` takes JMESPath, not jq syntax.\n- Neither applies to a batch summary, which always prints in full.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\n```\n\n## Lists and pages\n\nA list command prints one page. When there are more, it prints the command for the next page on stderr, for example `next: kenso tags list --limit 1 --cursor MQ`. `--all` follows every page and streams the items. `--limit` sets the page size and `--cursor` starts at a cursor.\n\n`accounts search`, `contacts search` and `people search` page the same way: one page with the `next:` command, or every page with `--all`. A search that asks for counts (`countBy` in `--data`) prints the whole answer instead: `data`, `pagination` and `counts`. Counts cover every match whatever the page, so ask for them on one page (`--limit 1`): `--all` with `countBy` is a usage error.\n\n```bash\nkenso tags list --limit 50\nkenso tags list --all\n```\n\n## Errors\n\nWhen stderr is not a terminal, an error is one JSON line on stderr:\n\n```json\n{"error":{"code":"unknown_flag","message":"Unknown flag --fiel for kenso contacts import.","field":"fiel","hint":"did you mean --file?","next":"kenso contacts import --help"}}\n```\n\n| Key | Always there | Meaning |\n|---|---|---|\n| `code` | yes | A stable snake_case code to branch on |\n| `message` | yes | One sentence for a person |\n| `field` | no | The flag or input field at fault |\n| `hint` | no | What to change |\n| `next` | no | The exact command to run next, such as `kenso auth login`, `kenso workspace list --search <name>` or the same command with `--yes` |\n| `httpStatus` | no | The API\'s HTTP status, when the API answered |\n| `requestId` | no | The API\'s request id: quote it when you contact Kenso support |\n\nOn a terminal the same error prints as text: `Error: <message>`, then `field:`, `hint:`, `next:` and `requestId:` lines. The key never appears in an error.\n\n### How API errors map\n\nThe CLI looks at the HTTP status first, then at the API\'s own `error.code`, which wins when present.\n\n| HTTP status | Default code | Exit |\n|---|---|---|\n| 400, 422 | `validation_failed` | 2 |\n| 401 | `unauthorized` (`next`: `kenso auth login`) | 3 |\n| 403 | `forbidden`: the key\'s user or role cannot do this in this workspace | 3 |\n| 404 | `not_found` | 4 |\n| 409 | `conflict` | 7 |\n| 429 | `rate_limited`, after the CLI waited and retried | 6 |\n| 5xx | `server_error`, after retries where they are safe | 8 |\n| anything else | `http_error` | 1 |\n\nTwo API codes change the exit code: `workspace_required` exits 2 with `"next":"kenso workspace list --search <name>"`, and `limit_reached` (the plan\'s or the campaign\'s lead limit) exits 6.\n\n### Errors from the CLI itself\n\n| Code | Exit | When |\n|---|---|---|\n| `usage_error` | 2 | A required flag or argument is missing, two flags conflict (`--yes` with `--dry-run`), or `--dry-run` on a command that has no dry run |\n| `unknown_command` | 2 | No such command; `hint` suggests the closest one |\n| `unknown_flag`, `invalid_flag`, `invalid_flag_value`, `unexpected_argument` | 2 | A flag or argument the command does not take |\n| `invalid_query` | 2 | `--query` is not valid JMESPath |\n| `confirmation_required` | 2 | A delete, archive or remove ran without `--yes` where nobody can confirm: nothing was sent; `next` adds `--yes` |\n| `cancelled` | 2 | A person answered no to the confirmation: nothing was sent |\n| `file_unreadable` | 2 | An input file is missing, is a folder, cannot be opened, or cannot be parsed; the message names the line, such as `leads.csv line 3: a quote is not closed.` |\n| `config_invalid` | 2 | `~/.kenso/config.json` is not valid JSON: fix or delete it |\n| `feature_not_enabled` | 2 | Every action of the resource is a beta command your workspace has not enabled |\n| `invalid_key_format`, `key_required` | 2 | `auth login --with-key` read something that is not a Kenso key, or stdin is a terminal instead of a pipe |\n| `invalid_workspace_id` | 2 | `kenso workspace use` got an id that is not a positive whole number |\n| `unknown_topic` | 2 | `kenso docs` got a topic it does not have; `hint` lists the topics |\n| `file_unwritable` | 2 or 1 | An output file cannot be written: `contacts export --out` (2), `skill install` (1) |\n| `no_api_key` | 3 | No key in `KENSO_API_KEY` or the profile (`next`: `kenso auth login`) |\n| `browser_login_unavailable`, `access_denied`, `login_expired` | 3 | Browser login is off, was denied, or timed out |\n| `run_not_found` | 4 | `kenso runs show` or `resume` got an unknown run id |\n| `docs_not_found` | 4 | `kenso docs reference` before the reference was generated (a source checkout without `pnpm build`) |\n| `run_in_progress`, `already_filled` | 7 | Another process is working on the run, or `studio fill` already ran with this file and these flags |\n| `skill_exists` | 7 | `kenso skill install` found a different `SKILL.md`; `next` adds `--force` to replace it |\n| `job_timeout`, `job_failed`, `job_canceled` | 1 | `kenso jobs wait` (or a command that waits on a job) ran out of time, or the job failed or was canceled |\n| `mcp_tool_error` | 1 | `kenso mcp call`: the MCP tool answered with an error |\n| `unsafe_path` | 1 | `studio pull` refused a file path that would land outside `--dir` |\n| `network_error` | 8 | The API could not be reached after retries |\n| `upload_failed`, `download_failed` | 8 or 1 | A signed upload or download of a Studio file failed: 8 when storage was unreachable or answered 5xx, 1 on a 4xx (often an expired link: run the command again) |\n| `pull_incomplete` | 8 | `studio pull`: a file came back with neither text nor a download link |\n| `unexpected_response` | 1 or 8 | The API answered something the CLI could not read |\n| `unexpected_error` | 1 | A bug: run again with `--verbose` and report it |\n| `interrupted` | 130 | Ctrl-C |\n\n## Exit codes\n\n| Code | Meaning |\n|---|---|\n| 0 | OK, including a batch where every row succeeded or was skipped |\n| 1 | Unexpected error |\n| 2 | Usage or input error: a bad flag, a bad file, a validation error |\n| 3 | Auth: no key, an invalid, revoked or expired key, or HTTP 401 or 403 |\n| 4 | Not found |\n| 5 | Partial: the batch finished and some rows failed, were not found or were invalid. See `results.csv` |\n| 6 | Rate limited after retries, or a plan or campaign lead limit stopped the run (`limit_reached`) |\n| 7 | Conflict or invalid state (HTTP 409), or a run another process holds |\n| 8 | Server error after retries (5xx), or the API is unreachable |\n| 9 | Answer refused: a Kenso sandbox run stopped because an answer held a credential or something shaped like one |\n| 130 | Interrupted. A batch run can be resumed: see its `next` |\n\nSkipped rows (duplicates, blocklisted, already contacted) are not failures: a batch with only created, updated and skipped rows exits 0.\n\n## Flags\n\n- Command flags go after the command: `kenso contacts import --campaign 812`. Global flags can go anywhere.\n- A boolean flag takes `--flag`, `--no-flag`, `--flag=true` and `--flag=false`.\n- A flag that carries a secret (`--password`, `--api-key`, `--api-secret`, any `--\u2026-token` or `--\u2026-secret`) also takes `-` (read stdin), `@file` (read the file) or `env:NAME` (read that environment variable), so the value stays out of shell history: `printf \'%s\' "$FATHOM_KEY" | kenso fathom-connection connect --api-key -`. A value typed on the command line still works and prints one warning. A typed secret that itself starts with `@` is written `@@` (`--password @@Spring2026` sends `@Spring2026`); one that is exactly `-` or starts with `env:` has to come through `@file` or `env:NAME`. `-` refuses a terminal, an empty value is refused, and only one flag can read stdin. `--dry-run` shows a secret as `***`. With `--each`, the plan, its `next` and the run record keep `@file` or `env:NAME` as typed and `kenso runs resume` reads it again; a secret from stdin is refused there.\n- `--help` on any command prints its flags, arguments and examples. `kenso describe <resource> <action>` prints the same as JSON, with the body schema.\n\n## Beta commands\n\nCommands that need a workspace feature flag (CRM, Studio and others) are beta. Help and `kenso describe` hide the ones your workspace has not enabled and say how many they hid; `--all-commands` shows them. Calling a hidden command still works: Kenso decides. `kenso <resource>` on a resource whose every action is hidden answers `feature_not_enabled` (exit 2) and names the flags it needs.\n\n```bash\nkenso --help --all-commands\nkenso describe --all-commands\n```\n\n## What the CLI sends\n\nEvery API call carries `Authorization: Bearer <key>`, `Ken-Version: 1.1`, `X-Ken-Workspace-Id` (when a workspace is picked), `User-Agent: kenso-cli/<version> (node <version>; <platform>)` and `X-Ken-Client: Kenso CLI`. When a coding agent runs the CLI, `X-Ken-Client` names it (`Kenso CLI via Claude Code`) and writes carry `X-Ken-Actor: agent`, so Kenso\'s activity log shows who made a change.\n';
7153
7250
  }
7154
7251
  });
7155
7252
 
@@ -8396,27 +8493,58 @@ var logout_exports = {};
8396
8493
  __export(logout_exports, {
8397
8494
  default: () => logout_default
8398
8495
  });
8496
+ async function revoke(ctx, apiKey, keyId, savedWorkspaceId) {
8497
+ const auth = { Authorization: `Bearer ${apiKey}` };
8498
+ try {
8499
+ let workspaceId = savedWorkspaceId;
8500
+ if (!workspaceId) {
8501
+ const me = await ctx.client.request({ method: "GET", path: "/v1/me", anonymous: true, noWorkspace: true, headers: auth, signal: ctx.signal });
8502
+ const first = unwrap(me.body)?.workspaces?.[0]?.id;
8503
+ workspaceId = first !== void 0 ? String(first) : void 0;
8504
+ }
8505
+ await ctx.client.request({
8506
+ method: "DELETE",
8507
+ path: `/v1/api-keys/${encodeURIComponent(keyId)}`,
8508
+ anonymous: true,
8509
+ noWorkspace: true,
8510
+ headers: workspaceId ? { ...auth, "X-Ken-Workspace-Id": workspaceId } : auth,
8511
+ signal: ctx.signal
8512
+ });
8513
+ return true;
8514
+ } catch (err) {
8515
+ if (err instanceof KensoError && err.exitCode === ExitCode.Interrupted) throw err;
8516
+ const why = err instanceof Error ? err.message : String(err);
8517
+ ctx.output.warn(`Could not revoke the key (${why}). The profile is removed anyway; revoke the key at Settings > Integrations > API keys.`);
8518
+ return false;
8519
+ }
8520
+ }
8399
8521
  var command6, logout_default;
8400
8522
  var init_logout = __esm({
8401
8523
  "src/commands/auth/logout.ts"() {
8402
8524
  "use strict";
8403
8525
  init_config();
8526
+ init_errors();
8527
+ init_http();
8404
8528
  init_exit_codes();
8405
8529
  command6 = {
8406
8530
  resource: "auth",
8407
8531
  action: "logout",
8408
- summary: "Remove a saved profile and its key",
8409
- description: "Removes the profile (--profile, KENSO_PROFILE or the active one) from ~/.kenso/config.json. The key itself stays valid: revoke it at Settings > Integrations > API keys.",
8410
- flags: {},
8411
- examples: ["kenso auth logout", "kenso auth logout --profile client-a"],
8412
- operationIds: [],
8413
- async run(ctx) {
8414
- const profile = ctx.auth.profileName;
8415
- const removed = profile in readConfig(ctx.env).profiles;
8416
- if (removed) removeProfile(profile, ctx.env);
8532
+ summary: "Remove a saved profile, and revoke the key browser login made",
8533
+ description: "Removes the profile (--profile, KENSO_PROFILE or the active one) from ~/.kenso/config.json. When browser login made its key, it revokes that key first (--keep-key keeps it valid); if the revoke fails it warns and still removes the profile. A key saved with --with-key stays valid: revoke it at Settings > Integrations > API keys.",
8534
+ flags: {
8535
+ "keep-key": { type: "boolean", description: "Remove the profile but leave its key valid" }
8536
+ },
8537
+ examples: ["kenso auth logout", "kenso auth logout --profile client-a", "kenso auth logout --keep-key"],
8538
+ operationIds: ["me.get", "api-keys.delete"],
8539
+ async run(ctx, { flags }) {
8540
+ const name = ctx.auth.profileName;
8541
+ const profile = readConfig(ctx.env).profiles[name];
8542
+ const removed = profile !== void 0;
8543
+ const revoked = profile?.apiKey && profile.keyId && flags["keep-key"] !== true ? await revoke(ctx, profile.apiKey, profile.keyId, profile.workspaceId) : false;
8544
+ if (removed) removeProfile(name, ctx.env);
8417
8545
  clearCache(ctx.env);
8418
8546
  if (ctx.auth.source === "env") ctx.output.warn("KENSO_API_KEY is still set, so commands keep using that key.");
8419
- ctx.output.object({ profile, removed });
8547
+ ctx.output.object({ profile: name, removed, revoked });
8420
8548
  return ExitCode.Ok;
8421
8549
  }
8422
8550
  };
@@ -8632,7 +8760,7 @@ var init_completion2 = __esm({
8632
8760
 
8633
8761
  // src/commands/contacts/common.ts
8634
8762
  import { createHash as createHash3 } from "node:crypto";
8635
- import { readFile as readFile5 } from "node:fs/promises";
8763
+ import { readFile as readFile6 } from "node:fs/promises";
8636
8764
  import { resolve as resolve5 } from "node:path";
8637
8765
  function stringFlag2(flags, name) {
8638
8766
  const value = flags[name];
@@ -8687,7 +8815,7 @@ function sameCommand2(command36, flags, ctx, extra = []) {
8687
8815
  return parts2.join(" ");
8688
8816
  }
8689
8817
  async function fileSha256(path) {
8690
- return createHash3("sha256").update(await readFile5(resolve5(path))).digest("hex");
8818
+ return createHash3("sha256").update(await readFile6(resolve5(path))).digest("hex");
8691
8819
  }
8692
8820
  function rateLimitRemaining3(headers) {
8693
8821
  const raw = headers.get("ratelimit-remaining");
@@ -9325,7 +9453,7 @@ var init_wait = __esm({
9325
9453
  });
9326
9454
 
9327
9455
  // src/commands/contacts/server-import.ts
9328
- import { readFile as readFile6 } from "node:fs/promises";
9456
+ import { readFile as readFile7 } from "node:fs/promises";
9329
9457
  import { basename as basename3, extname as extname2, resolve as resolve6 } from "node:path";
9330
9458
  function csvTargetOf(header, mapping) {
9331
9459
  if (mapping.dropped[header] !== "reserved_name") return void 0;
@@ -9355,7 +9483,7 @@ async function readUpload2(file) {
9355
9483
  }
9356
9484
  const path = resolve6(file);
9357
9485
  try {
9358
- const bytes = await readFile6(path);
9486
+ const bytes = await readFile7(path);
9359
9487
  const name = ext === ".csv" ? basename3(path) : `${basename3(path, extname2(path))}.csv`;
9360
9488
  return { bytes, name, path };
9361
9489
  } catch (err) {
@@ -9805,7 +9933,7 @@ var init_update = __esm({
9805
9933
 
9806
9934
  // src/commands/contacts/bulk-store.ts
9807
9935
  import { existsSync as existsSync5 } from "node:fs";
9808
- import { appendFile as appendFile2, readFile as readFile7, writeFile as writeFile2 } from "node:fs/promises";
9936
+ import { appendFile as appendFile2, readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises";
9809
9937
  import { join as join11 } from "node:path";
9810
9938
  function whereDir(env) {
9811
9939
  return join11(runsRoot(env), WHERE_DIR);
@@ -9834,7 +9962,7 @@ function chunkAttempts(env) {
9834
9962
  return async (runId, chunkIndex) => {
9835
9963
  earlier ??= (async () => {
9836
9964
  const path2 = join11(runsRoot(env), runId, ATTEMPTS_FILE);
9837
- const text3 = await readFile7(path2, "utf8").catch(() => "");
9965
+ const text3 = await readFile8(path2, "utf8").catch(() => "");
9838
9966
  const indexes3 = new Set(
9839
9967
  text3.split("\n").filter((line) => line.trim() !== "").map(Number)
9840
9968
  );
@@ -11160,7 +11288,7 @@ __export(resume_exports, {
11160
11288
  });
11161
11289
  import { createHash as createHash5 } from "node:crypto";
11162
11290
  import { existsSync as existsSync7 } from "node:fs";
11163
- import { readFile as readFile8 } from "node:fs/promises";
11291
+ import { readFile as readFile9 } from "node:fs/promises";
11164
11292
  import { resolve as resolve9 } from "node:path";
11165
11293
  function kebab(key) {
11166
11294
  return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
@@ -11205,7 +11333,7 @@ function resumeArgv(run, globals = {}) {
11205
11333
  return argv;
11206
11334
  }
11207
11335
  async function sha256(path) {
11208
- return createHash5("sha256").update(await readFile8(path)).digest("hex");
11336
+ return createHash5("sha256").update(await readFile9(path)).digest("hex");
11209
11337
  }
11210
11338
  var SKIPPED_KEYS, command21, resume_default;
11211
11339
  var init_resume = __esm({
@@ -11327,7 +11455,7 @@ var init_common2 = __esm({
11327
11455
  });
11328
11456
 
11329
11457
  // src/commands/studio/folder.ts
11330
- import { readdir as readdir2, readFile as readFile9, stat as stat2 } from "node:fs/promises";
11458
+ import { readdir as readdir2, readFile as readFile10, stat as stat2 } from "node:fs/promises";
11331
11459
  import { extname as extname3, isAbsolute, join as join13, relative, resolve as resolve10, sep } from "node:path";
11332
11460
  function textOf2(bytes) {
11333
11461
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
@@ -11353,7 +11481,7 @@ async function readFolder(dir) {
11353
11481
  const abs = join13(folder, entry.name);
11354
11482
  if (entry.isDirectory()) await walk(abs);
11355
11483
  else if (entry.isFile()) {
11356
- const bytes = await readFile9(abs);
11484
+ const bytes = await readFile10(abs);
11357
11485
  files.push({ path: relative(root2, abs).split(sep).join("/"), bytes, text: textOf2(bytes) });
11358
11486
  }
11359
11487
  }
@@ -11986,7 +12114,7 @@ __export(fill_exports, {
11986
12114
  default: () => fill_default
11987
12115
  });
11988
12116
  import { createHash as createHash8 } from "node:crypto";
11989
- import { readFile as readFile10 } from "node:fs/promises";
12117
+ import { readFile as readFile11 } from "node:fs/promises";
11990
12118
  import { join as join14, resolve as resolve12 } from "node:path";
11991
12119
  async function readTarget(ctx, flags) {
11992
12120
  const accounts = stringFlag(flags.accounts);
@@ -12020,7 +12148,7 @@ async function readTarget(ctx, flags) {
12020
12148
  items: [...firstRow].map(([id, row]) => ({ id, row })),
12021
12149
  duplicates: raw.length - firstRow.size,
12022
12150
  ...campaign !== void 0 ? { campaignId: positiveId2(campaign, "campaign") } : {},
12023
- input: source === "-" ? { path: "-", sha256: sha2562(raw.join("\n")) } : { path: resolve12(source), sha256: sha2562(await readFile10(resolve12(source))) }
12151
+ input: source === "-" ? { path: "-", sha256: sha2562(raw.join("\n")) } : { path: resolve12(source), sha256: sha2562(await readFile11(resolve12(source))) }
12024
12152
  };
12025
12153
  }
12026
12154
  async function refuseRefill(ctx, args, target) {