kenso 0.1.44 → 0.1.46

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
@@ -1292,7 +1292,7 @@ var require_jmespath = __commonJS({
1292
1292
  }
1293
1293
  },
1294
1294
  _parseSliceExpression: function() {
1295
- var parts = [null, null, null];
1295
+ var parts2 = [null, null, null];
1296
1296
  var index = 0;
1297
1297
  var currentToken = this._lookahead(0);
1298
1298
  while (currentToken !== TOK_RBRACKET && index < 3) {
@@ -1300,7 +1300,7 @@ var require_jmespath = __commonJS({
1300
1300
  index++;
1301
1301
  this._advance();
1302
1302
  } else if (currentToken === TOK_NUMBER) {
1303
- parts[index] = this._lookaheadToken(0).value;
1303
+ parts2[index] = this._lookaheadToken(0).value;
1304
1304
  this._advance();
1305
1305
  } else {
1306
1306
  var t = this._lookahead(0);
@@ -1313,7 +1313,7 @@ var require_jmespath = __commonJS({
1313
1313
  this._match(TOK_RBRACKET);
1314
1314
  return {
1315
1315
  type: "Slice",
1316
- children: parts
1316
+ children: parts2
1317
1317
  };
1318
1318
  },
1319
1319
  _parseComparator: function(left, comparator) {
@@ -2413,7 +2413,7 @@ var VERSION;
2413
2413
  var init_version = __esm({
2414
2414
  "src/core/version.ts"() {
2415
2415
  "use strict";
2416
- VERSION = true ? "0.1.44" : "0.0.0-dev";
2416
+ VERSION = true ? "0.1.46" : "0.0.0-dev";
2417
2417
  }
2418
2418
  });
2419
2419
 
@@ -2668,6 +2668,11 @@ var init_confirm = __esm({
2668
2668
 
2669
2669
  // src/core/input.ts
2670
2670
  import { readFile } from "node:fs/promises";
2671
+ function fileUnreadable(path, err, field = "file", hintOverride) {
2672
+ const code = err?.code;
2673
+ 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."];
2674
+ return new KensoError({ code: "file_unreadable", message, exitCode: ExitCode.Usage, field, hint: hintOverride ?? hint });
2675
+ }
2671
2676
  async function readStream(stream, maxBytes = DEFAULT_MAX_BYTES) {
2672
2677
  const chunks = [];
2673
2678
  let size = 0;
@@ -2692,13 +2697,7 @@ async function readDataArg(value, stdin) {
2692
2697
  try {
2693
2698
  text3 = await readFile(path, "utf8");
2694
2699
  } 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
- });
2700
+ throw fileUnreadable(path, err);
2702
2701
  }
2703
2702
  } else {
2704
2703
  source = "the inline value";
@@ -2723,6 +2722,74 @@ var init_input = __esm({
2723
2722
  }
2724
2723
  });
2725
2724
 
2725
+ // src/core/secret-flags.ts
2726
+ import { readFile as readFile2 } from "node:fs/promises";
2727
+ function isSecretFlag(name, type) {
2728
+ return type === "string" && SECRET_NAME.test(name);
2729
+ }
2730
+ function readValue(flag, source, text3) {
2731
+ const value = text3.replace(/\r?\n$/, "");
2732
+ if (value === "") throw usageError(`--${flag} read nothing from ${source}.`, { field: flag, hint: `Put the value in ${source}, or pass env:NAME.` });
2733
+ return value;
2734
+ }
2735
+ function checkSecretSources(flags, secretFlags) {
2736
+ const fromStdin = secretFlags.filter((flag) => flags[flag] === "-");
2737
+ if (fromStdin.length > 0 && flags.each !== void 0) {
2738
+ throw usageError(`--each cannot read --${fromStdin[0]} from stdin: a resumed run could not read it again.`, { field: fromStdin[0], hint: OTHER_FORMS });
2739
+ }
2740
+ const readers = [...fromStdin, ...flags.data === "-" ? ["data"] : []].map((flag) => `--${flag}`);
2741
+ if (readers.length > 1) throw usageError(`Only one flag can read stdin, and ${readers.join(" and ")} both pass -.`, { field: fromStdin[0], hint: OTHER_FORMS });
2742
+ }
2743
+ async function readSecretFlag(ctx, flag, raw) {
2744
+ if (raw === "-") {
2745
+ const stdin = ctx.stdin ?? process.stdin;
2746
+ if (stdin.isTTY === true) {
2747
+ 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.` });
2748
+ }
2749
+ return readValue(flag, "stdin", await readStream(stdin));
2750
+ }
2751
+ if (raw.startsWith("@") && !raw.startsWith("@@") && raw.length > 1) {
2752
+ const path = raw.slice(1);
2753
+ let text3;
2754
+ try {
2755
+ text3 = await readFile2(path, "utf8");
2756
+ } catch (err) {
2757
+ throw fileUnreadable(path, err, flag, `--${flag} @path reads a file. A value that itself starts with @ is written @@, for example @@Spring2026.`);
2758
+ }
2759
+ return readValue(flag, path, text3);
2760
+ }
2761
+ if (raw.startsWith("env:") && raw.length > 4) {
2762
+ const name = raw.slice(4);
2763
+ const value = ctx.env[name];
2764
+ if (!value) {
2765
+ throw usageError(`--${flag} reads the environment variable ${name}, which is not set or is empty.`, {
2766
+ field: flag,
2767
+ hint: `Set ${name} first, or pass the value with - (stdin) or @file.`
2768
+ });
2769
+ }
2770
+ return value;
2771
+ }
2772
+ ctx.output.warn(`--${flag} typed on the command line lands in shell history. Next time pass - (stdin), @file or env:NAME.`);
2773
+ return raw.startsWith("@@") ? raw.slice(1) : raw;
2774
+ }
2775
+ function maskSecrets(body, secrets) {
2776
+ if (secrets.size === 0 || body === null || typeof body !== "object" || Array.isArray(body)) return body;
2777
+ const out = { ...body };
2778
+ for (const key of secrets) if (typeof out[key] === "string") out[key] = "***";
2779
+ return out;
2780
+ }
2781
+ var SECRET_NAME, SECRET_HELP, OTHER_FORMS;
2782
+ var init_secret_flags = __esm({
2783
+ "src/core/secret-flags.ts"() {
2784
+ "use strict";
2785
+ init_errors();
2786
+ init_input();
2787
+ SECRET_NAME = /(^|-)(password|secret|token|api-key)$/;
2788
+ SECRET_HELP = "Pass -, @file or env:NAME to keep it out of shell history.";
2789
+ OTHER_FORMS = "Pass it as @file or env:NAME instead.";
2790
+ }
2791
+ });
2792
+
2726
2793
  // node_modules/.pnpm/csv-stringify@6.9.0/node_modules/csv-stringify/lib/utils/get.js
2727
2794
  var charCodeOfDot, reEscapeChar, rePropName, reIsDeepProp, reIsPlainProp, getTag, isSymbol, isKey, stringToPath, castPath, toKey, get;
2728
2795
  var init_get = __esm({
@@ -3428,7 +3495,7 @@ var init_sync = __esm({
3428
3495
  // src/batch/results.ts
3429
3496
  import { createHash } from "node:crypto";
3430
3497
  import { readFileSync as readFileSync4 } from "node:fs";
3431
- import { readFile as readFile2 } from "node:fs/promises";
3498
+ import { readFile as readFile3 } from "node:fs/promises";
3432
3499
  import { join as join3 } from "node:path";
3433
3500
  function filesOf(dir) {
3434
3501
  return {
@@ -3478,7 +3545,7 @@ async function readResults(path) {
3478
3545
  const results = /* @__PURE__ */ new Map();
3479
3546
  let text3;
3480
3547
  try {
3481
- text3 = await readFile2(path, "utf8");
3548
+ text3 = await readFile3(path, "utf8");
3482
3549
  } catch {
3483
3550
  return results;
3484
3551
  }
@@ -3556,7 +3623,7 @@ var init_results = __esm({
3556
3623
  // src/batch/runs.ts
3557
3624
  import { randomBytes } from "node:crypto";
3558
3625
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync2 } from "node:fs";
3559
- import { readdir, readFile as readFile3, realpath, rename, unlink, writeFile } from "node:fs/promises";
3626
+ import { readdir, readFile as readFile4, realpath, rename, unlink, writeFile } from "node:fs/promises";
3560
3627
  import { join as join4, resolve } from "node:path";
3561
3628
  function runsRoot(env = process.env) {
3562
3629
  const override2 = env.KENSO_RUNS_DIR?.trim();
@@ -3622,7 +3689,7 @@ async function writeRunRecord(record) {
3622
3689
  await writeJsonAtomic(join4(dir, "run.json"), rest);
3623
3690
  }
3624
3691
  async function readJson(path) {
3625
- return JSON.parse(await readFile3(path, "utf8"));
3692
+ return JSON.parse(await readFile4(path, "utf8"));
3626
3693
  }
3627
3694
  function asRecord3(value) {
3628
3695
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -3639,9 +3706,9 @@ async function readRunDir(dir) {
3639
3706
  return null;
3640
3707
  }
3641
3708
  if (!raw) return null;
3642
- const { runId, command: command35, createdAt, status } = raw;
3709
+ const { runId, command: command36, createdAt, status } = raw;
3643
3710
  if (typeof runId !== "string" || !RUN_ID_PATTERN.test(runId)) return null;
3644
- if (typeof command35 !== "string" || typeof createdAt !== "string") return null;
3711
+ if (typeof command36 !== "string" || typeof createdAt !== "string") return null;
3645
3712
  if (typeof status !== "string" || !STATUSES.includes(status)) return null;
3646
3713
  let chunksDone = chunkList(raw.chunksDone) ?? [];
3647
3714
  try {
@@ -3652,7 +3719,7 @@ async function readRunDir(dir) {
3652
3719
  const record = {
3653
3720
  ...raw,
3654
3721
  runId,
3655
- command: command35,
3722
+ command: command36,
3656
3723
  args: asRecord3(raw.args) ?? {},
3657
3724
  createdAt,
3658
3725
  status,
@@ -3707,11 +3774,11 @@ async function loadRun(runId, env = process.env) {
3707
3774
  }
3708
3775
  return run;
3709
3776
  }
3710
- async function findIdentical(command35, args, inputSha256, env, workspaceId, anyWorkspace = false) {
3777
+ async function findIdentical(command36, args, inputSha256, env, workspaceId, anyWorkspace = false) {
3711
3778
  const identity = argsIdentity(args);
3712
3779
  const runs = await listRuns(env);
3713
3780
  return runs.filter(
3714
- (run) => run.command === command35 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
3781
+ (run) => run.command === command36 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
3715
3782
  );
3716
3783
  }
3717
3784
  function isOtherLiveProcess(pid) {
@@ -3846,13 +3913,13 @@ async function dryRun(spec, ctx, plan) {
3846
3913
  };
3847
3914
  await writeJsonAtomic(files.planJson, planBody);
3848
3915
  if (plan.invalid.length > 0) await writeFileAtomic(files.invalidCsv, resultsToCsv(byRow(plan.invalid)));
3849
- const done = plan.finished ? 0 : plan.resumable?.chunksDone.length ?? 0;
3916
+ const done2 = plan.finished ? 0 : plan.resumable?.chunksDone.length ?? 0;
3850
3917
  const summary = {
3851
3918
  run: runId,
3852
3919
  ...planBody,
3853
3920
  plan: files.planJson,
3854
3921
  ...plan.invalid.length > 0 ? { invalidRows: files.invalidCsv } : {},
3855
- ...done > 0 ? { chunksDone: done } : {},
3922
+ ...done2 > 0 ? { chunksDone: done2 } : {},
3856
3923
  // The apply would change nothing: this run already finished every row.
3857
3924
  ...plan.finished ? { alreadyDone: true } : {}
3858
3925
  };
@@ -5938,7 +6005,7 @@ var init_sync2 = __esm({
5938
6005
 
5939
6006
  // src/batch/input.ts
5940
6007
  import { createHash as createHash2 } from "node:crypto";
5941
- import { readFile as readFile4, stat } from "node:fs/promises";
6008
+ import { readFile as readFile5, stat } from "node:fs/promises";
5942
6009
  import { extname, resolve as resolve3 } from "node:path";
5943
6010
  function tooLarge(source) {
5944
6011
  return usageError(`${source} is larger than 200 MB, the most the CLI reads in one run.`, {
@@ -5963,18 +6030,12 @@ async function readRaw(pathOrDash, stdin) {
5963
6030
  const path = resolve3(pathOrDash);
5964
6031
  try {
5965
6032
  const info = await stat(path);
5966
- if (info.isDirectory()) throw usageError(`${pathOrDash} is a directory, not a file.`, { field: "file" });
6033
+ if (info.isDirectory()) throw fileUnreadable(pathOrDash, { code: "EISDIR" });
5967
6034
  if (info.size > MAX_INPUT_BYTES) throw tooLarge(pathOrDash);
5968
- return { path, bytes: await readFile4(path) };
6035
+ return { path, bytes: await readFile5(path) };
5969
6036
  } catch (err) {
5970
6037
  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
- });
6038
+ throw fileUnreadable(pathOrDash, err);
5978
6039
  }
5979
6040
  }
5980
6041
  function stripBom(text3) {
@@ -5986,6 +6047,9 @@ function detectFormat(path, text3) {
5986
6047
  if (ext === ".jsonl" || ext === ".ndjson") return "jsonl";
5987
6048
  return stripBom(text3).trimStart().startsWith("{") ? "jsonl" : "csv";
5988
6049
  }
6050
+ function badFile(message, hint) {
6051
+ return new KensoError({ code: "file_unreadable", message, exitCode: ExitCode.Usage, field: "file", hint });
6052
+ }
5989
6053
  function parseCsv(text3, source) {
5990
6054
  let headers = [];
5991
6055
  let records;
@@ -6001,10 +6065,10 @@ function parseCsv(text3, source) {
6001
6065
  trim: false
6002
6066
  });
6003
6067
  } 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
- });
6068
+ const { code, lines } = err;
6069
+ const where = lines ? `${source} line ${lines}` : source;
6070
+ const problem = code ? CSV_PROBLEMS[code] : void 0;
6071
+ throw badFile(problem ? `${where}: ${problem}.` : `${where} is not valid CSV.`, "Check the quotes and commas there, or export the sheet again as CSV.");
6008
6072
  }
6009
6073
  const rows = records.map((record) => {
6010
6074
  const row = {};
@@ -6024,11 +6088,11 @@ function parseJsonl(text3, source) {
6024
6088
  let value;
6025
6089
  try {
6026
6090
  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" });
6091
+ } catch {
6092
+ 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
6093
  }
6030
6094
  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" });
6095
+ 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
6096
  }
6033
6097
  for (const key of Object.keys(value)) {
6034
6098
  if (!seen.has(key)) {
@@ -6089,14 +6153,24 @@ async function readIds(pathOrDash, opts) {
6089
6153
  }
6090
6154
  return ids2;
6091
6155
  }
6092
- var MAX_INPUT_BYTES;
6156
+ var MAX_INPUT_BYTES, CSV_PROBLEMS;
6093
6157
  var init_input2 = __esm({
6094
6158
  "src/batch/input.ts"() {
6095
6159
  "use strict";
6096
6160
  init_sync2();
6097
6161
  init_errors();
6098
6162
  init_exit_codes();
6163
+ init_input();
6099
6164
  MAX_INPUT_BYTES = 200 * 1024 * 1024;
6165
+ CSV_PROBLEMS = {
6166
+ CSV_QUOTE_NOT_CLOSED: "a quote is not closed",
6167
+ CSV_INVALID_CLOSING_QUOTE: "a quoted cell has more text after its closing quote",
6168
+ CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE: "a quoted cell has more text after its closing quote",
6169
+ CSV_RECORD_INCONSISTENT_COLUMNS: "the row has a different number of cells than the header",
6170
+ CSV_RECORD_INCONSISTENT_FIELDS_LENGTH: "the row has a different number of cells than the header",
6171
+ CSV_OPTION_COLUMNS_MISSING_NAME: "a header cell is empty",
6172
+ CSV_MAX_RECORD_SIZE: "the row is too long"
6173
+ };
6100
6174
  }
6101
6175
  });
6102
6176
 
@@ -6183,16 +6257,16 @@ function eachArgs(op, values, file) {
6183
6257
  return args;
6184
6258
  }
6185
6259
  function commandLine(op, args, ctx, extra) {
6186
- const parts = [`kenso ${op.resource} ${op.action}`];
6260
+ const parts2 = [`kenso ${op.resource} ${op.action}`];
6187
6261
  for (const [flag, value] of Object.entries(args)) {
6188
- if (value === true) parts.push(`--${flag}`);
6189
- else for (const item of Array.isArray(value) ? value : [value]) parts.push(`--${flag}`, shellQuote(String(item)));
6262
+ if (value === true) parts2.push(`--${flag}`);
6263
+ else for (const item of Array.isArray(value) ? value : [value]) parts2.push(`--${flag}`, shellQuote(String(item)));
6190
6264
  }
6191
6265
  for (const name of ["profile", "workspace"]) {
6192
6266
  const value = ctx.flags[name];
6193
- if (value !== void 0) parts.push(`--${name}`, shellQuote(value));
6267
+ if (value !== void 0) parts2.push(`--${name}`, shellQuote(value));
6194
6268
  }
6195
- return [...parts, ...extra].join(" ");
6269
+ return [...parts2, ...extra].join(" ");
6196
6270
  }
6197
6271
  function rateLimitRemaining(headers) {
6198
6272
  const value = Number(headers.get("ratelimit-remaining") ?? "");
@@ -6216,18 +6290,18 @@ async function sendRow(item, ctx) {
6216
6290
  return { results: [{ row: item.row, status, reason: code, error }] };
6217
6291
  }
6218
6292
  }
6219
- function preview(request) {
6293
+ function preview(request, op) {
6220
6294
  if (!request) return void 0;
6221
6295
  return {
6222
6296
  method: request.method,
6223
6297
  path: request.path,
6224
6298
  ...request.query ? { query: request.query } : {},
6225
- ...request.body !== void 0 ? { body: request.body } : {},
6299
+ ...request.body !== void 0 ? { body: maskSecrets(request.body, new Set(secretParams(op).map((s) => s.name))) } : {},
6226
6300
  ...request.form ? { form: [...request.form.keys()] } : {}
6227
6301
  };
6228
6302
  }
6229
6303
  async function runEach(ctx, op, values, file, opts = {}) {
6230
- const args = eachArgs(op, values, file);
6304
+ const args = eachArgs(op, opts.argValues ?? values, file);
6231
6305
  const applyCommand = commandLine(op, args, ctx, ["--yes"]);
6232
6306
  if (op.method !== "GET" && ctx.flags.yes !== true && ctx.flags.dryRun !== true) {
6233
6307
  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 +6333,7 @@ async function runEach(ctx, op, values, file, opts = {}) {
6259
6333
  execChunk: (chunk, chunkCtx) => sendRow(chunk[0], chunkCtx),
6260
6334
  invalid,
6261
6335
  dryRun: ctx.flags.dryRun === true,
6262
- dryRunExtra: { operationId: op.id, firstRequest: preview(items[0]?.request) },
6336
+ dryRunExtra: { operationId: op.id, firstRequest: preview(items[0]?.request, op) },
6263
6337
  applyCommand
6264
6338
  },
6265
6339
  ctx
@@ -6274,6 +6348,7 @@ var init_each = __esm({
6274
6348
  init_input2();
6275
6349
  init_errors();
6276
6350
  init_exit_codes();
6351
+ init_secret_flags();
6277
6352
  init_execute();
6278
6353
  DEFAULT_CONCURRENCY2 = 4;
6279
6354
  SERIAL_PER_PATH = "contacts.create";
@@ -6292,7 +6367,8 @@ __export(execute_exports, {
6292
6367
  isDestructive: () => isDestructive,
6293
6368
  operationExamples: () => operationExamples,
6294
6369
  operationFlags: () => operationFlags,
6295
- operationToCommand: () => operationToCommand
6370
+ operationToCommand: () => operationToCommand,
6371
+ secretParams: () => secretParams
6296
6372
  });
6297
6373
  import { readFileSync as readFileSync5 } from "node:fs";
6298
6374
  import { basename } from "node:path";
@@ -6416,8 +6492,7 @@ function readUpload(path, field) {
6416
6492
  try {
6417
6493
  return { blob: new Blob([readFileSync5(file)]), name: basename(file) };
6418
6494
  } 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" });
6495
+ throw fileUnreadable(file, err);
6421
6496
  }
6422
6497
  }
6423
6498
  function formValue(value) {
@@ -6504,7 +6579,7 @@ async function collectValues(ctx, op, flags) {
6504
6579
  } else if (f.type === "integer" || f.type === "number") {
6505
6580
  value = parseNumber(String(raw), f.flag, f.type === "integer");
6506
6581
  } else {
6507
- value = String(raw);
6582
+ value = f.location === "body" && isSecretFlag(f.flag, f.type) ? await readSecretFlag(ctx, f.flag, String(raw)) : String(raw);
6508
6583
  }
6509
6584
  if (value === void 0) continue;
6510
6585
  if (f.location === "body" && paramNames.has(f.param.name)) bodyOnly[f.param.name] = value;
@@ -6528,11 +6603,11 @@ function shellQuote2(value) {
6528
6603
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
6529
6604
  }
6530
6605
  function sameCommand(ctx, op, flags) {
6531
- const parts = [commandOf(op)];
6606
+ const parts2 = [commandOf(op)];
6532
6607
  for (const [name, value] of Object.entries(flags)) {
6533
6608
  if (value === void 0 || value === false || ["cursor", "all", "each"].includes(name)) continue;
6534
- if (value === true) parts.push(`--${name}`);
6535
- else for (const item of Array.isArray(value) ? value : [value]) parts.push(`--${name}`, shellQuote2(item));
6609
+ if (value === true) parts2.push(`--${name}`);
6610
+ else for (const item of Array.isArray(value) ? value : [value]) parts2.push(`--${name}`, shellQuote2(item));
6536
6611
  }
6537
6612
  const globals = [
6538
6613
  ["profile", ctx.flags.profile],
@@ -6541,17 +6616,18 @@ function sameCommand(ctx, op, flags) {
6541
6616
  ["fields", ctx.flags.fields],
6542
6617
  ["query", ctx.flags.query]
6543
6618
  ];
6544
- for (const [name, value] of globals) if (value !== void 0) parts.push(`--${name}`, shellQuote2(value));
6545
- return parts.join(" ");
6619
+ for (const [name, value] of globals) if (value !== void 0) parts2.push(`--${name}`, shellQuote2(value));
6620
+ return parts2.join(" ");
6546
6621
  }
6547
- function describeRequest(req) {
6622
+ function describeRequest(req, op) {
6623
+ const secrets = new Set(secretParams(op).map((s) => s.name));
6548
6624
  const out = { method: req.method, path: req.path };
6549
6625
  if (req.query) out.query = req.query;
6550
- if (req.body !== void 0) out.body = req.body;
6626
+ if (req.body !== void 0) out.body = maskSecrets(req.body, secrets);
6551
6627
  if (req.form) {
6552
6628
  const form = {};
6553
6629
  for (const [key, value] of req.form.entries()) {
6554
- const shown = typeof value === "string" ? value : { file: value.name, bytes: value.size };
6630
+ const shown = typeof value === "string" ? secrets.has(key) ? "***" : value : { file: value.name, bytes: value.size };
6555
6631
  const previous = form[key];
6556
6632
  form[key] = previous === void 0 ? shown : Array.isArray(previous) ? [...previous, shown] : [previous, shown];
6557
6633
  }
@@ -6567,15 +6643,21 @@ function eachConcurrency(raw) {
6567
6643
  }
6568
6644
  return value;
6569
6645
  }
6646
+ function secretParams(op) {
6647
+ return operationFlags(op).flatMap((f) => f.param && f.location === "body" && isSecretFlag(f.flag, f.type) ? [{ flag: f.flag, name: f.param.name }] : []);
6648
+ }
6570
6649
  async function runOperation(ctx, op, flags) {
6650
+ const secrets = secretParams(op);
6651
+ checkSecretSources(flags, secrets.map((s) => s.flag));
6571
6652
  const values = await collectValues(ctx, op, flags);
6572
6653
  if (typeof flags.each === "string") {
6573
6654
  const { runEach: runEach2 } = await Promise.resolve().then(() => (init_each(), each_exports));
6574
- return runEach2(ctx, op, values, flags.each, { concurrency: eachConcurrency(flags.concurrency) });
6655
+ const typed = Object.fromEntries(secrets.flatMap((s) => typeof flags[s.flag] === "string" ? [[s.name, flags[s.flag]]] : []));
6656
+ return runEach2(ctx, op, values, flags.each, { concurrency: eachConcurrency(flags.concurrency), argValues: { ...values, ...typed } });
6575
6657
  }
6576
6658
  const req = buildRequest(op, values);
6577
6659
  if (ctx.flags.dryRun) {
6578
- ctx.output.object({ dryRun: true, operationId: op.id, request: describeRequest(req) });
6660
+ ctx.output.object({ dryRun: true, operationId: op.id, request: describeRequest(req, op) });
6579
6661
  return ExitCode.Ok;
6580
6662
  }
6581
6663
  if (isDestructive(op)) await confirmDestructive(ctx, `${commandOf(op)} sends ${req.method} ${req.path}`, `${sameCommand(ctx, op, flags)} --yes`);
@@ -6629,10 +6711,11 @@ function operationToCommand(op) {
6629
6711
  for (const f of operationFlags(op)) {
6630
6712
  const shown = helpFlagText(f);
6631
6713
  cut ||= shown.cut;
6714
+ const text3 = f.location === "body" && isSecretFlag(f.flag, f.type) ? `${shown.text} ${SECRET_HELP}` : shown.text;
6632
6715
  const spec = {
6633
6716
  type: f.type === "boolean" ? "boolean" : "string",
6634
6717
  // 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
6718
+ description: f.required ? `${text3} (required)` : text3
6636
6719
  };
6637
6720
  if (f.multiple) spec.multiple = true;
6638
6721
  if (FOOTER_FLAGS.has(f.flag) && !f.param) spec.helpHidden = true;
@@ -6683,6 +6766,7 @@ var init_execute = __esm({
6683
6766
  init_exit_codes();
6684
6767
  init_http();
6685
6768
  init_input();
6769
+ init_secret_flags();
6686
6770
  DATA_KEY = "$data";
6687
6771
  SCALAR_TYPES = /* @__PURE__ */ new Set(["string", "integer", "number", "boolean"]);
6688
6772
  FLAG_ALIASES = [
@@ -6808,16 +6892,16 @@ function idValue(value, field) {
6808
6892
  function shellQuote3(arg) {
6809
6893
  return /^[A-Za-z0-9_./:=@%+,-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
6810
6894
  }
6811
- function commandLine2(ctx, command35, args, extra = []) {
6812
- const parts = ["kenso", ...command35.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
6895
+ function commandLine2(ctx, command36, args, extra = []) {
6896
+ const parts2 = ["kenso", ...command36.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
6813
6897
  for (const [name, value] of Object.entries(args.flags)) {
6814
6898
  if (value === void 0 || value === false) continue;
6815
- if (value === true) parts.push(`--${name}`);
6816
- else for (const item of Array.isArray(value) ? value : [value]) parts.push(`--${name}`, shellQuote3(item));
6899
+ if (value === true) parts2.push(`--${name}`);
6900
+ else for (const item of Array.isArray(value) ? value : [value]) parts2.push(`--${name}`, shellQuote3(item));
6817
6901
  }
6818
- if (ctx.flags.profile) parts.push("--profile", shellQuote3(ctx.flags.profile));
6819
- if (ctx.flags.workspace) parts.push("--workspace", shellQuote3(ctx.flags.workspace));
6820
- return [...parts, ...extra].join(" ");
6902
+ if (ctx.flags.profile) parts2.push("--profile", shellQuote3(ctx.flags.profile));
6903
+ if (ctx.flags.workspace) parts2.push("--workspace", shellQuote3(ctx.flags.workspace));
6904
+ return [...parts2, ...extra].join(" ");
6821
6905
  }
6822
6906
  function rateLimitRemaining2(headers) {
6823
6907
  const raw = headers.get("ratelimit-remaining");
@@ -6906,8 +6990,8 @@ __export(import_exports, {
6906
6990
  function domainsOf(row, columns2) {
6907
6991
  const list2 = firstValue(row, columns2.sources.get("domains"));
6908
6992
  if (list2 !== void 0) {
6909
- const parts = Array.isArray(list2) ? list2.map((v) => textValue(v, "domains") ?? "") : (textValue(list2, "domains") ?? "").split(/[,;]/);
6910
- return parts.map((p) => p.trim()).filter((p) => p !== "");
6993
+ const parts2 = Array.isArray(list2) ? list2.map((v) => textValue(v, "domains") ?? "") : (textValue(list2, "domains") ?? "").split(/[,;]/);
6994
+ return parts2.map((p) => p.trim()).filter((p) => p !== "");
6911
6995
  }
6912
6996
  const one = textValue(firstValue(row, columns2.sources.get("domain")), "domain");
6913
6997
  return one ? [one] : [];
@@ -7109,7 +7193,7 @@ var init_accounts = __esm({
7109
7193
  var agents_default;
7110
7194
  var init_agents = __esm({
7111
7195
  "docs/agents.md"() {
7112
- agents_default = '# Coding agents\n\nThe CLI is built to be driven by a coding agent: Claude Code, Codex, Cursor, Gemini CLI or anything else that runs shell commands. An agent learns it from the Agent Skill, `kenso --help` and `kenso describe`, and never needs these web pages.\n\n## Set up an agent in three steps\n\n1. Install the CLI where the agent runs: `npm i -g kenso` (Node 22 or newer). Without a global install, `npx -y kenso@latest <command>` runs any command.\n2. Give it a key. Either set `KENSO_API_KEY` (and `KENSO_WORKSPACE_ID` when the key reaches several workspaces) in the agent\'s environment, or log in once on that machine:\n\n```bash\nkenso auth login\nkenso workspace use 1234\n```\n\n3. Install the Agent Skill and connect the Kenso MCP server in one step, then check everything:\n\n```bash\nkenso agent setup\nkenso agent setup -y\nkenso doctor\n```\n\nTo hand the whole setup to an agent, give it [ken.so/get-started.md](https://ken.so/get-started.md): it runs these steps and stops only where a person has to act.\n\n## kenso agent setup\n\n`kenso agent setup` installs the `kenso-cli` skill (as `kenso skill install` does) and registers the Kenso MCP server, `https://mcp.ken.so/mcp`, with each coding agent:\n\n| Agent | `--client` | MCP server added with |\n|---|---|---|\n| Claude Code | `claude-code` | `claude mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| Codex | `codex` | `codex mcp add kenso --url https://mcp.ken.so/mcp` |\n| Cursor | `cursor` | a `kenso` entry in `~/.cursor/mcp.json` |\n| Gemini CLI | `gemini` | `gemini mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| OpenCode | `opencode` | a `kenso` entry in `~/.config/opencode/opencode.json` |\n\n```bash\nkenso agent setup --client claude-code -y\nkenso agent setup --client all -y\nkenso agent setup --status --json\n```\n\n- Without `--client`, it sets up the agent that runs it, else every agent found on the machine (its command on `PATH` or its config folder present).\n- Without `-y` it prints the plan and changes nothing; the plan\'s `next` applies it. `--status` reports, for every agent, whether the skill is `installed`, `missing` or `different` and whether the MCP server is `registered`, `missing`, in `conflict` or `unknown` (a config file it cannot read as JSON), and changes nothing. `--json` prints JSON on a terminal too.\n- An MCP entry with the Kenso URL under another name (such as `ken-ai` from the plugin) counts as registered, and nothing is added. A `kenso` entry pointing at another URL is left alone (`conflict`). A config file that is not plain JSON (it has comments) is left alone (`skipped`), and so is an agent whose command is not on `PATH`: their `next` is the command or edit to make by hand.\n- A different `SKILL.md` in the way stops the run before any change (exit 7) until you add `--force`.\n- It exits 1 when any agent was not fully set up. The MCP server signs in with your Kenso account in the browser the first time the agent uses it; each agent\'s `next` says how (in Claude Code, `/mcp`).\n\n## An AGENTS.md section for your repo\n\nPaste this into the `AGENTS.md` (or `CLAUDE.md`) of a repo whose agents work in Kenso:\n\n```markdown\n## Kenso\n\n- Kenso is our outbound platform. One record or a question: use the Kenso MCP server (https://mcp.ken.so/mcp). A file or more than about 50 records: use the `kenso` CLI.\n- Setup: `npm i -g kenso`, `kenso auth login` (a person approves in the browser), `kenso agent setup -y`, `kenso doctor`.\n- Every write runs first with `--dry-run`; apply with the plan\'s `next`. Never put an API key in a flag, a file or the chat: use `KENSO_API_KEY`.\n- Code that calls the API: send `Authorization: Bearer $KENSO_API_KEY`, `Ken-Version` and `X-Ken-Workspace-Id`. Reference: ken.so/docs.md; the kenso-api skill is listed at ken.so/.well-known/skills/index.json.\n```\n\n## The Agent Skill\n\n`kenso skill install` writes the skill `kenso-cli` (one `SKILL.md`) where each agent looks for skills:\n\n| Agent | `--client` | Folder |\n|---|---|---|\n| Claude Code | `claude-code` | `~/.claude/skills/kenso-cli/` |\n| Codex | `codex` | `~/.agents/skills/kenso-cli/` |\n| Cursor | `cursor` | `~/.cursor/skills/kenso-cli/` |\n| Gemini CLI | `gemini` | `~/.gemini/skills/kenso-cli/` |\n| OpenCode | `opencode` | `~/.config/opencode/skills/kenso-cli/` |\n\nClaude Code\'s folder follows `CLAUDE_CONFIG_DIR` when that is set. Without `--client`, it installs for the agent that runs it when that is Claude Code, Codex or Cursor (detected from the environment, see below), else for all five. It prints what it wrote:\n\n```json\n{"installed":[{"client":"claude-code","path":"/home/you/.claude/skills/kenso-cli/SKILL.md","status":"created"}]}\n```\n\n```bash\nkenso skill install --client claude-code\nkenso skill install --client all\nkenso skill install --dir .claude/skills/kenso-cli\nkenso skill install --force\n```\n\n- `--dir` writes the skill into that folder instead, for example a project\'s own skills folder. Name the folder `kenso-cli`, as agents expect the folder to match the skill name.\n- A different `SKILL.md` already in a target folder is replaced only with `--force`; without it the command exits 7, writes nothing, and its `next` adds `--force`. The same file is left alone (`"status":"unchanged"`).\n- `--dry-run` writes nothing and exits 0. It prints each target\'s status (`replaced` marks a different file there) and a `next` that applies it, with `--force` when a file would be replaced.\n- Cursor also reads `~/.claude/skills/` and `~/.agents/skills/` (Gemini CLI and OpenCode read `~/.agents/skills/` too), so after a default install for all of them an agent may list `kenso-cli` more than once. To avoid that, install with `--client cursor` only, or remove the copies you do not need.\n\nThe skill also ships in the Kenso plugin for Claude Code (`Ken-Technology/ken-ai-plugin`), so `npx skills add Ken-Technology/ken-ai-plugin` installs it along with the MCP skills. The plugin\'s copy is this file byte for byte. To read it without installing, open `skill/kenso-cli/SKILL.md` in the package.\n\n## Rules the skill teaches\n\n- **Data is on stdout, as JSON when piped.** Progress, warnings and errors are on stderr. Parse stdout; read stderr when the exit code is not 0.\n- **Plan, then apply.** Run a write with `--dry-run`, read the plan, then run the exact command in its `next` (the same command with `--yes`). A command with no dry run refuses `--dry-run` with `usage_error` and does nothing.\n- **Pass files, not rows.** Never paste a CSV into the conversation. Write the file, pass its path with `--file`, and read the summary.\n- **Read failures only.** If the summary\'s `failed`, `notFound` and `invalid` are 0, the work is done. Otherwise read just the problem rows from `results.csv` or `invalid.csv`.\n- **Follow `next`.** Every error with a known fix carries the exact command to run.\n- **Branch on the exit code:** 0 ok, 2 fix the command, 3 fix the key, 5 some rows failed, 6 wait or raise a limit, 130 resume.\n- **Look things up, do not guess.** `kenso describe <resource> <action>` prints any command\'s flags and body schema as JSON.\n\n## The token-saving pattern\n\nAdding 5,000 leads through the MCP sends every lead through the model, hundreds of thousands of tokens. Through the CLI it is two commands and two short JSON objects:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThen, only if the summary shows failures:\n\n```bash\ngrep -E \'^[0-9]+,(failed|not_found|invalid),\' ~/.kenso/runs/r_tdi5cdnx/results.csv | head -50\n```\n\n## Environment variables\n\n| Variable | What it does |\n|---|---|\n| `KENSO_API_KEY` | The API key. Wins over any saved profile |\n| `KENSO_WORKSPACE_ID` | The workspace for every command. `--workspace` wins over it |\n| `KENSO_PROFILE` | The saved profile to use. `--profile` wins over it |\n| `KENSO_API_URL` | The API, default `https://api.ken.so` |\n| `KENSO_CONFIG_DIR` | Where the config file and cache live, default `~/.kenso` |\n| `KENSO_RUNS_DIR` | Where run folders live, default `<config dir>/runs` |\n| `KENSO_MCP_URL` | The MCP for `kenso mcp`, default `https://mcp.ken.so/mcp` |\n\n## Cloud sandboxes\n\nCloud agents (Claude Code on the web, Codex cloud, Cursor background agents and similar) often run with a network allowlist. Allow:\n\n- `api.ken.so`: every command\n- `mcp.ken.so`: only `kenso mcp tools` and `kenso mcp call`\n- `registry.npmjs.org`: to install the CLI with npm\n\nStore the key as the platform\'s secret and expose it as `KENSO_API_KEY`. Run `kenso doctor` as the first command: it checks Node, the config, that the API is reachable and that the key works, and exits 0 when all four pass.\n\n```bash\nkenso doctor\n```\n\nPoint the run folders at the workspace if the home folder does not persist between sessions: `KENSO_RUNS_DIR=./.kenso-runs`. Keep that folder out of git.\n\n## How Kenso knows an agent ran a command\n\nThe CLI checks these environment variables, in this order: `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` (Claude Code), `CODEX_SANDBOX` and `CODEX_THREAD_ID` (Codex), `CURSOR_AGENT` (Cursor), `GEMINI_CLI` (Gemini CLI), `OPENCODE` (OpenCode), then `AI_AGENT`, a free-form name any other agent can set. When one is set:\n\n- every request carries `X-Ken-Client: Kenso CLI via <agent>`, and writes carry `X-Ken-Actor: agent`, so Kenso shows the change as made by you through that agent;\n- help ends with a short "For agents" block;\n- browser login never opens a browser itself: it prints the link for you to open.\n\n`kenso doctor` shows the agent it detected.\n\n## MCP-only tools\n\nA few Kenso MCP tools have no API route, such as the skills Kenso\'s own agents use. Reach them from the shell with the same key:\n\n```bash\nkenso mcp tools\nkenso mcp call list_skills\nkenso mcp call load_skill --args \'{"name":"create-campaign"}\'\nkenso mcp call contacts_read --operation list --args \'{"limit":5}\'\n```\n\n`mcp call` prints the tool\'s structured result, else its text parsed as JSON, else the text. A tool error exits 1 with `mcp_tool_error`.\n';
7196
+ agents_default = '# Coding agents\n\nThe CLI is built to be driven by a coding agent: Claude Code, Codex, Cursor, Gemini CLI or anything else that runs shell commands. An agent learns it from the Agent Skill, `kenso --help` and `kenso describe`, and never needs these web pages.\n\n## Set up an agent in three steps\n\n1. Install the CLI where the agent runs: `npm i -g kenso` (Node 22 or newer). Without a global install, `npx -y kenso@latest <command>` runs any command.\n2. Give it a key. Either set `KENSO_API_KEY` (and `KENSO_WORKSPACE_ID` when the key reaches several workspaces) in the agent\'s environment, or log in once on that machine:\n\n```bash\nkenso auth login\nkenso workspace use 1234\n```\n\n3. Install the Agent Skill and connect the Kenso MCP server in one step, then check everything:\n\n```bash\nkenso agent setup\nkenso agent setup -y\nkenso doctor\n```\n\nTo hand the whole setup to an agent, give it [ken.so/get-started.md](https://ken.so/get-started.md): it runs these steps and stops only where a person has to act.\n\n## kenso agent setup\n\n`kenso agent setup` installs the `kenso-cli` skill (as `kenso skill install` does) and registers the Kenso MCP server, `https://mcp.ken.so/mcp`, with each coding agent:\n\n| Agent | `--client` | MCP server added with |\n|---|---|---|\n| Claude Code | `claude-code` | `claude mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| Codex | `codex` | `codex mcp add kenso --url https://mcp.ken.so/mcp` |\n| Cursor | `cursor` | a `kenso` entry in `~/.cursor/mcp.json` |\n| Gemini CLI | `gemini` | `gemini mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| OpenCode | `opencode` | a `kenso` entry in `~/.config/opencode/opencode.json` |\n\n```bash\nkenso agent setup --client claude-code -y\nkenso agent setup --client all -y\nkenso agent setup --status --json\n```\n\n- Without `--client`, it sets up the agent that runs it, else every agent found on the machine (its command on `PATH` or its config folder present).\n- Without `-y` it prints the plan and changes nothing; the plan\'s `next` applies it. `--status` reports, for every agent, whether the skill is `installed`, `missing` or `different` and whether the MCP server is `registered`, `missing`, in `conflict` or `unknown` (a config file it cannot read as JSON), and changes nothing. `--json` prints JSON on a terminal too.\n- An MCP entry with the Kenso URL under another name (such as `ken-ai` from the plugin) counts as registered, and nothing is added. A `kenso` entry pointing at another URL is left alone (`conflict`). A config file that is not plain JSON (it has comments) is left alone (`skipped`), and so is an agent whose command is not on `PATH`: their `next` is the command or edit to make by hand.\n- A different `SKILL.md` in the way stops the run before any change (exit 7) until you add `--force`.\n- It exits 1 when any agent was not fully set up. The MCP server signs in with your Kenso account in the browser the first time the agent uses it; each agent\'s `next` says how (in Claude Code, `/mcp`).\n\n## An AGENTS.md section for your repo\n\nPaste this into the `AGENTS.md` (or `CLAUDE.md`) of a repo whose agents work in Kenso:\n\n```markdown\n## Kenso\n\n- Kenso is our outbound platform. One record or a question: use the Kenso MCP server (https://mcp.ken.so/mcp). A file or more than about 50 records: use the `kenso` CLI.\n- Setup: `npm i -g kenso`, `kenso auth login` (a person approves in the browser), `kenso agent setup -y`, `kenso doctor`.\n- Every write runs first with `--dry-run`; apply with the plan\'s `next`. Never put an API key in a flag, a file or the chat: use `KENSO_API_KEY`.\n- Code that calls the API: send `Authorization: Bearer $KENSO_API_KEY`, `Ken-Version` and `X-Ken-Workspace-Id`. Reference: ken.so/docs.md; the kenso-api skill is listed at ken.so/.well-known/skills/index.json.\n```\n\n## The Agent Skill\n\n`kenso skill install` writes the skill `kenso-cli` (one `SKILL.md`) where each agent looks for skills:\n\n| Agent | `--client` | Folder |\n|---|---|---|\n| Claude Code | `claude-code` | `~/.claude/skills/kenso-cli/` |\n| Codex | `codex` | `~/.agents/skills/kenso-cli/` |\n| Cursor | `cursor` | `~/.cursor/skills/kenso-cli/` |\n| Gemini CLI | `gemini` | `~/.gemini/skills/kenso-cli/` |\n| OpenCode | `opencode` | `~/.config/opencode/skills/kenso-cli/` |\n\nClaude Code\'s folder follows `CLAUDE_CONFIG_DIR` when that is set. Without `--client`, it installs for the agent that runs it when that is Claude Code, Codex or Cursor (detected from the environment, see below), else for all five. It prints what it wrote:\n\n```json\n{"installed":[{"client":"claude-code","path":"/home/you/.claude/skills/kenso-cli/SKILL.md","status":"created"}]}\n```\n\n```bash\nkenso skill install --client claude-code\nkenso skill install --client all\nkenso skill install --dir .claude/skills/kenso-cli\nkenso skill install --force\n```\n\n- `--dir` writes the skill into that folder instead, for example a project\'s own skills folder. Name the folder `kenso-cli`, as agents expect the folder to match the skill name.\n- A different `SKILL.md` already in a target folder is replaced only with `--force`; without it the command exits 7, writes nothing, and its `next` adds `--force`. The same file is left alone (`"status":"unchanged"`).\n- `--dry-run` writes nothing and exits 0. It prints each target\'s status (`replaced` marks a different file there) and a `next` that applies it, with `--force` when a file would be replaced.\n- Cursor also reads `~/.claude/skills/` and `~/.agents/skills/` (Gemini CLI and OpenCode read `~/.agents/skills/` too), so after a default install for all of them an agent may list `kenso-cli` more than once. To avoid that, install with `--client cursor` only, or remove the copies you do not need.\n\nThe skill also ships in the Kenso plugin for Claude Code (`Ken-Technology/ken-ai-plugin`), so `npx skills add Ken-Technology/ken-ai-plugin` installs it along with the MCP skills. The plugin\'s copy is this file byte for byte. To read it without installing, open `skill/kenso-cli/SKILL.md` in the package.\n\n## Rules the skill teaches\n\n- **Data is on stdout, as JSON when piped.** Progress, warnings and errors are on stderr. Parse stdout; read stderr when the exit code is not 0.\n- **Plan, then apply.** Run a write with `--dry-run`, read the plan, then run the exact command in its `next` (the same command with `--yes`). A command with no dry run refuses `--dry-run` with `usage_error` and does nothing.\n- **Pass files, not rows.** Never paste a CSV into the conversation. Write the file, pass its path with `--file`, and read the summary.\n- **Read failures only.** If the summary\'s `failed`, `notFound` and `invalid` are 0, the work is done. Otherwise read just the problem rows from `results.csv` or `invalid.csv`.\n- **Follow `next`.** Every error with a known fix carries the exact command to run.\n- **Branch on the exit code:** 0 ok, 2 fix the command, 3 fix the key, 5 some rows failed, 6 wait or raise a limit, 130 resume.\n- **Look things up, do not guess.** `kenso describe <resource> <action>` prints any command\'s flags and body schema as JSON.\n\n## The token-saving pattern\n\nAdding 5,000 leads through the MCP sends every lead through the model, hundreds of thousands of tokens. Through the CLI it is two commands and two short JSON objects:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThen, only if the summary shows failures:\n\n```bash\ngrep -E \'^[0-9]+,(failed|not_found|invalid),\' ~/.kenso/runs/r_tdi5cdnx/results.csv | head -50\n```\n\n## Environment variables\n\n| Variable | What it does |\n|---|---|\n| `KENSO_API_KEY` | The API key. Wins over any saved profile |\n| `KENSO_WORKSPACE_ID` | The workspace for every command. `--workspace` wins over it |\n| `KENSO_PROFILE` | The saved profile to use. `--profile` wins over it |\n| `KENSO_API_URL` | The API, default `https://api.ken.so` |\n| `KENSO_CONFIG_DIR` | Where the config file and cache live, default `~/.kenso` |\n| `KENSO_RUNS_DIR` | Where run folders live, default `<config dir>/runs` |\n| `KENSO_MCP_URL` | The MCP for `kenso mcp`, default `https://mcp.ken.so/mcp` |\n| `KENSO_NO_UPDATE_NOTIFIER` | Set to `1` to turn off the weekly "a newer kenso is out" line on stderr. It never shows under a detected agent, in CI or when stderr is not a terminal |\n\n## Cloud sandboxes\n\nCloud agents (Claude Code on the web, Codex cloud, Cursor background agents and similar) often run with a network allowlist. Allow:\n\n- `api.ken.so`: every command\n- `mcp.ken.so`: only `kenso mcp tools` and `kenso mcp call`\n- `registry.npmjs.org`: to install the CLI with npm\n\nStore the key as the platform\'s secret and expose it as `KENSO_API_KEY`. Run `kenso doctor` as the first command: it checks Node, the config, that the API is reachable and that the key works, and exits 0 when all four pass.\n\n```bash\nkenso doctor\n```\n\nPoint the run folders at the workspace if the home folder does not persist between sessions: `KENSO_RUNS_DIR=./.kenso-runs`. Keep that folder out of git.\n\n## How Kenso knows an agent ran a command\n\nThe CLI checks these environment variables, in this order: `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` (Claude Code), `CODEX_SANDBOX` and `CODEX_THREAD_ID` (Codex), `CURSOR_AGENT` (Cursor), `GEMINI_CLI` (Gemini CLI), `OPENCODE` (OpenCode), then `AI_AGENT`, a free-form name any other agent can set. When one is set:\n\n- every request carries `X-Ken-Client: Kenso CLI via <agent>`, and writes carry `X-Ken-Actor: agent`, so Kenso shows the change as made by you through that agent;\n- help ends with a short "For agents" block;\n- browser login never opens a browser itself: it prints the link for you to open.\n\n`kenso doctor` shows the agent it detected.\n\n## MCP-only tools\n\nA few Kenso MCP tools have no API route, such as the skills Kenso\'s own agents use. Reach them from the shell with the same key:\n\n```bash\nkenso mcp tools\nkenso mcp call list_skills\nkenso mcp call load_skill --args \'{"name":"create-campaign"}\'\nkenso mcp call contacts_read --operation list --args \'{"limit":5}\'\n```\n\n`mcp call` prints the tool\'s structured result, else its text parsed as JSON, else the text. A tool error exits 1 with `mcp_tool_error`.\n';
7113
7197
  }
7114
7198
  });
7115
7199
 
@@ -7117,7 +7201,7 @@ var init_agents = __esm({
7117
7201
  var auth_default;
7118
7202
  var init_auth = __esm({
7119
7203
  "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| 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';
7204
+ 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
7205
  }
7122
7206
  });
7123
7207
 
@@ -7125,7 +7209,7 @@ var init_auth = __esm({
7125
7209
  var batch_default;
7126
7210
  var init_batch = __esm({
7127
7211
  "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';
7212
+ 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
7213
  }
7130
7214
  });
7131
7215
 
@@ -7149,7 +7233,7 @@ var init_leads = __esm({
7149
7233
  var output_and_errors_default;
7150
7234
  var init_output_and_errors = __esm({
7151
7235
  "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';
7236
+ 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, 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
7237
  }
7154
7238
  });
7155
7239
 
@@ -7157,7 +7241,7 @@ var init_output_and_errors = __esm({
7157
7241
  var README_default;
7158
7242
  var init_README = __esm({
7159
7243
  "docs/README.md"() {
7160
- README_default = '# Kenso CLI\n\nThe Kenso CLI (`kenso`) is the command line for Kenso. It does bulk work in your Kenso workspace from files: add thousands of leads to a campaign, update or clean them up, import accounts and people, and build Studio templates. It is made for coding agents (Claude Code, Codex, Cursor) and the people who drive them: JSON on stdout, fixed exit codes, a dry run before every bulk write, and runs you can resume.\n\nEvery API operation a workspace member can call is also a command, such as `kenso campaigns list` or `kenso tags create`. So the CLI reaches what the Kenso MCP reaches, straight against `https://api.ken.so`.\n\n## Install\n\nYou need Node 22 or newer.\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`.\n\n## 60-second quickstart\n\n1. Create an API key in app.ken.so at Settings > Integrations > API keys.\n2. Save the key, pick a workspace, then plan and apply a CSV import:\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --limit 5\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`workspace list` and `workspace use` are only needed when your key reaches more than one workspace.\n\nThe dry run reads the file, maps the columns, checks every row, asks Kenso for a credit estimate, and writes nothing. It prints the plan, with the exact apply command in `next`:\n\n```json\n{"run":"r_tdi5cdnx","dryRun":true,"command":"contacts import","rows":4,"valid":2,"invalid":2,"chunks":1,"chunkSize":1000,"campaignId":812,"mapping":{"Email":"email","First Name":"firstName","Last Name":"lastName","Company":"companyName","Pain Point":"customVariables.pain_point"},"customVariableKeys":["pain_point"],"estimate":{"kind":"leads","totalMillicredits":2000,"availableMillicredits":500000,"sufficient":true},"credits":{"needed":2,"available":500,"sufficient":true},"next":"kenso contacts import --campaign 812 --file leads.csv --yes","plan":"/home/you/.kenso/runs/r_tdi5cdnx/plan.json","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv"}\n```\n\nThe apply sends the rows and prints one summary. Every input row has one line in `results.csv`:\n\n```json\n{"run":"r_tdi5cdnx","rows":4,"ok":0,"created":1,"updated":0,"skipped":{"duplicate":1},"failed":0,"notFound":0,"invalid":2,"changed":1,"results":"/home/you/.kenso/runs/r_tdi5cdnx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_tdi5cdnx/results.ndjson","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv","resumed":false,"durationMs":1840,"campaignId":812,"notSendable":0}\n```\n\nThis run exits 5 because two rows were invalid: open `invalid.csv` to see why, fix those rows, and import them again. Running the same command again is safe: an email that is already in the campaign comes back `updated` or `skipped`, never as a second lead.\n\n## CLI or MCP\n\n- **Use the CLI for volume:** anything that starts from a file, anything over about 50 records, anything you may need to rerun or resume. Records never pass through the model\'s context: the agent passes a file path and reads a short summary.\n- **Use the MCP for conversation and single records:** look up a campaign, draft a reply, read a report. The MCP is at `https://mcp.ken.so/mcp`, signs in with OAuth and needs no install ([connection guide](https://ken.so/mcp)).\n- **Both use the same API and the same permissions.** `kenso mcp call` reaches MCP-only tools, such as skills, from the shell.\n\n## Docs\n\nEvery page is in the package and prints offline with `kenso docs <topic>`.\n\n| Page | Topic | What it covers |\n|---|---|---|\n| [Authentication](auth.md) | `auth` | API keys, browser login, profiles, workspaces, `doctor` |\n| [Leads](leads.md) | `leads` | Import, update, remove, pause, tag and export leads, with recipes |\n| [Batch runs](batch.md) | `batch` | Dry run and apply, run folders, results files, resume, rate limits, `--each` |\n| [Output and errors](output-and-errors.md) | `output-and-errors` | The output contract, error JSON, error codes, exit codes |\n| [CRM (beta)](crm.md) | `crm` | Accounts, people, opportunities and CRM sync |\n| [Studio (beta)](studio.md) | `studio` | Pull, push, validate, preview and fill templates |\n| [Agent work (beta)](work.md) | `work` | My agent: your own coding agent writes Kenso AI work with `kenso work run`, or pull and submit |\n| [Webhooks](webhooks.md) | `webhooks` | Build a webhook handler locally: `kenso webhooks listen --forward-to`, `trigger`, the signature |\n| [Coding agents](agents.md) | `agents` | Claude Code, Codex, Cursor, the Agent Skill, environment variables, sandboxes |\n| Command reference | `reference` | Every command with its flags, generated from the CLI at build time: `kenso docs reference`, or `docs/reference.md` in the installed package |\n\n```bash\nkenso docs\nkenso docs leads\n```\n\nFor machine-readable help, run `kenso describe`: it prints every command, its flags and its body schema as JSON.\n';
7244
+ README_default = '# Kenso CLI\n\nThe Kenso CLI (`kenso`) is the command line for Kenso. It does bulk work in your Kenso workspace from files: add thousands of leads to a campaign, update or clean them up, import accounts and people, and build Studio templates. It is made for coding agents (Claude Code, Codex, Cursor) and the people who drive them: JSON on stdout, fixed exit codes, a dry run before every bulk write, and runs you can resume.\n\nEvery API operation a workspace member can call is also a command, such as `kenso campaigns list` or `kenso tags create`. So the CLI reaches what the Kenso MCP reaches, straight against `https://api.ken.so`.\n\n## Install\n\nYou need Node 22 or newer.\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`.\n\n### Tab completion\n\nTab completes resources, actions and flags once you install the script for your shell. The script asks `kenso` for the candidates on each Tab, so it stays right as the CLI updates: install it once.\n\n```bash\n# zsh: add this line to ~/.zshrc\nsource <(kenso completion zsh)\n# bash: add this line to ~/.bashrc (on bash 3.2, the macOS default, use: eval "$(kenso completion bash)")\nsource <(kenso completion bash)\n# fish: save the script once\nkenso completion fish > ~/.config/fish/completions/kenso.fish\n```\n\n### Update notice\n\nWhen a newer version is out, `kenso` says so on stderr after the command\'s own output, at most once a week: `kenso 0.1.40 is out (you have 0.1.35): npm i -g kenso@latest`. It checks `registry.npmjs.org` at most once every 7 days and never delays a command by more than about a second. It stays quiet when stderr is not a terminal, in CI (`CI` set) and under a coding agent. Set `KENSO_NO_UPDATE_NOTIFIER=1` to turn it off.\n\n## 60-second quickstart\n\n1. Create an API key in app.ken.so at Settings > Integrations > API keys.\n2. Save the key, pick a workspace, then plan and apply a CSV import:\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --limit 5\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`workspace list` and `workspace use` are only needed when your key reaches more than one workspace.\n\nThe dry run reads the file, maps the columns, checks every row, asks Kenso for a credit estimate, and writes nothing. It prints the plan, with the exact apply command in `next`:\n\n```json\n{"run":"r_tdi5cdnx","dryRun":true,"command":"contacts import","rows":4,"valid":2,"invalid":2,"chunks":1,"chunkSize":1000,"campaignId":812,"mapping":{"Email":"email","First Name":"firstName","Last Name":"lastName","Company":"companyName","Pain Point":"customVariables.pain_point"},"customVariableKeys":["pain_point"],"estimate":{"kind":"leads","totalMillicredits":2000,"availableMillicredits":500000,"sufficient":true},"credits":{"needed":2,"available":500,"sufficient":true},"next":"kenso contacts import --campaign 812 --file leads.csv --yes","plan":"/home/you/.kenso/runs/r_tdi5cdnx/plan.json","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv"}\n```\n\nThe apply sends the rows and prints one summary. Every input row has one line in `results.csv`:\n\n```json\n{"run":"r_tdi5cdnx","rows":4,"ok":0,"created":1,"updated":0,"skipped":{"duplicate":1},"failed":0,"notFound":0,"invalid":2,"changed":1,"results":"/home/you/.kenso/runs/r_tdi5cdnx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_tdi5cdnx/results.ndjson","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv","resumed":false,"durationMs":1840,"campaignId":812,"notSendable":0}\n```\n\nThis run exits 5 because two rows were invalid: open `invalid.csv` to see why, fix those rows, and import them again. Running the same command again is safe: an email that is already in the campaign comes back `updated` or `skipped`, never as a second lead.\n\n## CLI or MCP\n\n- **Use the CLI for volume:** anything that starts from a file, anything over about 50 records, anything you may need to rerun or resume. Records never pass through the model\'s context: the agent passes a file path and reads a short summary.\n- **Use the MCP for conversation and single records:** look up a campaign, draft a reply, read a report. The MCP is at `https://mcp.ken.so/mcp`, signs in with OAuth and needs no install ([connection guide](https://ken.so/mcp)).\n- **Both use the same API and the same permissions.** `kenso mcp call` reaches MCP-only tools, such as skills, from the shell.\n\n## Docs\n\nEvery page is in the package and prints offline with `kenso docs <topic>`.\n\n| Page | Topic | What it covers |\n|---|---|---|\n| [Authentication](auth.md) | `auth` | API keys, browser login, profiles, workspaces, `doctor` |\n| [Leads](leads.md) | `leads` | Import, update, remove, pause, tag and export leads, with recipes |\n| [Batch runs](batch.md) | `batch` | Dry run and apply, run folders, results files, resume, rate limits, `--each` |\n| [Output and errors](output-and-errors.md) | `output-and-errors` | The output contract, error JSON, error codes, exit codes |\n| [CRM (beta)](crm.md) | `crm` | Accounts, people, opportunities and CRM sync |\n| [Studio (beta)](studio.md) | `studio` | Pull, push, validate, preview and fill templates |\n| [Agent work (beta)](work.md) | `work` | My agent: your own coding agent writes Kenso AI work with `kenso work run`, or pull and submit |\n| [Webhooks](webhooks.md) | `webhooks` | Build a webhook handler locally: `kenso webhooks listen --forward-to`, `trigger`, the signature |\n| [Coding agents](agents.md) | `agents` | Claude Code, Codex, Cursor, the Agent Skill, environment variables, sandboxes |\n| Command reference | `reference` | Every command with its flags, generated from the CLI at build time: `kenso docs reference`, or `docs/reference.md` in the installed package |\n\n```bash\nkenso docs\nkenso docs leads\n```\n\nFor machine-readable help, run `kenso describe`: it prints every command, its flags and its body schema as JSON.\n';
7161
7245
  }
7162
7246
  });
7163
7247
 
@@ -7427,7 +7511,7 @@ var init_client = __esm({
7427
7511
  };
7428
7512
  try {
7429
7513
  for (; ; ) {
7430
- const { done, value } = await reader.read();
7514
+ const { done: done2, value } = await reader.read();
7431
7515
  if (value) buffer = (buffer + decoder.decode(value, { stream: true })).replace(/\r\n/g, "\n");
7432
7516
  let boundary = buffer.indexOf("\n\n");
7433
7517
  while (boundary >= 0) {
@@ -7436,7 +7520,7 @@ var init_client = __esm({
7436
7520
  if (found) return found;
7437
7521
  boundary = buffer.indexOf("\n\n");
7438
7522
  }
7439
- if (done) return buffer.trim() === "" ? void 0 : take(buffer);
7523
+ if (done2) return buffer.trim() === "" ? void 0 : take(buffer);
7440
7524
  }
7441
7525
  } catch (err) {
7442
7526
  if (this.opts.signal?.aborted) throw interrupted2();
@@ -7534,11 +7618,11 @@ function folders(ctx, client, dir) {
7534
7618
  return clients.map((c) => ({ client: c, folder: join8(skillsFolder(c, ctx.env), SKILL_NAME) }));
7535
7619
  }
7536
7620
  function installCommand(opts) {
7537
- const parts = ["kenso skill install"];
7538
- if (opts.client !== void 0) parts.push("--client", quote(opts.client));
7539
- if (opts.dir !== void 0) parts.push("--dir", quote(opts.dir));
7540
- if (opts.force) parts.push("--force");
7541
- return parts.join(" ");
7621
+ const parts2 = ["kenso skill install"];
7622
+ if (opts.client !== void 0) parts2.push("--client", quote(opts.client));
7623
+ if (opts.dir !== void 0) parts2.push("--dir", quote(opts.dir));
7624
+ if (opts.force) parts2.push("--force");
7625
+ return parts2.join(" ");
7542
7626
  }
7543
7627
  var SKILL_NAME, AGENT_CLIENTS2, command2, install_default;
7544
7628
  var init_install = __esm({
@@ -7892,10 +7976,10 @@ var init_setup = __esm({
7892
7976
  }
7893
7977
  const different = rows.filter((r) => r.skill.status === "different");
7894
7978
  const pinned = clientFlag ?? (clients.length === 1 ? clients[0] : void 0);
7895
- const parts = ["kenso agent setup"];
7896
- if (pinned !== void 0) parts.push("--client", quote2(pinned));
7897
- if (force || different.length > 0) parts.push("--force");
7898
- const apply = [...parts, "-y"].join(" ");
7979
+ const parts2 = ["kenso agent setup"];
7980
+ if (pinned !== void 0) parts2.push("--client", quote2(pinned));
7981
+ if (force || different.length > 0) parts2.push("--force");
7982
+ const apply = [...parts2, "-y"].join(" ");
7899
7983
  if (!ctx.flags.yes) {
7900
7984
  print({ dryRun: true, mcpUrl: url, clients: rows, next: apply });
7901
7985
  return ExitCode.Ok;
@@ -8246,8 +8330,8 @@ var init_browser_login = __esm({
8246
8330
  defaultDeps = {
8247
8331
  sleep: (ms, signal) => delay2(ms, void 0, signal ? { signal } : void 0),
8248
8332
  now: () => Date.now(),
8249
- spawn: (command35, args) => {
8250
- const child = nodeSpawn(command35, args, { detached: true, stdio: "ignore" });
8333
+ spawn: (command36, args) => {
8334
+ const child = nodeSpawn(command36, args, { detached: true, stdio: "ignore" });
8251
8335
  child.on("error", () => {
8252
8336
  });
8253
8337
  child.unref();
@@ -8396,27 +8480,58 @@ var logout_exports = {};
8396
8480
  __export(logout_exports, {
8397
8481
  default: () => logout_default
8398
8482
  });
8483
+ async function revoke(ctx, apiKey, keyId, savedWorkspaceId) {
8484
+ const auth = { Authorization: `Bearer ${apiKey}` };
8485
+ try {
8486
+ let workspaceId = savedWorkspaceId;
8487
+ if (!workspaceId) {
8488
+ const me = await ctx.client.request({ method: "GET", path: "/v1/me", anonymous: true, noWorkspace: true, headers: auth, signal: ctx.signal });
8489
+ const first = unwrap(me.body)?.workspaces?.[0]?.id;
8490
+ workspaceId = first !== void 0 ? String(first) : void 0;
8491
+ }
8492
+ await ctx.client.request({
8493
+ method: "DELETE",
8494
+ path: `/v1/api-keys/${encodeURIComponent(keyId)}`,
8495
+ anonymous: true,
8496
+ noWorkspace: true,
8497
+ headers: workspaceId ? { ...auth, "X-Ken-Workspace-Id": workspaceId } : auth,
8498
+ signal: ctx.signal
8499
+ });
8500
+ return true;
8501
+ } catch (err) {
8502
+ if (err instanceof KensoError && err.exitCode === ExitCode.Interrupted) throw err;
8503
+ const why = err instanceof Error ? err.message : String(err);
8504
+ ctx.output.warn(`Could not revoke the key (${why}). The profile is removed anyway; revoke the key at Settings > Integrations > API keys.`);
8505
+ return false;
8506
+ }
8507
+ }
8399
8508
  var command6, logout_default;
8400
8509
  var init_logout = __esm({
8401
8510
  "src/commands/auth/logout.ts"() {
8402
8511
  "use strict";
8403
8512
  init_config();
8513
+ init_errors();
8514
+ init_http();
8404
8515
  init_exit_codes();
8405
8516
  command6 = {
8406
8517
  resource: "auth",
8407
8518
  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);
8519
+ summary: "Remove a saved profile, and revoke the key browser login made",
8520
+ 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.",
8521
+ flags: {
8522
+ "keep-key": { type: "boolean", description: "Remove the profile but leave its key valid" }
8523
+ },
8524
+ examples: ["kenso auth logout", "kenso auth logout --profile client-a", "kenso auth logout --keep-key"],
8525
+ operationIds: ["me.get", "api-keys.delete"],
8526
+ async run(ctx, { flags }) {
8527
+ const name = ctx.auth.profileName;
8528
+ const profile = readConfig(ctx.env).profiles[name];
8529
+ const removed = profile !== void 0;
8530
+ const revoked = profile?.apiKey && profile.keyId && flags["keep-key"] !== true ? await revoke(ctx, profile.apiKey, profile.keyId, profile.workspaceId) : false;
8531
+ if (removed) removeProfile(name, ctx.env);
8417
8532
  clearCache(ctx.env);
8418
8533
  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 });
8534
+ ctx.output.object({ profile: name, removed, revoked });
8420
8535
  return ExitCode.Ok;
8421
8536
  }
8422
8537
  };
@@ -8517,9 +8632,122 @@ var init_auth2 = __esm({
8517
8632
  }
8518
8633
  });
8519
8634
 
8635
+ // src/commands/completion/completion.ts
8636
+ var completion_exports = {};
8637
+ __export(completion_exports, {
8638
+ SCRIPTS: () => SCRIPTS,
8639
+ default: () => completion_default
8640
+ });
8641
+ var ZSH, BASH, FISH, SCRIPTS, command8, completion_default;
8642
+ var init_completion = __esm({
8643
+ "src/commands/completion/completion.ts"() {
8644
+ "use strict";
8645
+ init_errors();
8646
+ init_exit_codes();
8647
+ ZSH = `#compdef kenso
8648
+ # Tab completion for kenso in zsh. Add this line to ~/.zshrc:
8649
+ # source <(kenso completion zsh)
8650
+ # kenso lists the candidates itself (kenso __complete), so this script stays right as kenso updates.
8651
+ _kenso() {
8652
+ local -a candidates
8653
+ candidates=(\${(f)"$(kenso __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"})
8654
+ if (( \${#candidates} )); then
8655
+ compadd -a candidates
8656
+ else
8657
+ _files
8658
+ fi
8659
+ }
8660
+ if [[ "\${funcstack[1]}" == "_kenso" ]]; then
8661
+ _kenso "$@"
8662
+ else
8663
+ (( \${+functions[compdef]} )) || { autoload -Uz compinit && compinit }
8664
+ compdef _kenso kenso
8665
+ fi
8666
+ `;
8667
+ BASH = `# Tab completion for kenso in bash. Add this line to ~/.bashrc:
8668
+ # source <(kenso completion bash)
8669
+ # kenso lists the candidates itself (kenso __complete), so this script stays right as kenso updates.
8670
+ _kenso() {
8671
+ # The words up to the cursor, split on blanks only: COMP_WORDS also splits --output=json at the "=".
8672
+ local line="\${COMP_LINE:0:COMP_POINT}" IFS=$' \\t\\n'
8673
+ local -a words candidates
8674
+ read -ra words <<< "$line"
8675
+ case "$line" in *[[:space:]]) words+=("") ;; esac
8676
+ local cur="\${words[\${#words[@]}-1]}"
8677
+ IFS=$'\\n'
8678
+ candidates=($(kenso __complete "\${words[@]:1}" 2>/dev/null))
8679
+ # Bash completes only the text after the "=" of --flag=value, so the candidates drop the "--flag=" too.
8680
+ if [[ "$cur" == *=* && "$COMP_WORDBREAKS" == *=* ]]; then
8681
+ candidates=("\${candidates[@]#"\${cur%%=*}="}")
8682
+ cur="\${cur#*=}"
8683
+ fi
8684
+ COMPREPLY=($(compgen -W "\${candidates[*]}" -- "$cur"))
8685
+ }
8686
+ complete -o default -F _kenso kenso
8687
+ `;
8688
+ FISH = `# Tab completion for kenso in fish. Save it once:
8689
+ # kenso completion fish > ~/.config/fish/completions/kenso.fish
8690
+ # kenso lists the candidates itself (kenso __complete), so this file stays right as kenso updates.
8691
+ function __kenso_complete
8692
+ set -l words (commandline -opc)
8693
+ set -e words[1]
8694
+ set -l current (commandline -ct)
8695
+ set -l candidates (kenso __complete $words "$current" 2>/dev/null)
8696
+ if set -q candidates[1]
8697
+ printf '%s\\n' $candidates
8698
+ else
8699
+ __fish_complete_path "$current"
8700
+ end
8701
+ end
8702
+ complete -c kenso -f -a '(__kenso_complete)'
8703
+ `;
8704
+ SCRIPTS = { bash: BASH, zsh: ZSH, fish: FISH };
8705
+ command8 = {
8706
+ resource: "completion",
8707
+ action: "",
8708
+ summary: "Print the tab-completion script for bash, zsh or fish",
8709
+ brief: "",
8710
+ description: "Prints a script that makes Tab complete kenso's resources, actions and flags. The script asks kenso for the candidates on each Tab, so it stays right as kenso updates: install it once.",
8711
+ flags: {},
8712
+ positionals: [{ name: "shell", required: true, description: "bash, zsh or fish" }],
8713
+ examples: ["kenso completion zsh", "kenso completion bash", "kenso completion fish > ~/.config/fish/completions/kenso.fish"],
8714
+ helpFooter: [
8715
+ "Install it once:",
8716
+ " zsh: add source <(kenso completion zsh) to ~/.zshrc",
8717
+ ' bash: add source <(kenso completion bash) to ~/.bashrc (on bash 3.2: eval "$(kenso completion bash)")',
8718
+ " fish: kenso completion fish > ~/.config/fish/completions/kenso.fish"
8719
+ ],
8720
+ operationIds: [],
8721
+ // It needs no key: reading no config means a broken config file never breaks a shell's startup.
8722
+ ownCredential: () => true,
8723
+ async run(ctx, args) {
8724
+ const shell = args.positionals[0];
8725
+ const script = Object.hasOwn(SCRIPTS, shell) ? SCRIPTS[shell] : void 0;
8726
+ if (script === void 0) {
8727
+ throw usageError(`kenso completion takes bash, zsh or fish (got "${shell}").`, { field: "shell", next: "kenso completion --help" });
8728
+ }
8729
+ ctx.output.writeRaw(script);
8730
+ return ExitCode.Ok;
8731
+ }
8732
+ };
8733
+ completion_default = command8;
8734
+ }
8735
+ });
8736
+
8737
+ // src/commands/completion/index.ts
8738
+ var actions5;
8739
+ var init_completion2 = __esm({
8740
+ "src/commands/completion/index.ts"() {
8741
+ "use strict";
8742
+ actions5 = {
8743
+ "": () => Promise.resolve().then(() => (init_completion(), completion_exports)).then((m) => m.default)
8744
+ };
8745
+ }
8746
+ });
8747
+
8520
8748
  // src/commands/contacts/common.ts
8521
8749
  import { createHash as createHash3 } from "node:crypto";
8522
- import { readFile as readFile5 } from "node:fs/promises";
8750
+ import { readFile as readFile6 } from "node:fs/promises";
8523
8751
  import { resolve as resolve5 } from "node:path";
8524
8752
  function stringFlag2(flags, name) {
8525
8753
  const value = flags[name];
@@ -8527,9 +8755,9 @@ function stringFlag2(flags, name) {
8527
8755
  const text3 = value.trim();
8528
8756
  return text3 === "" ? void 0 : text3;
8529
8757
  }
8530
- function requireFlag(flags, name, command35, hint) {
8758
+ function requireFlag(flags, name, command36, hint) {
8531
8759
  const value = stringFlag2(flags, name);
8532
- if (value === void 0) throw usageError(`--${name} is required for ${command35}.`, { field: name, next: `${command35} --help`, ...hint ? { hint } : {} });
8760
+ if (value === void 0) throw usageError(`--${name} is required for ${command36}.`, { field: name, next: `${command36} --help`, ...hint ? { hint } : {} });
8533
8761
  return value;
8534
8762
  }
8535
8763
  function positiveId(value) {
@@ -8538,8 +8766,8 @@ function positiveId(value) {
8538
8766
  const id = Number(text3);
8539
8767
  return Number.isSafeInteger(id) && id > 0 ? id : void 0;
8540
8768
  }
8541
- function idFlag(flags, name, command35) {
8542
- const raw = requireFlag(flags, name, command35);
8769
+ function idFlag(flags, name, command36) {
8770
+ const raw = requireFlag(flags, name, command36);
8543
8771
  const id = positiveId(raw);
8544
8772
  if (id === void 0) throw usageError(`--${name} must be a positive whole number (got "${raw}").`, { field: name });
8545
8773
  return id;
@@ -8559,22 +8787,22 @@ function isDryRun(ctx) {
8559
8787
  function shellQuote4(value) {
8560
8788
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8561
8789
  }
8562
- function sameCommand2(command35, flags, ctx, extra = []) {
8563
- const parts = [command35];
8790
+ function sameCommand2(command36, flags, ctx, extra = []) {
8791
+ const parts2 = [command36];
8564
8792
  for (const [name, value] of Object.entries(flags)) {
8565
8793
  if (value === void 0 || value === false) continue;
8566
- if (value === true) parts.push(`--${name}`);
8567
- else for (const item of Array.isArray(value) ? value : [value]) parts.push(`--${name}`, shellQuote4(item));
8794
+ if (value === true) parts2.push(`--${name}`);
8795
+ else for (const item of Array.isArray(value) ? value : [value]) parts2.push(`--${name}`, shellQuote4(item));
8568
8796
  }
8569
8797
  for (const name of ["profile", "workspace"]) {
8570
8798
  const value = ctx.flags[name];
8571
- if (value !== void 0) parts.push(`--${name}`, shellQuote4(value));
8799
+ if (value !== void 0) parts2.push(`--${name}`, shellQuote4(value));
8572
8800
  }
8573
- parts.push(...extra);
8574
- return parts.join(" ");
8801
+ parts2.push(...extra);
8802
+ return parts2.join(" ");
8575
8803
  }
8576
8804
  async function fileSha256(path) {
8577
- return createHash3("sha256").update(await readFile5(resolve5(path))).digest("hex");
8805
+ return createHash3("sha256").update(await readFile6(resolve5(path))).digest("hex");
8578
8806
  }
8579
8807
  function rateLimitRemaining3(headers) {
8580
8808
  const raw = headers.get("ratelimit-remaining");
@@ -9160,7 +9388,7 @@ function parseDuration(text3) {
9160
9388
  const ms = Number(match[1]) * (UNIT_MS[(match[2] || "s").toLowerCase()] ?? 1e3);
9161
9389
  return Number.isFinite(ms) ? Math.round(ms) : void 0;
9162
9390
  }
9163
- var UNIT_MS, command8, wait_default;
9391
+ var UNIT_MS, command9, wait_default;
9164
9392
  var init_wait = __esm({
9165
9393
  "src/commands/jobs/wait.ts"() {
9166
9394
  "use strict";
@@ -9168,7 +9396,7 @@ var init_wait = __esm({
9168
9396
  init_errors();
9169
9397
  init_exit_codes();
9170
9398
  UNIT_MS = { s: 1e3, m: 6e4, h: 36e5 };
9171
- command8 = {
9399
+ command9 = {
9172
9400
  resource: "jobs",
9173
9401
  action: "wait",
9174
9402
  summary: "Wait for a background job and print it",
@@ -9194,8 +9422,8 @@ var init_wait = __esm({
9194
9422
  timeoutMs,
9195
9423
  signal: ctx.signal,
9196
9424
  onProgress: (j) => {
9197
- const done = j.progress ? `, ${j.progress.completed}/${j.progress.total ?? "?"}` : "";
9198
- ctx.output.progress(`job ${j.id}: ${j.status}${done}`);
9425
+ const done2 = j.progress ? `, ${j.progress.completed}/${j.progress.total ?? "?"}` : "";
9426
+ ctx.output.progress(`job ${j.id}: ${j.status}${done2}`);
9199
9427
  }
9200
9428
  });
9201
9429
  ctx.output.object(job);
@@ -9207,12 +9435,12 @@ var init_wait = __esm({
9207
9435
  });
9208
9436
  }
9209
9437
  };
9210
- wait_default = command8;
9438
+ wait_default = command9;
9211
9439
  }
9212
9440
  });
9213
9441
 
9214
9442
  // src/commands/contacts/server-import.ts
9215
- import { readFile as readFile6 } from "node:fs/promises";
9443
+ import { readFile as readFile7 } from "node:fs/promises";
9216
9444
  import { basename as basename3, extname as extname2, resolve as resolve6 } from "node:path";
9217
9445
  function csvTargetOf(header, mapping) {
9218
9446
  if (mapping.dropped[header] !== "reserved_name") return void 0;
@@ -9242,7 +9470,7 @@ async function readUpload2(file) {
9242
9470
  }
9243
9471
  const path = resolve6(file);
9244
9472
  try {
9245
- const bytes = await readFile6(path);
9473
+ const bytes = await readFile7(path);
9246
9474
  const name = ext === ".csv" ? basename3(path) : `${basename3(path, extname2(path))}.csv`;
9247
9475
  return { bytes, name, path };
9248
9476
  } catch (err) {
@@ -9389,7 +9617,7 @@ function summarize2(campaignId) {
9389
9617
  notSendable: results.filter((r) => (r.status === "created" || r.status === "updated") && r.sendable === false).length
9390
9618
  });
9391
9619
  }
9392
- var COMMAND2, CHUNK_SIZE2, LINKEDIN_ONLY_CHANNELS, TEMPLATE_HEADER, command9, import_default2;
9620
+ var COMMAND2, CHUNK_SIZE2, LINKEDIN_ONLY_CHANNELS, TEMPLATE_HEADER, command10, import_default2;
9393
9621
  var init_import2 = __esm({
9394
9622
  "src/commands/contacts/import.ts"() {
9395
9623
  "use strict";
@@ -9408,7 +9636,7 @@ var init_import2 = __esm({
9408
9636
  CHUNK_SIZE2 = 1e3;
9409
9637
  LINKEDIN_ONLY_CHANNELS = /* @__PURE__ */ new Set(["linkedin", "linkedin_only"]);
9410
9638
  TEMPLATE_HEADER = `${CONTACT_FIELDS.join(",")},<your custom columns>`;
9411
- command9 = {
9639
+ command10 = {
9412
9640
  resource: "contacts",
9413
9641
  action: "import",
9414
9642
  summary: "Add leads from a CSV or JSONL file to a campaign",
@@ -9497,7 +9725,7 @@ var init_import2 = __esm({
9497
9725
  return outcome.exitCode;
9498
9726
  }
9499
9727
  };
9500
- import_default2 = command9;
9728
+ import_default2 = command10;
9501
9729
  }
9502
9730
  });
9503
9731
 
@@ -9601,7 +9829,7 @@ async function sendUpdateChunk(chunk, ctx) {
9601
9829
  });
9602
9830
  return { results: mapUpdateAnswer(chunk, res.body), rateLimitRemaining: rateLimitRemaining3(res.headers) };
9603
9831
  }
9604
- var COMMAND3, CHUNK_SIZE3, PAGE_SIZE, command10, update_default;
9832
+ var COMMAND3, CHUNK_SIZE3, PAGE_SIZE, command11, update_default;
9605
9833
  var init_update = __esm({
9606
9834
  "src/commands/contacts/update.ts"() {
9607
9835
  "use strict";
@@ -9615,7 +9843,7 @@ var init_update = __esm({
9615
9843
  COMMAND3 = "kenso contacts update";
9616
9844
  CHUNK_SIZE3 = 1e3;
9617
9845
  PAGE_SIZE = 200;
9618
- command10 = {
9846
+ command11 = {
9619
9847
  resource: "contacts",
9620
9848
  action: "update",
9621
9849
  summary: "Edit leads from a CSV or JSONL file, by id or email (also one lead)",
@@ -9686,23 +9914,23 @@ var init_update = __esm({
9686
9914
  return outcome.exitCode;
9687
9915
  }
9688
9916
  };
9689
- update_default = command10;
9917
+ update_default = command11;
9690
9918
  }
9691
9919
  });
9692
9920
 
9693
9921
  // src/commands/contacts/bulk-store.ts
9694
9922
  import { existsSync as existsSync5 } from "node:fs";
9695
- import { appendFile as appendFile2, readFile as readFile7, writeFile as writeFile2 } from "node:fs/promises";
9923
+ import { appendFile as appendFile2, readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises";
9696
9924
  import { join as join11 } from "node:path";
9697
9925
  function whereDir(env) {
9698
9926
  return join11(runsRoot(env), WHERE_DIR);
9699
9927
  }
9700
- async function unfinishedWhereIds(ctx, command35, args) {
9928
+ async function unfinishedWhereIds(ctx, command36, args) {
9701
9929
  const dir = whereDir(ctx.env);
9702
9930
  const identity = argsIdentity(args);
9703
9931
  const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
9704
9932
  for (const run of await listRuns(ctx.env)) {
9705
- if (run.command !== command35 || run.status === "done" || run.status === "planned") continue;
9933
+ if (run.command !== command36 || run.status === "done" || run.status === "planned") continue;
9706
9934
  if ((run.workspaceId || void 0) !== (workspaceId || void 0) || argsIdentity(run.args) !== identity) continue;
9707
9935
  if (run.inputPath?.startsWith(`${dir}/`) && existsSync5(run.inputPath)) return run.inputPath;
9708
9936
  }
@@ -9721,7 +9949,7 @@ function chunkAttempts(env) {
9721
9949
  return async (runId, chunkIndex) => {
9722
9950
  earlier ??= (async () => {
9723
9951
  const path2 = join11(runsRoot(env), runId, ATTEMPTS_FILE);
9724
- const text3 = await readFile7(path2, "utf8").catch(() => "");
9952
+ const text3 = await readFile8(path2, "utf8").catch(() => "");
9725
9953
  const indexes3 = new Set(
9726
9954
  text3.split("\n").filter((line) => line.trim() !== "").map(Number)
9727
9955
  );
@@ -9848,14 +10076,14 @@ async function idsFromRun(ctx, runId) {
9848
10076
  return { ...idItems(ids2), source: "run" };
9849
10077
  }
9850
10078
  async function collectIds(ctx, flags, kind, dryRun2) {
9851
- const command35 = `kenso contacts ${kind}`;
10079
+ const command36 = `kenso contacts ${kind}`;
9852
10080
  const ids2 = stringFlag2(flags, "ids");
9853
10081
  const where = kind === "restore" ? void 0 : stringFlag2(flags, "where");
9854
10082
  const run = kind === "restore" ? stringFlag2(flags, "run") : void 0;
9855
10083
  const given = [ids2, where, run].filter((v) => v !== void 0).length;
9856
10084
  if (given !== 1) {
9857
10085
  const choices = kind === "restore" ? "--ids <file|-> or --run <runId>" : "--ids <file|-> or --where '<json>'";
9858
- throw usageError(`${command35} needs exactly one of ${choices}.`, { field: "ids", next: `${command35} --help` });
10086
+ throw usageError(`${command36} needs exactly one of ${choices}.`, { field: "ids", next: `${command36} --help` });
9859
10087
  }
9860
10088
  if (ids2 !== void 0) return idsFromFile(ctx, ids2);
9861
10089
  if (where !== void 0) return idsFromWhere(ctx, kind, flags, where, dryRun2);
@@ -10157,7 +10385,7 @@ async function download(ctx, job, exportId, out) {
10157
10385
  }
10158
10386
  return { rows: countRows(body), path };
10159
10387
  }
10160
- var COMMAND4, JOB_TYPE, DEFAULT_TIMEOUT2, CONTENT_PATH, command11, export_default;
10388
+ var COMMAND4, JOB_TYPE, DEFAULT_TIMEOUT2, CONTENT_PATH, command12, export_default;
10161
10389
  var init_export = __esm({
10162
10390
  "src/commands/contacts/export.ts"() {
10163
10391
  "use strict";
@@ -10172,7 +10400,7 @@ var init_export = __esm({
10172
10400
  JOB_TYPE = "contact_export";
10173
10401
  DEFAULT_TIMEOUT2 = "30m";
10174
10402
  CONTENT_PATH = /\/v1\/contact-exports\/([0-9]+)\/content/;
10175
- command11 = {
10403
+ command12 = {
10176
10404
  resource: "contacts",
10177
10405
  action: "export",
10178
10406
  summary: "Export a campaign's contacts to CSV (a segment: contact-exports create)",
@@ -10230,16 +10458,16 @@ var init_export = __esm({
10230
10458
  return ExitCode.Ok;
10231
10459
  }
10232
10460
  };
10233
- export_default = command11;
10461
+ export_default = command12;
10234
10462
  }
10235
10463
  });
10236
10464
 
10237
10465
  // src/commands/contacts/index.ts
10238
- var actions5;
10466
+ var actions6;
10239
10467
  var init_contacts = __esm({
10240
10468
  "src/commands/contacts/index.ts"() {
10241
10469
  "use strict";
10242
- actions5 = {
10470
+ actions6 = {
10243
10471
  import: () => Promise.resolve().then(() => (init_import2(), import_exports2)).then((m) => m.default),
10244
10472
  update: () => Promise.resolve().then(() => (init_update(), update_exports)).then((m) => m.default),
10245
10473
  remove: () => Promise.resolve().then(() => (init_bulk_ids(), bulk_ids_exports)).then((m) => m.remove),
@@ -10354,7 +10582,7 @@ function unknown(words) {
10354
10582
  next: "kenso describe"
10355
10583
  });
10356
10584
  }
10357
- var command12, describe_default;
10585
+ var command13, describe_default;
10358
10586
  var init_describe = __esm({
10359
10587
  "src/commands/describe/describe.ts"() {
10360
10588
  "use strict";
@@ -10367,7 +10595,7 @@ var init_describe = __esm({
10367
10595
  init_manifest();
10368
10596
  init_help();
10369
10597
  init_registry();
10370
- command12 = {
10598
+ command13 = {
10371
10599
  resource: "describe",
10372
10600
  action: "",
10373
10601
  summary: "The command map as JSON: commands, flags, body schemas",
@@ -10408,16 +10636,16 @@ var init_describe = __esm({
10408
10636
  return ExitCode.Ok;
10409
10637
  }
10410
10638
  };
10411
- describe_default = command12;
10639
+ describe_default = command13;
10412
10640
  }
10413
10641
  });
10414
10642
 
10415
10643
  // src/commands/describe/index.ts
10416
- var actions6;
10644
+ var actions7;
10417
10645
  var init_describe2 = __esm({
10418
10646
  "src/commands/describe/index.ts"() {
10419
10647
  "use strict";
10420
- actions6 = {
10648
+ actions7 = {
10421
10649
  "": () => Promise.resolve().then(() => (init_describe(), describe_exports)).then((m) => m.default)
10422
10650
  };
10423
10651
  }
@@ -10432,7 +10660,7 @@ function findTopic(input) {
10432
10660
  const name = input.trim().toLowerCase().replace(/\.md$/, "");
10433
10661
  return TOPICS.find((t) => t.topic === name);
10434
10662
  }
10435
- var NAMES, command13, docs_default;
10663
+ var NAMES, command14, docs_default;
10436
10664
  var init_docs = __esm({
10437
10665
  "src/commands/docs/docs.ts"() {
10438
10666
  "use strict";
@@ -10440,7 +10668,7 @@ var init_docs = __esm({
10440
10668
  init_exit_codes();
10441
10669
  init_content();
10442
10670
  NAMES = TOPICS.map((t) => t.topic).join(", ");
10443
- command13 = {
10671
+ command14 = {
10444
10672
  resource: "docs",
10445
10673
  action: "",
10446
10674
  summary: "Offline docs: the topic list, or one topic",
@@ -10481,16 +10709,16 @@ var init_docs = __esm({
10481
10709
  return ExitCode.Ok;
10482
10710
  }
10483
10711
  };
10484
- docs_default = command13;
10712
+ docs_default = command14;
10485
10713
  }
10486
10714
  });
10487
10715
 
10488
10716
  // src/commands/docs/index.ts
10489
- var actions7;
10717
+ var actions8;
10490
10718
  var init_docs2 = __esm({
10491
10719
  "src/commands/docs/index.ts"() {
10492
10720
  "use strict";
10493
- actions7 = {
10721
+ actions8 = {
10494
10722
  "": () => Promise.resolve().then(() => (init_docs(), docs_exports)).then((m) => m.default)
10495
10723
  };
10496
10724
  }
@@ -10519,7 +10747,7 @@ function configCheck(env) {
10519
10747
  const octal = mode.toString(8).padStart(4, "0");
10520
10748
  return mode === 384 ? { name: "config_permissions", ok: true, detail: `${file} is ${octal}` } : { name: "config_permissions", ok: false, detail: `${file} is ${octal}: run chmod 600 ${file}` };
10521
10749
  }
10522
- var MIN_NODE_MAJOR, command14, actions8;
10750
+ var MIN_NODE_MAJOR, command15, actions9;
10523
10751
  var init_doctor = __esm({
10524
10752
  "src/commands/doctor/index.ts"() {
10525
10753
  "use strict";
@@ -10528,7 +10756,7 @@ var init_doctor = __esm({
10528
10756
  init_exit_codes();
10529
10757
  init_http();
10530
10758
  MIN_NODE_MAJOR = 22;
10531
- command14 = {
10759
+ command15 = {
10532
10760
  resource: "doctor",
10533
10761
  action: "",
10534
10762
  summary: "Check Node, the config, the API and the key",
@@ -10592,18 +10820,18 @@ var init_doctor = __esm({
10592
10820
  return keyFailed ? ExitCode.Auth : ExitCode.Error;
10593
10821
  }
10594
10822
  };
10595
- actions8 = {
10596
- "": async () => command14
10823
+ actions9 = {
10824
+ "": async () => command15
10597
10825
  };
10598
10826
  }
10599
10827
  });
10600
10828
 
10601
10829
  // src/commands/jobs/index.ts
10602
- var actions9;
10830
+ var actions10;
10603
10831
  var init_jobs2 = __esm({
10604
10832
  "src/commands/jobs/index.ts"() {
10605
10833
  "use strict";
10606
- actions9 = {
10834
+ actions10 = {
10607
10835
  wait: () => Promise.resolve().then(() => (init_wait(), wait_exports)).then((m) => m.default)
10608
10836
  };
10609
10837
  }
@@ -10659,7 +10887,7 @@ function isRecord6(value) {
10659
10887
  function textOf(result) {
10660
10888
  return (result.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
10661
10889
  }
10662
- var command15, call_default;
10890
+ var command16, call_default;
10663
10891
  var init_call = __esm({
10664
10892
  "src/commands/mcp/call.ts"() {
10665
10893
  "use strict";
@@ -10667,7 +10895,7 @@ var init_call = __esm({
10667
10895
  init_exit_codes();
10668
10896
  init_input();
10669
10897
  init_connect();
10670
- command15 = {
10898
+ command16 = {
10671
10899
  resource: "mcp",
10672
10900
  action: "call",
10673
10901
  summary: "Call a hosted Kenso MCP tool, such as list_skills",
@@ -10720,7 +10948,7 @@ var init_call = __esm({
10720
10948
  return ExitCode.Ok;
10721
10949
  }
10722
10950
  };
10723
- call_default = command15;
10951
+ call_default = command16;
10724
10952
  }
10725
10953
  });
10726
10954
 
@@ -10729,13 +10957,13 @@ var tools_exports = {};
10729
10957
  __export(tools_exports, {
10730
10958
  default: () => tools_default
10731
10959
  });
10732
- var command16, tools_default;
10960
+ var command17, tools_default;
10733
10961
  var init_tools = __esm({
10734
10962
  "src/commands/mcp/tools.ts"() {
10735
10963
  "use strict";
10736
10964
  init_exit_codes();
10737
10965
  init_connect();
10738
- command16 = {
10966
+ command17 = {
10739
10967
  resource: "mcp",
10740
10968
  action: "tools",
10741
10969
  summary: "List the hosted Kenso MCP's tools",
@@ -10750,16 +10978,16 @@ var init_tools = __esm({
10750
10978
  return ExitCode.Ok;
10751
10979
  }
10752
10980
  };
10753
- tools_default = command16;
10981
+ tools_default = command17;
10754
10982
  }
10755
10983
  });
10756
10984
 
10757
10985
  // src/commands/mcp/index.ts
10758
- var actions10;
10986
+ var actions11;
10759
10987
  var init_mcp = __esm({
10760
10988
  "src/commands/mcp/index.ts"() {
10761
10989
  "use strict";
10762
- actions10 = {
10990
+ actions11 = {
10763
10991
  call: () => Promise.resolve().then(() => (init_call(), call_exports)).then((m) => m.default),
10764
10992
  tools: () => Promise.resolve().then(() => (init_tools(), tools_exports)).then((m) => m.default)
10765
10993
  };
@@ -10837,7 +11065,7 @@ function summarize3(results) {
10837
11065
  }
10838
11066
  return { matched, addedToAccounts, emailFindsQueued };
10839
11067
  }
10840
- var COMMAND5, CHUNK_SIZE6, ALIASES3, PERSON_FIELDS, ACCOUNT_NOT_FOUND, command17, import_default3;
11068
+ var COMMAND5, CHUNK_SIZE6, ALIASES3, PERSON_FIELDS, ACCOUNT_NOT_FOUND, command18, import_default3;
10841
11069
  var init_import3 = __esm({
10842
11070
  "src/commands/people/import.ts"() {
10843
11071
  "use strict";
@@ -10869,7 +11097,7 @@ var init_import3 = __esm({
10869
11097
  };
10870
11098
  PERSON_FIELDS = ["email", "fullName", "firstName", "lastName", "linkedinUrl", "title"];
10871
11099
  ACCOUNT_NOT_FOUND = "No account in this workspace has that domain. The person was saved without an account: add the account (kenso accounts import) and run the same command again.";
10872
- command17 = {
11100
+ command18 = {
10873
11101
  resource: "people",
10874
11102
  action: "import",
10875
11103
  summary: "Create or match people from a CSV or JSONL file, optionally onto accounts",
@@ -10934,16 +11162,16 @@ var init_import3 = __esm({
10934
11162
  return outcome.exitCode;
10935
11163
  }
10936
11164
  };
10937
- import_default3 = command17;
11165
+ import_default3 = command18;
10938
11166
  }
10939
11167
  });
10940
11168
 
10941
11169
  // src/commands/people/index.ts
10942
- var actions11;
11170
+ var actions12;
10943
11171
  var init_people = __esm({
10944
11172
  "src/commands/people/index.ts"() {
10945
11173
  "use strict";
10946
- actions11 = {
11174
+ actions12 = {
10947
11175
  import: () => Promise.resolve().then(() => (init_import3(), import_exports3)).then((m) => m.default)
10948
11176
  };
10949
11177
  }
@@ -10954,14 +11182,14 @@ var list_exports = {};
10954
11182
  __export(list_exports, {
10955
11183
  default: () => list_default
10956
11184
  });
10957
- var command18, list_default;
11185
+ var command19, list_default;
10958
11186
  var init_list = __esm({
10959
11187
  "src/commands/runs/list.ts"() {
10960
11188
  "use strict";
10961
11189
  init_runs();
10962
11190
  init_errors();
10963
11191
  init_exit_codes();
10964
- command18 = {
11192
+ command19 = {
10965
11193
  resource: "runs",
10966
11194
  action: "list",
10967
11195
  summary: "List batch runs, newest first (finds an interrupted run)",
@@ -10982,7 +11210,7 @@ var init_list = __esm({
10982
11210
  return ExitCode.Ok;
10983
11211
  }
10984
11212
  };
10985
- list_default = command18;
11213
+ list_default = command19;
10986
11214
  }
10987
11215
  });
10988
11216
 
@@ -10993,7 +11221,7 @@ __export(show_exports, {
10993
11221
  });
10994
11222
  import { existsSync as existsSync6, readFileSync as readFileSync9 } from "node:fs";
10995
11223
  import { join as join12 } from "node:path";
10996
- var FILES, command19, show_default;
11224
+ var FILES, command20, show_default;
10997
11225
  var init_show = __esm({
10998
11226
  "src/commands/runs/show.ts"() {
10999
11227
  "use strict";
@@ -11008,7 +11236,7 @@ var init_show = __esm({
11008
11236
  ["plan", "plan.json"],
11009
11237
  ["summary", "summary.json"]
11010
11238
  ];
11011
- command19 = {
11239
+ command20 = {
11012
11240
  resource: "runs",
11013
11241
  action: "show",
11014
11242
  summary: "Show one batch run and its files",
@@ -11035,7 +11263,7 @@ var init_show = __esm({
11035
11263
  return ExitCode.Ok;
11036
11264
  }
11037
11265
  };
11038
- show_default = command19;
11266
+ show_default = command20;
11039
11267
  }
11040
11268
  });
11041
11269
 
@@ -11047,7 +11275,7 @@ __export(resume_exports, {
11047
11275
  });
11048
11276
  import { createHash as createHash5 } from "node:crypto";
11049
11277
  import { existsSync as existsSync7 } from "node:fs";
11050
- import { readFile as readFile8 } from "node:fs/promises";
11278
+ import { readFile as readFile9 } from "node:fs/promises";
11051
11279
  import { resolve as resolve9 } from "node:path";
11052
11280
  function kebab(key) {
11053
11281
  return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
@@ -11092,16 +11320,16 @@ function resumeArgv(run, globals = {}) {
11092
11320
  return argv;
11093
11321
  }
11094
11322
  async function sha256(path) {
11095
- return createHash5("sha256").update(await readFile8(path)).digest("hex");
11323
+ return createHash5("sha256").update(await readFile9(path)).digest("hex");
11096
11324
  }
11097
- var SKIPPED_KEYS, command20, resume_default;
11325
+ var SKIPPED_KEYS, command21, resume_default;
11098
11326
  var init_resume = __esm({
11099
11327
  "src/commands/runs/resume.ts"() {
11100
11328
  "use strict";
11101
11329
  init_runs();
11102
11330
  init_errors();
11103
11331
  SKIPPED_KEYS = /* @__PURE__ */ new Set(["positionals", "yes", "dryRun", "dry-run", "help", "version"]);
11104
- command20 = {
11332
+ command21 = {
11105
11333
  resource: "runs",
11106
11334
  action: "resume",
11107
11335
  summary: "Continue an interrupted batch run (its command with --yes, no dry run)",
@@ -11156,16 +11384,16 @@ var init_resume = __esm({
11156
11384
  }
11157
11385
  }
11158
11386
  };
11159
- resume_default = command20;
11387
+ resume_default = command21;
11160
11388
  }
11161
11389
  });
11162
11390
 
11163
11391
  // src/commands/runs/index.ts
11164
- var actions12;
11392
+ var actions13;
11165
11393
  var init_runs2 = __esm({
11166
11394
  "src/commands/runs/index.ts"() {
11167
11395
  "use strict";
11168
- actions12 = {
11396
+ actions13 = {
11169
11397
  list: () => Promise.resolve().then(() => (init_list(), list_exports)).then((m) => m.default),
11170
11398
  show: () => Promise.resolve().then(() => (init_show(), show_exports)).then((m) => m.default),
11171
11399
  resume: () => Promise.resolve().then(() => (init_resume(), resume_exports)).then((m) => m.default)
@@ -11174,11 +11402,11 @@ var init_runs2 = __esm({
11174
11402
  });
11175
11403
 
11176
11404
  // src/commands/skill/index.ts
11177
- var actions13;
11405
+ var actions14;
11178
11406
  var init_skill = __esm({
11179
11407
  "src/commands/skill/index.ts"() {
11180
11408
  "use strict";
11181
- actions13 = {
11409
+ actions14 = {
11182
11410
  install: () => Promise.resolve().then(() => (init_install(), install_exports)).then((m) => m.default)
11183
11411
  };
11184
11412
  }
@@ -11214,7 +11442,7 @@ var init_common2 = __esm({
11214
11442
  });
11215
11443
 
11216
11444
  // src/commands/studio/folder.ts
11217
- import { readdir as readdir2, readFile as readFile9, stat as stat2 } from "node:fs/promises";
11445
+ import { readdir as readdir2, readFile as readFile10, stat as stat2 } from "node:fs/promises";
11218
11446
  import { extname as extname3, isAbsolute, join as join13, relative, resolve as resolve10, sep } from "node:path";
11219
11447
  function textOf2(bytes) {
11220
11448
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
@@ -11240,7 +11468,7 @@ async function readFolder(dir) {
11240
11468
  const abs = join13(folder, entry.name);
11241
11469
  if (entry.isDirectory()) await walk(abs);
11242
11470
  else if (entry.isFile()) {
11243
- const bytes = await readFile9(abs);
11471
+ const bytes = await readFile10(abs);
11244
11472
  files.push({ path: relative(root2, abs).split(sep).join("/"), bytes, text: textOf2(bytes) });
11245
11473
  }
11246
11474
  }
@@ -11414,7 +11642,7 @@ __export(pull_exports, {
11414
11642
  });
11415
11643
  import { mkdir, writeFile as writeFile4 } from "node:fs/promises";
11416
11644
  import { dirname as dirname2, resolve as resolve11 } from "node:path";
11417
- var command21, pull_default;
11645
+ var command22, pull_default;
11418
11646
  var init_pull = __esm({
11419
11647
  "src/commands/studio/pull.ts"() {
11420
11648
  "use strict";
@@ -11424,7 +11652,7 @@ var init_pull = __esm({
11424
11652
  init_common2();
11425
11653
  init_folder();
11426
11654
  init_transfer();
11427
- command21 = {
11655
+ command22 = {
11428
11656
  resource: "studio",
11429
11657
  action: "pull",
11430
11658
  summary: "Write a template version's files to a folder",
@@ -11471,7 +11699,7 @@ var init_pull = __esm({
11471
11699
  return ExitCode.Ok;
11472
11700
  }
11473
11701
  };
11474
- pull_default = command21;
11702
+ pull_default = command22;
11475
11703
  }
11476
11704
  });
11477
11705
 
@@ -11504,7 +11732,7 @@ var push_exports = {};
11504
11732
  __export(push_exports, {
11505
11733
  default: () => push_default
11506
11734
  });
11507
- var BUILT_BY, DEFAULT_MESSAGE, command22, push_default;
11735
+ var BUILT_BY, DEFAULT_MESSAGE, command23, push_default;
11508
11736
  var init_push = __esm({
11509
11737
  "src/commands/studio/push.ts"() {
11510
11738
  "use strict";
@@ -11516,7 +11744,7 @@ var init_push = __esm({
11516
11744
  init_read();
11517
11745
  BUILT_BY = "customer_agent";
11518
11746
  DEFAULT_MESSAGE = "Pushed with the Kenso CLI";
11519
- command22 = {
11747
+ command23 = {
11520
11748
  resource: "studio",
11521
11749
  action: "push",
11522
11750
  summary: "Save a folder's files to a template's draft and print the validation",
@@ -11608,7 +11836,7 @@ var init_push = __esm({
11608
11836
  );
11609
11837
  }
11610
11838
  };
11611
- push_default = command22;
11839
+ push_default = command23;
11612
11840
  }
11613
11841
  });
11614
11842
 
@@ -11617,7 +11845,7 @@ var validate_exports = {};
11617
11845
  __export(validate_exports, {
11618
11846
  default: () => validate_default
11619
11847
  });
11620
- var command23, validate_default;
11848
+ var command24, validate_default;
11621
11849
  var init_validate = __esm({
11622
11850
  "src/commands/studio/validate.ts"() {
11623
11851
  "use strict";
@@ -11626,7 +11854,7 @@ var init_validate = __esm({
11626
11854
  init_columns();
11627
11855
  init_common2();
11628
11856
  init_read();
11629
- command23 = {
11857
+ command24 = {
11630
11858
  resource: "studio",
11631
11859
  action: "validate",
11632
11860
  summary: "Validate a folder's files against a template without saving them",
@@ -11655,7 +11883,7 @@ var init_validate = __esm({
11655
11883
  throw validationFailed(validation, "The files have validation errors", commandLine2(ctx, "studio validate", args));
11656
11884
  }
11657
11885
  };
11658
- validate_default = command23;
11886
+ validate_default = command24;
11659
11887
  }
11660
11888
  });
11661
11889
 
@@ -11688,12 +11916,12 @@ async function warnIfFolderDiffers(ctx, templateId, dir, versionId, push) {
11688
11916
  const onlySaved = Object.keys(saved).filter((path) => !localPaths.has(path)).sort();
11689
11917
  const total = changed.length + onlyLocal.length + onlySaved.length;
11690
11918
  if (total === 0) return;
11691
- const parts = [
11919
+ const parts2 = [
11692
11920
  changed.length ? `changed: ${list(changed)}` : "",
11693
11921
  onlyLocal.length ? `only in the folder: ${list(onlyLocal)}` : "",
11694
11922
  onlySaved.length ? `only saved: ${list(onlySaved)}` : ""
11695
11923
  ].filter(Boolean);
11696
- ctx.output.warn(`The preview renders the saved version, not your folder: ${total} file${total === 1 ? "" : "s"} differ (${parts.join("; ")}). Push first: ${push}`);
11924
+ ctx.output.warn(`The preview renders the saved version, not your folder: ${total} file${total === 1 ? "" : "s"} differ (${parts2.join("; ")}). Push first: ${push}`);
11697
11925
  }
11698
11926
  function accountIds(value) {
11699
11927
  if (value === void 0) return void 0;
@@ -11704,7 +11932,7 @@ function accountIds(value) {
11704
11932
  }
11705
11933
  return ids2.map(Number);
11706
11934
  }
11707
- var SHOWN, command24, preview_default;
11935
+ var SHOWN, command25, preview_default;
11708
11936
  var init_preview = __esm({
11709
11937
  "src/commands/studio/preview.ts"() {
11710
11938
  "use strict";
@@ -11716,7 +11944,7 @@ var init_preview = __esm({
11716
11944
  init_common2();
11717
11945
  init_folder();
11718
11946
  SHOWN = 5;
11719
- command24 = {
11947
+ command25 = {
11720
11948
  resource: "studio",
11721
11949
  action: "preview",
11722
11950
  summary: "Render a saved version for up to 3 accounts; for local edits, studio push them to the draft first",
@@ -11765,14 +11993,14 @@ var init_preview = __esm({
11765
11993
  return ExitCode.Ok;
11766
11994
  }
11767
11995
  };
11768
- preview_default = command24;
11996
+ preview_default = command25;
11769
11997
  }
11770
11998
  });
11771
11999
 
11772
12000
  // src/commands/studio/fill-runs.ts
11773
12001
  import { setTimeout as delay5 } from "node:timers/promises";
11774
12002
  async function estimateFill(ctx, templateId, count) {
11775
- const parts = [];
12003
+ const parts2 = [];
11776
12004
  for (let left = count; left > 0; left -= RUN_SIZE) {
11777
12005
  const res = await ctx.client.request({
11778
12006
  method: "POST",
@@ -11780,22 +12008,22 @@ async function estimateFill(ctx, templateId, count) {
11780
12008
  body: { templateId, accountCount: Math.min(left, RUN_SIZE) },
11781
12009
  signal: ctx.signal
11782
12010
  });
11783
- parts.push(unwrap(res.body) ?? {});
12011
+ parts2.push(unwrap(res.body) ?? {});
11784
12012
  }
11785
- const millicredits = parts.reduce((sum, p) => sum + (p.millicredits ?? 0), 0);
12013
+ const millicredits = parts2.reduce((sum, p) => sum + (p.millicredits ?? 0), 0);
11786
12014
  const breakdown = /* @__PURE__ */ new Map();
11787
- for (const line of parts.flatMap((p) => p.breakdown ?? [])) {
12015
+ for (const line of parts2.flatMap((p) => p.breakdown ?? [])) {
11788
12016
  const item = line.item ?? "";
11789
12017
  breakdown.set(item, (breakdown.get(item) ?? 0) + (line.millicredits ?? 0));
11790
12018
  }
11791
12019
  return {
11792
12020
  templateId,
11793
- templateVersionId: parts[0]?.templateVersionId,
11794
- executor: parts[0]?.executor,
12021
+ templateVersionId: parts2[0]?.templateVersionId,
12022
+ executor: parts2[0]?.executor,
11795
12023
  accountCount: count,
11796
12024
  millicredits,
11797
12025
  credits: millicredits / 1e3,
11798
- perAccountMillicredits: parts[0]?.perAccountMillicredits,
12026
+ perAccountMillicredits: parts2[0]?.perAccountMillicredits,
11799
12027
  breakdown: [...breakdown.entries()].map(([item, sum]) => ({ item, millicredits: sum }))
11800
12028
  };
11801
12029
  }
@@ -11873,7 +12101,7 @@ __export(fill_exports, {
11873
12101
  default: () => fill_default
11874
12102
  });
11875
12103
  import { createHash as createHash8 } from "node:crypto";
11876
- import { readFile as readFile10 } from "node:fs/promises";
12104
+ import { readFile as readFile11 } from "node:fs/promises";
11877
12105
  import { join as join14, resolve as resolve12 } from "node:path";
11878
12106
  async function readTarget(ctx, flags) {
11879
12107
  const accounts = stringFlag(flags.accounts);
@@ -11907,7 +12135,7 @@ async function readTarget(ctx, flags) {
11907
12135
  items: [...firstRow].map(([id, row]) => ({ id, row })),
11908
12136
  duplicates: raw.length - firstRow.size,
11909
12137
  ...campaign !== void 0 ? { campaignId: positiveId2(campaign, "campaign") } : {},
11910
- input: source === "-" ? { path: "-", sha256: sha2562(raw.join("\n")) } : { path: resolve12(source), sha256: sha2562(await readFile10(resolve12(source))) }
12138
+ input: source === "-" ? { path: "-", sha256: sha2562(raw.join("\n")) } : { path: resolve12(source), sha256: sha2562(await readFile11(resolve12(source))) }
11911
12139
  };
11912
12140
  }
11913
12141
  async function refuseRefill(ctx, args, target) {
@@ -11966,7 +12194,7 @@ function estimateOutput(templateId, target, estimate2) {
11966
12194
  ...target.campaignId !== void 0 ? { estimateNote: "An upper bound: it counts one page per lead, and a campaign run builds one page per company." } : {}
11967
12195
  };
11968
12196
  }
11969
- var COMMAND6, sha2562, command25, fill_default;
12197
+ var COMMAND6, sha2562, command26, fill_default;
11970
12198
  var init_fill = __esm({
11971
12199
  "src/commands/studio/fill.ts"() {
11972
12200
  "use strict";
@@ -11982,7 +12210,7 @@ var init_fill = __esm({
11982
12210
  init_fill_runs();
11983
12211
  COMMAND6 = "studio fill";
11984
12212
  sha2562 = (data) => createHash8("sha256").update(data).digest("hex");
11985
- command25 = {
12213
+ command26 = {
11986
12214
  resource: "studio",
11987
12215
  action: "fill",
11988
12216
  summary: "Fill a template on many accounts or campaign leads (estimate first)",
@@ -12042,16 +12270,16 @@ var init_fill = __esm({
12042
12270
  return outcome.exitCode;
12043
12271
  }
12044
12272
  };
12045
- fill_default = command25;
12273
+ fill_default = command26;
12046
12274
  }
12047
12275
  });
12048
12276
 
12049
12277
  // src/commands/studio/index.ts
12050
- var actions14;
12278
+ var actions15;
12051
12279
  var init_studio2 = __esm({
12052
12280
  "src/commands/studio/index.ts"() {
12053
12281
  "use strict";
12054
- actions14 = {
12282
+ actions15 = {
12055
12283
  pull: () => Promise.resolve().then(() => (init_pull(), pull_exports)).then((m) => m.default),
12056
12284
  push: () => Promise.resolve().then(() => (init_push(), push_exports)).then((m) => m.default),
12057
12285
  validate: () => Promise.resolve().then(() => (init_validate(), validate_exports)).then((m) => m.default),
@@ -12193,7 +12421,7 @@ function readBody(req) {
12193
12421
  function reply(res, status, body) {
12194
12422
  res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
12195
12423
  }
12196
- var MIN_POLL_MS, MAX_POLL_MS, MAX_TRIGGER_BYTES, command26, listen_default;
12424
+ var MIN_POLL_MS, MAX_POLL_MS, MAX_TRIGGER_BYTES, command27, listen_default;
12197
12425
  var init_listen = __esm({
12198
12426
  "src/commands/webhooks/listen.ts"() {
12199
12427
  "use strict";
@@ -12204,7 +12432,7 @@ var init_listen = __esm({
12204
12432
  MIN_POLL_MS = 1e3;
12205
12433
  MAX_POLL_MS = 6e4;
12206
12434
  MAX_TRIGGER_BYTES = 1e6;
12207
- command26 = {
12435
+ command27 = {
12208
12436
  resource: "webhooks",
12209
12437
  action: "listen",
12210
12438
  summary: "Stream the workspace's events and forward them, signed, to a local handler",
@@ -12310,7 +12538,7 @@ var init_listen = __esm({
12310
12538
  return ExitCode.Ok;
12311
12539
  }
12312
12540
  };
12313
- listen_default = command26;
12541
+ listen_default = command27;
12314
12542
  }
12315
12543
  });
12316
12544
 
@@ -12329,7 +12557,7 @@ function notRunning() {
12329
12557
  next: LISTEN_NEXT
12330
12558
  });
12331
12559
  }
12332
- var LISTEN_NEXT, command27, trigger_default;
12560
+ var LISTEN_NEXT, command28, trigger_default;
12333
12561
  var init_trigger = __esm({
12334
12562
  "src/commands/webhooks/trigger.ts"() {
12335
12563
  "use strict";
@@ -12338,7 +12566,7 @@ var init_trigger = __esm({
12338
12566
  init_http();
12339
12567
  init_local();
12340
12568
  LISTEN_NEXT = "kenso webhooks listen --forward-to http://localhost:3000/hook";
12341
- command27 = {
12569
+ command28 = {
12342
12570
  resource: "webhooks",
12343
12571
  action: "trigger",
12344
12572
  summary: "Send a sample event of one type through the running kenso webhooks listen",
@@ -12395,16 +12623,16 @@ var init_trigger = __esm({
12395
12623
  return ExitCode.Ok;
12396
12624
  }
12397
12625
  };
12398
- trigger_default = command27;
12626
+ trigger_default = command28;
12399
12627
  }
12400
12628
  });
12401
12629
 
12402
12630
  // src/commands/webhooks/index.ts
12403
- var actions15;
12631
+ var actions16;
12404
12632
  var init_webhooks2 = __esm({
12405
12633
  "src/commands/webhooks/index.ts"() {
12406
12634
  "use strict";
12407
- actions15 = {
12635
+ actions16 = {
12408
12636
  listen: () => Promise.resolve().then(() => (init_listen(), listen_exports)).then((m) => m.default),
12409
12637
  trigger: () => Promise.resolve().then(() => (init_trigger(), trigger_exports)).then((m) => m.default)
12410
12638
  };
@@ -12591,14 +12819,14 @@ var status_exports2 = {};
12591
12819
  __export(status_exports2, {
12592
12820
  default: () => status_default2
12593
12821
  });
12594
- var command28, status_default2;
12822
+ var command29, status_default2;
12595
12823
  var init_status2 = __esm({
12596
12824
  "src/commands/work/status.ts"() {
12597
12825
  "use strict";
12598
12826
  init_exit_codes();
12599
12827
  init_http();
12600
12828
  init_common3();
12601
- command28 = {
12829
+ command29 = {
12602
12830
  resource: "work",
12603
12831
  action: "status",
12604
12832
  summary: "Show the Kenso AI work waiting for your own agent, per kind",
@@ -12631,7 +12859,7 @@ var init_status2 = __esm({
12631
12859
  return ExitCode.Ok;
12632
12860
  }
12633
12861
  };
12634
- status_default2 = command28;
12862
+ status_default2 = command29;
12635
12863
  }
12636
12864
  });
12637
12865
 
@@ -12763,9 +12991,9 @@ var init_files = __esm({
12763
12991
  import { execFile, spawnSync as spawnSync2 } from "node:child_process";
12764
12992
  import { readFileSync as readFileSync12 } from "node:fs";
12765
12993
  import { isAbsolute as isAbsolute2 } from "node:path";
12766
- function sudoArgs(user, command35, args, keep = [], set = {}) {
12994
+ function sudoArgs(user, command36, args, keep = [], set = {}) {
12767
12995
  const assignments = Object.entries(set).map(([name, value]) => `${name}=${value}`);
12768
- return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command35, ...args];
12996
+ return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command36, ...args];
12769
12997
  }
12770
12998
  function agentKensoEnv(opts) {
12771
12999
  return {
@@ -12775,12 +13003,12 @@ function agentKensoEnv(opts) {
12775
13003
  AI_AGENT: opts.agentName
12776
13004
  };
12777
13005
  }
12778
- function sudoExec(user, command35, args, opts = {}) {
13006
+ function sudoExec(user, command36, args, opts = {}) {
12779
13007
  const [sudo = "/usr/bin/sudo", ...lead] = user.sudo;
12780
13008
  return new Promise((resolve16) => {
12781
13009
  execFile(
12782
13010
  sudo,
12783
- [...lead, ...sudoArgs(user.name, command35, args)],
13011
+ [...lead, ...sudoArgs(user.name, command36, args)],
12784
13012
  { env: { PATH: SUDO_PATH }, cwd: "/", timeout: opts.timeoutMs ?? PROBE_TIMEOUT_MS, maxBuffer: opts.maxBuffer ?? 1024 * 1024, encoding: "utf8", windowsHide: true, shell: false },
12785
13013
  (err, stdout, stderr) => {
12786
13014
  const code = err ? err.code : 0;
@@ -12890,9 +13118,9 @@ var init_folder2 = __esm({
12890
13118
  init_redact();
12891
13119
  init_agent_user();
12892
13120
  WorkRunFolder = class {
12893
- constructor(ctx, command35, args, outDir, shared = false) {
13121
+ constructor(ctx, command36, args, outDir, shared = false) {
12894
13122
  this.ctx = ctx;
12895
- this.command = command35;
13123
+ this.command = command36;
12896
13124
  this.args = args;
12897
13125
  this.outDir = outDir;
12898
13126
  this.shared = shared;
@@ -13007,7 +13235,7 @@ var pull_exports2 = {};
13007
13235
  __export(pull_exports2, {
13008
13236
  default: () => pull_default2
13009
13237
  });
13010
- var MAX_FILES, command29, pull_default2;
13238
+ var MAX_FILES, command30, pull_default2;
13011
13239
  var init_pull2 = __esm({
13012
13240
  "src/commands/work/pull.ts"() {
13013
13241
  "use strict";
@@ -13016,7 +13244,7 @@ var init_pull2 = __esm({
13016
13244
  init_common3();
13017
13245
  init_folder2();
13018
13246
  MAX_FILES = 100;
13019
- command29 = {
13247
+ command30 = {
13020
13248
  resource: "work",
13021
13249
  action: "pull",
13022
13250
  summary: "Claim waiting work into local work files, to answer by hand",
@@ -13092,7 +13320,7 @@ var init_pull2 = __esm({
13092
13320
  return interrupted6 ? ExitCode.Interrupted : ExitCode.Ok;
13093
13321
  }
13094
13322
  };
13095
- pull_default2 = command29;
13323
+ pull_default2 = command30;
13096
13324
  }
13097
13325
  });
13098
13326
 
@@ -13234,7 +13462,7 @@ __export(submit_exports, {
13234
13462
  default: () => submit_default
13235
13463
  });
13236
13464
  import { resolve as resolve14 } from "node:path";
13237
- var command30, submit_default;
13465
+ var command31, submit_default;
13238
13466
  var init_submit = __esm({
13239
13467
  "src/commands/work/submit.ts"() {
13240
13468
  "use strict";
@@ -13243,7 +13471,7 @@ var init_submit = __esm({
13243
13471
  init_files();
13244
13472
  init_answers();
13245
13473
  init_common3();
13246
- command30 = {
13474
+ command31 = {
13247
13475
  resource: "work",
13248
13476
  action: "submit",
13249
13477
  summary: "Send answers files to Kenso and write each one's results",
@@ -13275,7 +13503,7 @@ var init_submit = __esm({
13275
13503
  return totals.rejected > 0 ? ExitCode.Partial : ExitCode.Ok;
13276
13504
  }
13277
13505
  };
13278
- submit_default = command30;
13506
+ submit_default = command31;
13279
13507
  }
13280
13508
  });
13281
13509
 
@@ -13296,7 +13524,7 @@ function claimIdOf(arg) {
13296
13524
  if (!CLAIM_ID.test(arg)) throw usageError(`"${arg}" is neither a claim id nor a work file.`, { field: "claim", hint: "Claim ids look like awc_8fK2..." });
13297
13525
  return arg;
13298
13526
  }
13299
- var CLAIM_ID, command31, release_default;
13527
+ var CLAIM_ID, command32, release_default;
13300
13528
  var init_release = __esm({
13301
13529
  "src/commands/work/release.ts"() {
13302
13530
  "use strict";
@@ -13305,7 +13533,7 @@ var init_release = __esm({
13305
13533
  init_files();
13306
13534
  init_common3();
13307
13535
  CLAIM_ID = /^[A-Za-z0-9_-]{1,64}$/;
13308
- command31 = {
13536
+ command32 = {
13309
13537
  resource: "work",
13310
13538
  action: "release",
13311
13539
  summary: "Give claimed work back to the queue now",
@@ -13324,7 +13552,7 @@ var init_release = __esm({
13324
13552
  return ExitCode.Ok;
13325
13553
  }
13326
13554
  };
13327
- release_default = command31;
13555
+ release_default = command32;
13328
13556
  }
13329
13557
  });
13330
13558
 
@@ -13663,12 +13891,12 @@ function plain(text3) {
13663
13891
  return text3.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
13664
13892
  }
13665
13893
  function runStatus(bin, args, env, adapter, runAs) {
13666
- const command35 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
13894
+ const command36 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
13667
13895
  const commandArgs2 = runAs ? [...runAs.sudo.slice(1), ...sudoArgs(runAs.name, bin, args)] : args;
13668
13896
  const options = runAs ? { env: { PATH: SUDO_PATH }, cwd: "/" } : { env: childEnv(env, adapter) };
13669
13897
  return new Promise((resolve16) => {
13670
13898
  execFile2(
13671
- command35,
13899
+ command36,
13672
13900
  commandArgs2,
13673
13901
  { ...options, timeout: STATUS_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
13674
13902
  (err, stdout, stderr) => {
@@ -14302,8 +14530,8 @@ import { closeSync as closeSync2, fchmodSync as fchmodSync2, openSync as openSyn
14302
14530
  import { join as join23 } from "node:path";
14303
14531
  function agentGuide(opts) {
14304
14532
  const browser = opts.browser ?? findOperation("browser-runs", "create") !== void 0;
14305
- const parts = opts.kensoKey ? [JOB, KENSO, ...browser ? [BROWSER] : [], NEVER] : [JOB, NO_KENSO, NEVER];
14306
- return parts.join("\n");
14533
+ const parts2 = opts.kensoKey ? [JOB, KENSO, ...browser ? [BROWSER] : [], NEVER] : [JOB, NO_KENSO, NEVER];
14534
+ return parts2.join("\n");
14307
14535
  }
14308
14536
  function writeAgentGuide(dir, text3, mode = WORK_FILE_MODE) {
14309
14537
  for (const name of GUIDE_FILES) {
@@ -14748,7 +14976,7 @@ var run_exports = {};
14748
14976
  __export(run_exports, {
14749
14977
  default: () => run_default
14750
14978
  });
14751
- var FAILURES_IN_A_ROW, command32, run_default;
14979
+ var FAILURES_IN_A_ROW, command33, run_default;
14752
14980
  var init_run = __esm({
14753
14981
  "src/commands/work/run.ts"() {
14754
14982
  "use strict";
@@ -14769,7 +14997,7 @@ var init_run = __esm({
14769
14997
  init_folder2();
14770
14998
  init_stop();
14771
14999
  FAILURES_IN_A_ROW = 3;
14772
- command32 = {
15000
+ command33 = {
14773
15001
  resource: "work",
14774
15002
  action: "run",
14775
15003
  summary: "Run your own coding agent on the waiting work until the queue is empty",
@@ -14980,7 +15208,7 @@ var init_run = __esm({
14980
15208
  return;
14981
15209
  }
14982
15210
  const jobTotals = zeroTotals();
14983
- let done = 0;
15211
+ let done2 = 0;
14984
15212
  let submitError;
14985
15213
  let kept;
14986
15214
  let refused;
@@ -14994,7 +15222,7 @@ var init_run = __esm({
14994
15222
  ...scanner ? { check: (answers, agent) => scanner.check(answers, agent) } : {}
14995
15223
  });
14996
15224
  addTotals(jobTotals, sent.totals);
14997
- done = settled(sent.results);
15225
+ done2 = settled(sent.results);
14998
15226
  } catch (err) {
14999
15227
  if (err instanceof AnswerRefusedError) {
15000
15228
  refused = err;
@@ -15006,7 +15234,7 @@ var init_run = __esm({
15006
15234
  }
15007
15235
  }
15008
15236
  }
15009
- const giveBack = kept === void 0 && (done < claim.items.length || stop.signal.aborted);
15237
+ const giveBack = kept === void 0 && (done2 < claim.items.length || stop.signal.aborted);
15010
15238
  if (giveBack) await releaseOnce(claim.id);
15011
15239
  else open.delete(claim.id);
15012
15240
  if (kept !== void 0) {
@@ -15092,16 +15320,16 @@ var init_run = __esm({
15092
15320
  return exitCodeFor(reason, totals.rejected > 0 || jobsFailed > 0);
15093
15321
  }
15094
15322
  };
15095
- run_default = command32;
15323
+ run_default = command33;
15096
15324
  }
15097
15325
  });
15098
15326
 
15099
15327
  // src/commands/work/index.ts
15100
- var actions16;
15328
+ var actions17;
15101
15329
  var init_work2 = __esm({
15102
15330
  "src/commands/work/index.ts"() {
15103
15331
  "use strict";
15104
- actions16 = {
15332
+ actions17 = {
15105
15333
  status: () => Promise.resolve().then(() => (init_status2(), status_exports2)).then((m) => m.default),
15106
15334
  pull: () => Promise.resolve().then(() => (init_pull2(), pull_exports2)).then((m) => m.default),
15107
15335
  submit: () => Promise.resolve().then(() => (init_submit(), submit_exports)).then((m) => m.default),
@@ -15125,14 +15353,14 @@ function parseLimit(value) {
15125
15353
  }
15126
15354
  return limit;
15127
15355
  }
15128
- var MAX_LIMIT, command33, list_default2;
15356
+ var MAX_LIMIT, command34, list_default2;
15129
15357
  var init_list2 = __esm({
15130
15358
  "src/commands/workspace/list.ts"() {
15131
15359
  "use strict";
15132
15360
  init_errors();
15133
15361
  init_exit_codes();
15134
15362
  MAX_LIMIT = 200;
15135
- command33 = {
15363
+ command34 = {
15136
15364
  resource: "workspace",
15137
15365
  action: "list",
15138
15366
  summary: "List the workspaces your key can use",
@@ -15160,7 +15388,7 @@ var init_list2 = __esm({
15160
15388
  return ExitCode.Ok;
15161
15389
  }
15162
15390
  };
15163
- list_default2 = command33;
15391
+ list_default2 = command34;
15164
15392
  }
15165
15393
  });
15166
15394
 
@@ -15169,7 +15397,7 @@ var use_exports = {};
15169
15397
  __export(use_exports, {
15170
15398
  default: () => use_default
15171
15399
  });
15172
- var command34, use_default;
15400
+ var command35, use_default;
15173
15401
  var init_use = __esm({
15174
15402
  "src/commands/workspace/use.ts"() {
15175
15403
  "use strict";
@@ -15177,7 +15405,7 @@ var init_use = __esm({
15177
15405
  init_errors();
15178
15406
  init_exit_codes();
15179
15407
  init_http();
15180
- command34 = {
15408
+ command35 = {
15181
15409
  resource: "workspace",
15182
15410
  action: "use",
15183
15411
  summary: "Set the profile's default workspace",
@@ -15234,16 +15462,16 @@ var init_use = __esm({
15234
15462
  return ExitCode.Ok;
15235
15463
  }
15236
15464
  };
15237
- use_default = command34;
15465
+ use_default = command35;
15238
15466
  }
15239
15467
  });
15240
15468
 
15241
15469
  // src/commands/workspace/index.ts
15242
- var actions17;
15470
+ var actions18;
15243
15471
  var init_workspace = __esm({
15244
15472
  "src/commands/workspace/index.ts"() {
15245
15473
  "use strict";
15246
- actions17 = {
15474
+ actions18 = {
15247
15475
  list: () => Promise.resolve().then(() => (init_list2(), list_exports2)).then((m) => m.default),
15248
15476
  use: () => Promise.resolve().then(() => (init_use(), use_exports)).then((m) => m.default)
15249
15477
  };
@@ -15267,6 +15495,7 @@ var init_registry = __esm({
15267
15495
  init_agent2();
15268
15496
  init_api3();
15269
15497
  init_auth2();
15498
+ init_completion2();
15270
15499
  init_contacts();
15271
15500
  init_describe2();
15272
15501
  init_docs2();
@@ -15285,22 +15514,23 @@ var init_registry = __esm({
15285
15514
  agent: actions2,
15286
15515
  api: actions3,
15287
15516
  auth: actions4,
15288
- contacts: actions5,
15289
- describe: actions6,
15290
- docs: actions7,
15291
- doctor: actions8,
15292
- jobs: actions9,
15517
+ completion: actions5,
15518
+ contacts: actions6,
15519
+ describe: actions7,
15520
+ docs: actions8,
15521
+ doctor: actions9,
15522
+ jobs: actions10,
15293
15523
  login: topLevel("login", actions4.login, "kenso auth login"),
15294
15524
  logout: topLevel("logout", actions4.logout, "kenso auth logout"),
15295
- mcp: actions10,
15296
- people: actions11,
15297
- runs: actions12,
15298
- skill: actions13,
15299
- studio: actions14,
15300
- webhooks: actions15,
15525
+ mcp: actions11,
15526
+ people: actions12,
15527
+ runs: actions13,
15528
+ skill: actions14,
15529
+ studio: actions15,
15530
+ webhooks: actions16,
15301
15531
  whoami: topLevel("whoami", actions4.status, "kenso auth status"),
15302
- work: actions16,
15303
- workspace: actions17
15532
+ work: actions17,
15533
+ workspace: actions18
15304
15534
  };
15305
15535
  resourceAliases = { leads: "contacts" };
15306
15536
  }
@@ -15322,10 +15552,10 @@ function lazyFeatures(opts) {
15322
15552
  };
15323
15553
  }
15324
15554
  function describeGates(gates) {
15325
- const parts = [];
15326
- if (gates.all?.length) parts.push(gates.all.join(" and "));
15327
- if (gates.any?.length) parts.push(gates.any.length === 1 ? gates.any[0] : `one of ${gates.any.join(", ")}`);
15328
- return parts.join(" and ");
15555
+ const parts2 = [];
15556
+ if (gates.all?.length) parts2.push(gates.all.join(" and "));
15557
+ if (gates.any?.length) parts2.push(gates.any.length === 1 ? gates.any[0] : `one of ${gates.any.join(", ")}`);
15558
+ return parts2.join(" and ");
15329
15559
  }
15330
15560
  async function visibleSpecs(specs, opts, getFeatures, hidden) {
15331
15561
  const visible = [];
@@ -15388,10 +15618,10 @@ function commandName(spec) {
15388
15618
  return spec.action ? `kenso ${spec.resource} ${spec.action}` : `kenso ${spec.resource}`;
15389
15619
  }
15390
15620
  function usageLine2(spec) {
15391
- const parts = [commandName(spec)];
15392
- for (const p of spec.positionals ?? []) parts.push(`${p.required ? `<${p.name}>` : `[${p.name}]`}${p.variadic ? "..." : ""}`);
15393
- if (Object.keys(spec.flags).length > 0) parts.push("[flags]");
15394
- return parts.join(" ");
15621
+ const parts2 = [commandName(spec)];
15622
+ for (const p of spec.positionals ?? []) parts2.push(`${p.required ? `<${p.name}>` : `[${p.name}]`}${p.variadic ? "..." : ""}`);
15623
+ if (Object.keys(spec.flags).length > 0) parts2.push("[flags]");
15624
+ return parts2.join(" ");
15395
15625
  }
15396
15626
  function flagLabel(name, flag) {
15397
15627
  const long = `--${name}${flag.type === "string" ? " <value>" : ""}`;
@@ -15437,8 +15667,8 @@ async function renderTopHelp(opts) {
15437
15667
  names.push(withPositionals(spec, spec.action));
15438
15668
  groups.set(hint, names);
15439
15669
  }
15440
- const actions18 = [...groups.entries()].map(([hint, names]) => `${names.join(", ")}${hint}`);
15441
- if (actions18.length > 0) rows.push([resource, actions18.join(", ")]);
15670
+ const actions20 = [...groups.entries()].map(([hint, names]) => `${names.join(", ")}${hint}`);
15671
+ if (actions20.length > 0) rows.push([resource, actions20.join(", ")]);
15442
15672
  }
15443
15673
  const at = 4 + Math.min(22, Math.max(0, ...rows.map(([left]) => left.length)));
15444
15674
  lines.push(
@@ -15451,7 +15681,7 @@ async function renderTopHelp(opts) {
15451
15681
  const [area = "", action = ""] = name.split(" ");
15452
15682
  byArea.set(area, [...byArea.get(area) ?? [], action]);
15453
15683
  }
15454
- const named = [...byArea.entries()].map(([area, actions18]) => `${area} ${actions18.join("|")}`);
15684
+ const named = [...byArea.entries()].map(([area, actions20]) => `${area} ${actions20.join("|")}`);
15455
15685
  lines.push(wrap(`Beta, hidden here but they run (the server decides): ${named.join(", ")}.`, " "));
15456
15686
  }
15457
15687
  const generated = await listGenerated({ features: opts.allCommands ? [] : getFeatures, env: opts.env });
@@ -15459,16 +15689,16 @@ async function renderTopHelp(opts) {
15459
15689
  if (visible.length > 0) {
15460
15690
  const byResource = /* @__PURE__ */ new Map();
15461
15691
  for (const g of visible) {
15462
- const actions18 = byResource.get(g.resource) ?? [];
15463
- actions18.push(`${g.action}${g.beta ? " (beta)" : ""}`);
15464
- byResource.set(g.resource, actions18);
15692
+ const actions20 = byResource.get(g.resource) ?? [];
15693
+ actions20.push(`${g.action}${g.beta ? " (beta)" : ""}`);
15694
+ byResource.set(g.resource, actions20);
15465
15695
  }
15466
- const sorted = [...byResource.entries()].sort(([a], [b]) => a.localeCompare(b));
15696
+ const sorted2 = [...byResource.entries()].sort(([a], [b]) => a.localeCompare(b));
15467
15697
  if (opts.allCommands) {
15468
- const generatedRows = sorted.map(([resource, actions18]) => [resource, actions18.sort().join(", ")]);
15698
+ const generatedRows = sorted2.map(([resource, actions20]) => [resource, actions20.sort().join(", ")]);
15469
15699
  lines.push("", "API resources (kenso <resource> <action>):", columns(generatedRows));
15470
15700
  } else {
15471
- const names = new Set(sorted.map(([resource]) => resource));
15701
+ const names = new Set(sorted2.map(([resource]) => resource));
15472
15702
  const common = COMMON_RESOURCES.filter((r) => names.has(r)).join(", ");
15473
15703
  const hidden = generated.length - visible.length + hiddenSpecs.count;
15474
15704
  lines.push(
@@ -15606,6 +15836,27 @@ var init_help = __esm({
15606
15836
  }
15607
15837
  });
15608
15838
 
15839
+ // src/core/closed-pipe.ts
15840
+ function guardClosedPipe(stream) {
15841
+ if (guardedStreams.has(stream)) return;
15842
+ guardedStreams.add(stream);
15843
+ stream.on("error", (err) => {
15844
+ if (err.code === "EPIPE") {
15845
+ process.exit(ExitCode.Ok);
15846
+ return;
15847
+ }
15848
+ throw err;
15849
+ });
15850
+ }
15851
+ var guardedStreams;
15852
+ var init_closed_pipe = __esm({
15853
+ "src/core/closed-pipe.ts"() {
15854
+ "use strict";
15855
+ init_exit_codes();
15856
+ guardedStreams = /* @__PURE__ */ new WeakSet();
15857
+ }
15858
+ });
15859
+
15609
15860
  // src/core/flag-names.ts
15610
15861
  function distance(a, b) {
15611
15862
  let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
@@ -15655,13 +15906,234 @@ var init_flag_names = __esm({
15655
15906
  }
15656
15907
  });
15657
15908
 
15909
+ // src/core/invoked.ts
15910
+ import { realpathSync } from "node:fs";
15911
+ import { pathToFileURL } from "node:url";
15912
+ function invokedDirectly(moduleUrl) {
15913
+ const script = process.argv[1];
15914
+ if (!script) return false;
15915
+ try {
15916
+ return moduleUrl === pathToFileURL(realpathSync(script)).href;
15917
+ } catch {
15918
+ return false;
15919
+ }
15920
+ }
15921
+ var init_invoked = __esm({
15922
+ "src/core/invoked.ts"() {
15923
+ "use strict";
15924
+ }
15925
+ });
15926
+
15927
+ // src/core/update-notice.ts
15928
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync13, renameSync as renameSync4, writeFileSync as writeFileSync7 } from "node:fs";
15929
+ import { dirname as dirname5, join as join24 } from "node:path";
15930
+ function readCheck(file) {
15931
+ try {
15932
+ const parsed2 = JSON.parse(readFileSync13(file, "utf8"));
15933
+ if (typeof parsed2?.checkedAt !== "string") return void 0;
15934
+ return { checkedAt: parsed2.checkedAt, ...typeof parsed2.latest === "string" ? { latest: parsed2.latest } : {} };
15935
+ } catch {
15936
+ return void 0;
15937
+ }
15938
+ }
15939
+ function writeCheck(file, check) {
15940
+ try {
15941
+ mkdirSync5(dirname5(file), { recursive: true, mode: 448 });
15942
+ const temp = `${file}.${process.pid}.tmp`;
15943
+ writeFileSync7(temp, `${JSON.stringify(check)}
15944
+ `, { mode: 384 });
15945
+ renameSync4(temp, file);
15946
+ } catch {
15947
+ }
15948
+ }
15949
+ function parts(version) {
15950
+ const match = RELEASE.exec(version);
15951
+ return match ? match.slice(1).map(Number) : void 0;
15952
+ }
15953
+ function isNewer(latest, current) {
15954
+ const a = parts(latest);
15955
+ const b = parts(current);
15956
+ if (!a || !b) return false;
15957
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
15958
+ return false;
15959
+ }
15960
+ async function fetchLatest(fetchImpl, signal) {
15961
+ const res = await fetchImpl(REGISTRY_URL, { signal, headers: { accept: "application/json" } });
15962
+ if (!res.ok) return void 0;
15963
+ const body = await res.json();
15964
+ return typeof body?.version === "string" && RELEASE.test(body.version) ? body.version : void 0;
15965
+ }
15966
+ function startUpdateNotice(argv, opts = {}) {
15967
+ try {
15968
+ const env = opts.env ?? process.env;
15969
+ const version = opts.version ?? VERSION;
15970
+ const stderr = opts.stderr ?? process.stderr;
15971
+ const wanted = (opts.stderrIsTTY ?? process.stderr.isTTY === true) && detectAgent(env) === null && env.CI === void 0 && !env.KENSO_NO_UPDATE_NOTIFIER && RELEASE.test(version) && !argv.some((word) => QUIET_COMMANDS.has(word));
15972
+ if (!wanted) return done;
15973
+ const file = join24(configDir(env), UPDATE_CHECK_FILE);
15974
+ const now = (opts.now ?? Date.now)();
15975
+ const cached = readCheck(file);
15976
+ const checkedAt = Date.parse(cached?.checkedAt ?? "");
15977
+ if (checkedAt <= now && now - checkedAt < CHECK_EVERY_MS) return done;
15978
+ writeCheck(file, { checkedAt: new Date(now).toISOString(), ...cached?.latest ? { latest: cached.latest } : {} });
15979
+ const stop = new AbortController();
15980
+ const signal = AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS3), stop.signal]);
15981
+ const latest = fetchLatest(opts.fetchImpl ?? fetch, signal).catch(() => void 0);
15982
+ return async () => {
15983
+ try {
15984
+ const timer = setTimeout(() => stop.abort(), opts.waitMs ?? WAIT_AFTER_COMMAND_MS);
15985
+ timer.unref();
15986
+ const found = await latest;
15987
+ clearTimeout(timer);
15988
+ if (!found) return;
15989
+ writeCheck(file, { checkedAt: new Date(now).toISOString(), latest: found });
15990
+ if (isNewer(found, version)) {
15991
+ stderr.write(`kenso ${found} is out (you have ${version}): npm i -g kenso@latest
15992
+ Turn this off with KENSO_NO_UPDATE_NOTIFIER=1.
15993
+ `);
15994
+ }
15995
+ } catch {
15996
+ }
15997
+ };
15998
+ } catch {
15999
+ return done;
16000
+ }
16001
+ }
16002
+ var UPDATE_CHECK_FILE, REGISTRY_URL, CHECK_EVERY_MS, REQUEST_TIMEOUT_MS3, WAIT_AFTER_COMMAND_MS, QUIET_COMMANDS, RELEASE, done;
16003
+ var init_update_notice = __esm({
16004
+ "src/core/update-notice.ts"() {
16005
+ "use strict";
16006
+ init_agent();
16007
+ init_config();
16008
+ init_version();
16009
+ UPDATE_CHECK_FILE = "update-check.json";
16010
+ REGISTRY_URL = "https://registry.npmjs.org/kenso/latest";
16011
+ CHECK_EVERY_MS = 7 * 24 * 60 * 60 * 1e3;
16012
+ REQUEST_TIMEOUT_MS3 = 5e3;
16013
+ WAIT_AFTER_COMMAND_MS = 1e3;
16014
+ QUIET_COMMANDS = /* @__PURE__ */ new Set(["completion", "__complete"]);
16015
+ RELEASE = /^(\d+)\.(\d+)\.([1-9]\d*)$/;
16016
+ done = async () => {
16017
+ };
16018
+ }
16019
+ });
16020
+
16021
+ // src/commands/completion/complete.ts
16022
+ var complete_exports = {};
16023
+ __export(complete_exports, {
16024
+ COMPLETE_COMMAND: () => COMPLETE_COMMAND,
16025
+ completions: () => completions,
16026
+ printCompletions: () => printCompletions
16027
+ });
16028
+ function resources() {
16029
+ const names = Object.entries(handWritten).filter(([, area]) => Object.keys(area).length > 0).map(([resource]) => resource);
16030
+ return sorted([...names, ...Object.keys(resourceAliases), ...loadManifest().operations.map((op) => op.resource)]);
16031
+ }
16032
+ function actions19(resource) {
16033
+ const own = Object.keys(handWritten[resource] ?? {}).filter((action) => action !== "");
16034
+ return sorted([...own, ...loadManifest().operations.filter((op) => op.resource === resource).map((op) => op.action)]);
16035
+ }
16036
+ function flagName(word, spec, globals) {
16037
+ if (word.startsWith("--")) return word.slice(2).split("=")[0];
16038
+ if (word.length !== 2) return void 0;
16039
+ const letter = word[1];
16040
+ const own = spec ? Object.entries(spec.flags).find(([, flag]) => flag.short === letter)?.[0] : void 0;
16041
+ return own ?? Object.entries(globals).find(([, option]) => option.short === letter)?.[0];
16042
+ }
16043
+ function optionOf(name, spec, globals) {
16044
+ const flags = spec?.flags ?? {};
16045
+ return flags[name] ?? Object.values(flags).find((flag) => flag.aliases?.includes(name)) ?? globals[name];
16046
+ }
16047
+ function flagsOf2(spec, globals, commandless) {
16048
+ const global = Object.keys(globals).filter((name) => commandless || name !== "version" && (name !== "dry-run" || spec?.dryRun === true));
16049
+ return sorted([...Object.keys(spec?.flags ?? {}), ...global].map((name) => `--${name}`));
16050
+ }
16051
+ async function completions(words, globals) {
16052
+ const current = words.at(-1) ?? "";
16053
+ const positionals = [];
16054
+ let spec;
16055
+ let commandWords = 0;
16056
+ let valueFor;
16057
+ let afterDashes = false;
16058
+ let help = false;
16059
+ for (const word of words.slice(0, -1)) {
16060
+ if (valueFor !== void 0) {
16061
+ valueFor = void 0;
16062
+ continue;
16063
+ }
16064
+ if (!afterDashes && word === "--") {
16065
+ afterDashes = true;
16066
+ continue;
16067
+ }
16068
+ if (!afterDashes && word.startsWith("-") && word !== "-") {
16069
+ const name = flagName(word, spec, globals);
16070
+ if (name !== void 0 && !word.includes("=") && optionOf(name, spec, globals)?.type === "string") valueFor = name;
16071
+ continue;
16072
+ }
16073
+ if (positionals.length === 0 && word === "help" && !help) {
16074
+ help = true;
16075
+ continue;
16076
+ }
16077
+ positionals.push(word);
16078
+ if (spec) continue;
16079
+ const resource = resourceAliases[positionals[0]] ?? positionals[0];
16080
+ const area = handWritten[resource] ?? {};
16081
+ if (positionals.length === 1 && area[""]) {
16082
+ spec = await area[""]();
16083
+ commandWords = 1;
16084
+ } else if (positionals.length === 2) {
16085
+ const loader = area[positionals[1]];
16086
+ spec = (loader ? await loader() : await resolveGenerated(resource, positionals[1])) ?? void 0;
16087
+ commandWords = 2;
16088
+ }
16089
+ }
16090
+ if (valueFor !== void 0) return [...FLAG_VALUES[valueFor] ?? []];
16091
+ if (!afterDashes && current.startsWith("-")) {
16092
+ const inline = /^--([^=]+)=/.exec(current);
16093
+ if (inline) return (FLAG_VALUES[inline[1]] ?? []).map((value) => `--${inline[1]}=${value}`);
16094
+ return flagsOf2(spec, globals, positionals.length === 0);
16095
+ }
16096
+ if (positionals.length === 0) return resources();
16097
+ if (!spec) return positionals.length === 1 ? actions19(resourceAliases[positionals[0]] ?? positionals[0]) : [];
16098
+ const given = positionals.length - commandWords;
16099
+ const declared = spec.positionals ?? [];
16100
+ if (given < declared.length || declared.at(-1)?.variadic === true) {
16101
+ return given === 0 ? [...POSITIONAL_VALUES[spec.resource] ?? []] : [];
16102
+ }
16103
+ return flagsOf2(spec, globals, false);
16104
+ }
16105
+ async function printCompletions(words, globals, stdout) {
16106
+ let candidates;
16107
+ try {
16108
+ candidates = await completions(words, globals);
16109
+ } catch {
16110
+ candidates = [];
16111
+ }
16112
+ if (candidates.length > 0) stdout.write(`${candidates.join("\n")}
16113
+ `);
16114
+ return ExitCode.Ok;
16115
+ }
16116
+ var COMPLETE_COMMAND, FLAG_VALUES, POSITIONAL_VALUES, sorted;
16117
+ var init_complete = __esm({
16118
+ "src/commands/completion/complete.ts"() {
16119
+ "use strict";
16120
+ init_exit_codes();
16121
+ init_output();
16122
+ init_manifest();
16123
+ init_generated_hook();
16124
+ init_registry();
16125
+ COMPLETE_COMMAND = "__complete";
16126
+ FLAG_VALUES = { output: OUTPUT_FORMATS };
16127
+ POSITIONAL_VALUES = { completion: ["bash", "zsh", "fish"] };
16128
+ sorted = (values) => [...new Set(values)].sort();
16129
+ }
16130
+ });
16131
+
15658
16132
  // src/main.ts
15659
16133
  var main_exports = {};
15660
16134
  __export(main_exports, {
15661
16135
  main: () => main
15662
16136
  });
15663
- import { realpathSync } from "node:fs";
15664
- import { pathToFileURL } from "node:url";
15665
16137
  import { parseArgs } from "node:util";
15666
16138
  function onSigint() {
15667
16139
  if (sigintCount > 0) process.exit(ExitCode.Interrupted);
@@ -15685,17 +16157,6 @@ function leaveRun(active) {
15685
16157
  graceTimer = void 0;
15686
16158
  }
15687
16159
  }
15688
- function guardClosedPipe(stream) {
15689
- if (guardedStreams.has(stream)) return;
15690
- guardedStreams.add(stream);
15691
- stream.on("error", (err) => {
15692
- if (err.code === "EPIPE") {
15693
- process.exit(ExitCode.Ok);
15694
- return;
15695
- }
15696
- throw err;
15697
- });
15698
- }
15699
16160
  function normalizeBooleans(argv, names, strict) {
15700
16161
  const out = [];
15701
16162
  for (let i = 0; i < argv.length; i++) {
@@ -15727,9 +16188,9 @@ function normalizeBooleans(argv, names, strict) {
15727
16188
  async function knownCommands() {
15728
16189
  const commands = /* @__PURE__ */ new Set();
15729
16190
  for (const [resource, area] of Object.entries(handWritten)) {
15730
- const actions18 = Object.keys(area);
15731
- if (actions18.length > 0) commands.add(resource);
15732
- for (const action of actions18) commands.add(action ? `${resource} ${action}` : resource);
16191
+ const actions20 = Object.keys(area);
16192
+ if (actions20.length > 0) commands.add(resource);
16193
+ for (const action of actions20) commands.add(action ? `${resource} ${action}` : resource);
15733
16194
  }
15734
16195
  for (const g of await listGenerated({ features: [] })) {
15735
16196
  commands.add(g.resource);
@@ -15871,16 +16332,17 @@ function commandArgs(spec, parsed2, tokens) {
15871
16332
  });
15872
16333
  }
15873
16334
  const flags = {};
15874
- for (const [flagName, flag] of Object.entries(spec.flags)) {
15875
- const value = parsed2.values[flagName];
15876
- flags[flagName] = Array.isArray(value) ? value.map(String) : value;
15877
- if (flag.required && value === void 0) throw usageError(`--${flagName} is required for ${name}.`, { field: flagName, next: `${name} --help` });
16335
+ for (const [flagName2, flag] of Object.entries(spec.flags)) {
16336
+ const value = parsed2.values[flagName2];
16337
+ flags[flagName2] = Array.isArray(value) ? value.map(String) : value;
16338
+ if (flag.required && value === void 0) throw usageError(`--${flagName2} is required for ${name}.`, { field: flagName2, next: `${name} --help` });
15878
16339
  }
15879
16340
  return { flags, positionals };
15880
16341
  }
15881
16342
  async function main(argv, env = process.env, overrides = {}) {
15882
16343
  const stdout = overrides.stdout ?? process.stdout;
15883
16344
  guardClosedPipe(stdout);
16345
+ if (argv[0] === "__complete") return (await Promise.resolve().then(() => (init_complete(), complete_exports))).printCompletions(argv.slice(1), GLOBAL_OPTIONS, stdout);
15884
16346
  let output = new Output({ stdout: overrides.stdout, stderr: overrides.stderr, stdoutIsTTY: overrides.stdoutIsTTY, stderrIsTTY: overrides.stderrIsTTY });
15885
16347
  const agent = detectAgent(env);
15886
16348
  const controller = new AbortController();
@@ -15976,28 +16438,22 @@ async function main(argv, env = process.env, overrides = {}) {
15976
16438
  return error.exitCode;
15977
16439
  }
15978
16440
  }
15979
- function invokedDirectly() {
15980
- const script = process.argv[1];
15981
- if (!script) return false;
15982
- try {
15983
- return import.meta.url === pathToFileURL(realpathSync(script)).href;
15984
- } catch {
15985
- return false;
15986
- }
15987
- }
15988
- var GLOBAL_OPTIONS, INTERRUPT_GRACE_MS, GLOBAL_BOOLEANS, COMMAND_GLOBAL_OPTIONS, COMMAND_GLOBAL_BOOLEANS, activeRuns, sigintCount, graceTimer, lookupFailed, LINGERING_REQUEST_GRACE_MS, guardedStreams, JQ_HINT;
16441
+ var GLOBAL_OPTIONS, INTERRUPT_GRACE_MS, GLOBAL_BOOLEANS, COMMAND_GLOBAL_OPTIONS, COMMAND_GLOBAL_BOOLEANS, activeRuns, sigintCount, graceTimer, lookupFailed, LINGERING_REQUEST_GRACE_MS, JQ_HINT;
15989
16442
  var init_main = __esm({
15990
16443
  "src/main.ts"() {
15991
16444
  init_generated_hook();
15992
16445
  init_help();
15993
16446
  init_registry();
15994
16447
  init_agent();
16448
+ init_closed_pipe();
15995
16449
  init_context();
15996
16450
  init_errors();
15997
16451
  init_exit_codes();
15998
16452
  init_flag_names();
16453
+ init_invoked();
15999
16454
  init_output();
16000
16455
  init_redact();
16456
+ init_update_notice();
16001
16457
  init_version();
16002
16458
  GLOBAL_OPTIONS = {
16003
16459
  profile: { type: "string" },
@@ -16022,11 +16478,12 @@ var init_main = __esm({
16022
16478
  sigintCount = 0;
16023
16479
  lookupFailed = false;
16024
16480
  LINGERING_REQUEST_GRACE_MS = 50;
16025
- guardedStreams = /* @__PURE__ */ new WeakSet();
16026
16481
  JQ_HINT = "kenso has no --jq: --query filters the output with a JMESPath expression, for example --query '[].id'.";
16027
- if (invokedDirectly()) {
16028
- void main(process.argv.slice(2)).then((code) => {
16482
+ if (invokedDirectly(import.meta.url)) {
16483
+ const updateNotice = startUpdateNotice(process.argv.slice(2));
16484
+ void main(process.argv.slice(2)).then(async (code) => {
16029
16485
  process.exitCode = code;
16486
+ if (code !== ExitCode.Interrupted) await updateNotice();
16030
16487
  if (code === ExitCode.Interrupted) setTimeout(() => process.exit(code), INTERRUPT_GRACE_MS).unref();
16031
16488
  else if (lookupFailed) setTimeout(() => process.exit(code), LINGERING_REQUEST_GRACE_MS).unref();
16032
16489
  });