kenso 0.1.73 → 0.1.75

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
@@ -375,6 +375,17 @@ function unwrap(body2) {
375
375
  function interruptedError() {
376
376
  return new KensoError({ code: "interrupted", message: "Interrupted.", exitCode: ExitCode.Interrupted });
377
377
  }
378
+ function mediaType(contentType) {
379
+ return (contentType ?? "").split(";")[0].trim().toLowerCase();
380
+ }
381
+ function isJsonContentType(contentType) {
382
+ return /^(application|text)\/([\w.-]+\+)?json$/.test(mediaType(contentType));
383
+ }
384
+ function isTextContentType(contentType) {
385
+ const media = mediaType(contentType);
386
+ if (media === "" || media.startsWith("text/") || isJsonContentType(contentType)) return true;
387
+ return /[/+]xml$/.test(media) || ["application/csv", "application/x-www-form-urlencoded", "application/javascript"].includes(media);
388
+ }
378
389
  function parseBody(text4, contentType) {
379
390
  if (text4 === "") return null;
380
391
  const looksJson = contentType?.includes("json") || /^\s*[[{]/.test(text4);
@@ -482,10 +493,10 @@ var init_http = __esm({
482
493
  const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
483
494
  const started = Date.now();
484
495
  let res;
485
- let text4;
496
+ let bytes;
486
497
  try {
487
498
  res = await this.fetchImpl(url, { method: req.method, headers, body: body2, signal });
488
- text4 = await res.text();
499
+ bytes = Buffer.from(await res.arrayBuffer());
489
500
  } catch (err) {
490
501
  if (callerSignal?.aborted) throw interruptedError();
491
502
  if (!isNetworkFailure(err)) {
@@ -512,7 +523,9 @@ var init_http = __esm({
512
523
  }
513
524
  const requestId = res.headers.get("x-request-id") ?? void 0;
514
525
  this.opts.onResponse?.({ method: req.method, url, status: res.status, ms: Date.now() - started, requestId });
515
- const parsed2 = parseBody(text4, res.headers.get("content-type"));
526
+ const contentType = res.headers.get("content-type");
527
+ const binary = res.ok && !isTextContentType(contentType);
528
+ const parsed2 = binary ? bytes.length > 0 ? bytes : null : parseBody(new TextDecoder().decode(bytes), contentType);
516
529
  if (res.status === 429) {
517
530
  const remaining = this.rateLimitBudgetMs - this.rateLimitWaitedMs;
518
531
  if (remaining <= 0) throw errorFromResponse(res.status, parsed2, requestId);
@@ -531,7 +544,9 @@ var init_http = __esm({
531
544
  continue;
532
545
  }
533
546
  if (!res.ok) throw errorFromResponse(res.status, parsed2, requestId);
534
- return { status: res.status, body: parsed2, headers: res.headers, requestId };
547
+ const response = { status: res.status, body: parsed2, headers: res.headers, requestId };
548
+ if (contentType !== null && !isJsonContentType(contentType)) response.raw = bytes;
549
+ return response;
535
550
  }
536
551
  }
537
552
  /**
@@ -2315,6 +2330,10 @@ var init_output = __esm({
2315
2330
  writeRaw(text4) {
2316
2331
  this.write(text4);
2317
2332
  }
2333
+ /** Bytes to stdout exactly as given (a downloaded file piped on). */
2334
+ writeBytes(bytes) {
2335
+ this.stdout.write(bytes);
2336
+ }
2318
2337
  info(message) {
2319
2338
  this.writeErr(`${redact(message)}
2320
2339
  `);
@@ -2458,7 +2477,7 @@ var VERSION;
2458
2477
  var init_version = __esm({
2459
2478
  "src/core/version.ts"() {
2460
2479
  "use strict";
2461
- VERSION = true ? "0.1.73" : "0.0.0-dev";
2480
+ VERSION = true ? "0.1.75" : "0.0.0-dev";
2462
2481
  }
2463
2482
  });
2464
2483
 
@@ -2835,6 +2854,154 @@ var init_secret_flags = __esm({
2835
2854
  }
2836
2855
  });
2837
2856
 
2857
+ // src/core/transfer.ts
2858
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
2859
+ import { writeFile } from "node:fs/promises";
2860
+ import { basename, extname, resolve } from "node:path";
2861
+ function contentTypeFor(name) {
2862
+ return CONTENT_TYPES[extname(name).toLowerCase()];
2863
+ }
2864
+ function readUpload(path, field) {
2865
+ if (path instanceof Blob) return { blob: path, name: field };
2866
+ const file = String(path);
2867
+ let bytes;
2868
+ try {
2869
+ bytes = readFileSync4(file);
2870
+ } catch (err) {
2871
+ throw fileUnreadable(file, err);
2872
+ }
2873
+ const type = contentTypeFor(file);
2874
+ return { blob: new Blob([bytes], type ? { type } : {}), name: basename(file) };
2875
+ }
2876
+ function formValue(value) {
2877
+ return typeof value === "string" ? value : JSON.stringify(value);
2878
+ }
2879
+ function describeForm(form, secrets = /* @__PURE__ */ new Set()) {
2880
+ const out = {};
2881
+ for (const [key, value] of form.entries()) {
2882
+ const shown = typeof value === "string" ? secrets.has(key) ? "***" : value : { file: value.name, bytes: value.size };
2883
+ const previous = out[key];
2884
+ out[key] = previous === void 0 ? shown : Array.isArray(previous) ? [...previous, shown] : [previous, shown];
2885
+ }
2886
+ return out;
2887
+ }
2888
+ function splitFileArg(value) {
2889
+ const eq = value.indexOf("=");
2890
+ if (eq > 0) {
2891
+ const field = value.slice(0, eq);
2892
+ if (FIELD_NAME.test(field) && !existsSync2(value)) return { field, path: value.slice(eq + 1) };
2893
+ }
2894
+ return { path: value };
2895
+ }
2896
+ function fileUnwritable(path, err, field = "out") {
2897
+ const code = err?.code;
2898
+ return new KensoError({
2899
+ code: "file_unwritable",
2900
+ message: `Cannot write ${path}${code ? ` (${code})` : ""}.`,
2901
+ exitCode: ExitCode.Usage,
2902
+ field,
2903
+ hint: "Check that the folder exists and that you can write to it."
2904
+ });
2905
+ }
2906
+ async function saveFile(out, bytes) {
2907
+ const path = resolve(out);
2908
+ try {
2909
+ await writeFile(path, bytes, { mode: 384 });
2910
+ } catch (err) {
2911
+ throw fileUnwritable(out, err);
2912
+ }
2913
+ return path;
2914
+ }
2915
+ function suggestedFileName(res) {
2916
+ const header = res.headers.get("content-disposition") ?? "";
2917
+ const encoded = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header)?.[1];
2918
+ let name;
2919
+ if (encoded) {
2920
+ try {
2921
+ name = decodeURIComponent(encoded.trim());
2922
+ } catch {
2923
+ name = void 0;
2924
+ }
2925
+ }
2926
+ name ??= /filename\s*=\s*"?([^";]+)"?/.exec(header)?.[1]?.trim();
2927
+ const safe = basename(name ?? "").replace(/[^\w.-]+/g, "_").replace(/^\.+/, "");
2928
+ return safe === "" ? "download" : safe;
2929
+ }
2930
+ function isBinaryResponse(res) {
2931
+ return Buffer.isBuffer(res.body) || res.raw !== void 0 && !isTextContentType(res.headers.get("content-type"));
2932
+ }
2933
+ function responseBytes(res) {
2934
+ if (res.raw !== void 0) return res.raw;
2935
+ if (res.body === null || res.body === void 0) return Buffer.alloc(0);
2936
+ return Buffer.from(typeof res.body === "string" ? res.body : `${JSON.stringify(res.body)}
2937
+ `, "utf8");
2938
+ }
2939
+ async function writeFileResponse(ctx, res, opts = {}) {
2940
+ const bytes = responseBytes(res);
2941
+ const contentType = res.headers.get("content-type") ?? void 0;
2942
+ if (opts.out !== void 0) {
2943
+ const path = await saveFile(opts.out, bytes);
2944
+ ctx.output.object({ out: path, bytes: bytes.length, ...contentType ? { contentType } : {} });
2945
+ return;
2946
+ }
2947
+ if (bytes.length === 0) return;
2948
+ if (!isBinaryResponse(res)) {
2949
+ ctx.output.writeRaw(bytes.toString("utf8"));
2950
+ return;
2951
+ }
2952
+ if (ctx.output.stdoutIsTTY) {
2953
+ throw new KensoError({
2954
+ code: "binary_output",
2955
+ message: `The answer is a ${contentType ?? "binary"} file of ${bytes.length} bytes, which is not printed to a terminal.`,
2956
+ exitCode: ExitCode.Usage,
2957
+ field: "out",
2958
+ hint: "Save it with --out <path>, or redirect stdout to a file.",
2959
+ ...opts.next ? { next: opts.next } : {}
2960
+ });
2961
+ }
2962
+ ctx.output.writeBytes(bytes);
2963
+ }
2964
+ var CONTENT_TYPES, FIELD_NAME;
2965
+ var init_transfer = __esm({
2966
+ "src/core/transfer.ts"() {
2967
+ "use strict";
2968
+ init_errors();
2969
+ init_exit_codes();
2970
+ init_http();
2971
+ init_input();
2972
+ CONTENT_TYPES = {
2973
+ ".png": "image/png",
2974
+ ".jpg": "image/jpeg",
2975
+ ".jpeg": "image/jpeg",
2976
+ ".webp": "image/webp",
2977
+ ".gif": "image/gif",
2978
+ ".svg": "image/svg+xml",
2979
+ ".ico": "image/x-icon",
2980
+ ".csv": "text/csv",
2981
+ ".txt": "text/plain",
2982
+ ".md": "text/markdown",
2983
+ ".vtt": "text/vtt",
2984
+ ".srt": "application/x-subrip",
2985
+ ".html": "text/html",
2986
+ ".json": "application/json",
2987
+ ".pdf": "application/pdf",
2988
+ ".zip": "application/zip",
2989
+ ".skill": "application/zip",
2990
+ ".doc": "application/msword",
2991
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2992
+ ".xls": "application/vnd.ms-excel",
2993
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2994
+ ".ppt": "application/vnd.ms-powerpoint",
2995
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2996
+ ".mp3": "audio/mpeg",
2997
+ ".wav": "audio/wav",
2998
+ ".m4a": "audio/mp4",
2999
+ ".mp4": "video/mp4"
3000
+ };
3001
+ FIELD_NAME = /^[A-Za-z_][\w.[\]-]*$/;
3002
+ }
3003
+ });
3004
+
2838
3005
  // src/core/sse.ts
2839
3006
  var SseParser;
2840
3007
  var init_sse = __esm({
@@ -3126,9 +3293,9 @@ var init_get = __esm({
3126
3293
  if (string.charCodeAt(0) === charCodeOfDot) {
3127
3294
  result.push("");
3128
3295
  }
3129
- string.replace(rePropName, function(match, expression, quote3, subString) {
3296
+ string.replace(rePropName, function(match, expression, quote4, subString) {
3130
3297
  let key = match;
3131
- if (quote3) {
3298
+ if (quote4) {
3132
3299
  key = subString.replace(reEscapeChar, "$1");
3133
3300
  } else if (expression) {
3134
3301
  key = expression.trim();
@@ -3621,7 +3788,7 @@ var init_api = __esm({
3621
3788
  const {
3622
3789
  delimiter: delimiter3,
3623
3790
  escape,
3624
- quote: quote3,
3791
+ quote: quote4,
3625
3792
  quoted,
3626
3793
  quoted_empty,
3627
3794
  quoted_string,
@@ -3634,7 +3801,7 @@ var init_api = __esm({
3634
3801
  const quotedMatch = matches_quoted_match(value, quoted_match);
3635
3802
  const shouldQuote = quotedMatch || true === quoted_empty || true === quoted_string && false !== quoted_empty;
3636
3803
  if (shouldQuote === true) {
3637
- value = quote3 + value + quote3;
3804
+ value = quote4 + value + quote4;
3638
3805
  }
3639
3806
  csvrecord += value;
3640
3807
  } else if (value) {
@@ -3646,8 +3813,8 @@ var init_api = __esm({
3646
3813
  ];
3647
3814
  }
3648
3815
  const containsdelimiter = emits_separator(value, [delimiter3]);
3649
- const containsQuote = quote3 !== "" && value.indexOf(quote3) >= 0;
3650
- const containsEscape = value.indexOf(escape) >= 0 && escape !== quote3;
3816
+ const containsQuote = quote4 !== "" && value.indexOf(quote4) >= 0;
3817
+ const containsEscape = value.indexOf(escape) >= 0 && escape !== quote4;
3651
3818
  const containsRecordDelimiter = emits_separator(value, [
3652
3819
  record_delimiter,
3653
3820
  ...quote_record_delimiter === false ? [] : ["\n", "\r"]
@@ -3683,14 +3850,14 @@ var init_api = __esm({
3683
3850
  value = value.replaceAll(escape, () => escape + escape);
3684
3851
  }
3685
3852
  if (containsQuote === true) {
3686
- value = value.replaceAll(quote3, () => escape + quote3);
3853
+ value = value.replaceAll(quote4, () => escape + quote4);
3687
3854
  }
3688
3855
  if (shouldQuote === true) {
3689
- value = quote3 + value + quote3;
3856
+ value = quote4 + value + quote4;
3690
3857
  }
3691
3858
  csvrecord += value;
3692
3859
  } else if (quoted_empty === true || field === "" && quoted_string === true && quoted_empty !== false) {
3693
- csvrecord += quote3 + quote3;
3860
+ csvrecord += quote4 + quote4;
3694
3861
  }
3695
3862
  if (i !== record.length - 1) {
3696
3863
  csvrecord += delimiter3;
@@ -3795,7 +3962,7 @@ var init_sync = __esm({
3795
3962
 
3796
3963
  // src/batch/results.ts
3797
3964
  import { createHash } from "node:crypto";
3798
- import { readFileSync as readFileSync4 } from "node:fs";
3965
+ import { readFileSync as readFileSync5 } from "node:fs";
3799
3966
  import { readFile as readFile3 } from "node:fs/promises";
3800
3967
  import { join as join3 } from "node:path";
3801
3968
  function filesOf(dir) {
@@ -3862,7 +4029,7 @@ async function readResults(path) {
3862
4029
  }
3863
4030
  function readSummary(path) {
3864
4031
  try {
3865
- const value = JSON.parse(readFileSync4(path, "utf8"));
4032
+ const value = JSON.parse(readFileSync5(path, "utf8"));
3866
4033
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3867
4034
  } catch {
3868
4035
  return void 0;
@@ -3924,11 +4091,11 @@ var init_results = __esm({
3924
4091
  // src/batch/runs.ts
3925
4092
  import { randomBytes } from "node:crypto";
3926
4093
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync2 } from "node:fs";
3927
- import { readdir, readFile as readFile4, realpath, rename, unlink, writeFile } from "node:fs/promises";
3928
- import { join as join4, resolve } from "node:path";
4094
+ import { readdir, readFile as readFile4, realpath, rename, unlink, writeFile as writeFile2 } from "node:fs/promises";
4095
+ import { join as join4, resolve as resolve2 } from "node:path";
3929
4096
  function runsRoot(env = process.env) {
3930
4097
  const override2 = env.KENSO_RUNS_DIR?.trim();
3931
- return resolve(override2 ? override2 : join4(configDir(env), "runs"));
4098
+ return resolve2(override2 ? override2 : join4(configDir(env), "runs"));
3932
4099
  }
3933
4100
  function newRunId() {
3934
4101
  const bytes = randomBytes(5);
@@ -3974,7 +4141,7 @@ function ensurePrivateDir2(dir) {
3974
4141
  async function writeFileAtomic(path, content) {
3975
4142
  const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
3976
4143
  try {
3977
- await writeFile(temp, content, { mode: 384 });
4144
+ await writeFile2(temp, content, { mode: 384 });
3978
4145
  await rename(temp, path);
3979
4146
  } catch (err) {
3980
4147
  await unlink(temp).catch(() => void 0);
@@ -4007,9 +4174,9 @@ async function readRunDir(dir) {
4007
4174
  return null;
4008
4175
  }
4009
4176
  if (!raw) return null;
4010
- const { runId, command: command48, createdAt, status } = raw;
4177
+ const { runId, command: command49, createdAt, status } = raw;
4011
4178
  if (typeof runId !== "string" || !RUN_ID_PATTERN.test(runId)) return null;
4012
- if (typeof command48 !== "string" || typeof createdAt !== "string") return null;
4179
+ if (typeof command49 !== "string" || typeof createdAt !== "string") return null;
4013
4180
  if (typeof status !== "string" || !STATUSES.includes(status)) return null;
4014
4181
  let chunksDone = chunkList(raw.chunksDone) ?? [];
4015
4182
  try {
@@ -4020,7 +4187,7 @@ async function readRunDir(dir) {
4020
4187
  const record = {
4021
4188
  ...raw,
4022
4189
  runId,
4023
- command: command48,
4190
+ command: command49,
4024
4191
  args: asRecord3(raw.args) ?? {},
4025
4192
  createdAt,
4026
4193
  status,
@@ -4075,11 +4242,11 @@ async function loadRun(runId, env = process.env) {
4075
4242
  }
4076
4243
  return run;
4077
4244
  }
4078
- async function findIdentical(command48, args, inputSha256, env, workspaceId, anyWorkspace = false) {
4245
+ async function findIdentical(command49, args, inputSha256, env, workspaceId, anyWorkspace = false) {
4079
4246
  const identity = argsIdentity(args);
4080
4247
  const runs = await listRuns(env);
4081
4248
  return runs.filter(
4082
- (run) => run.command === command48 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
4249
+ (run) => run.command === command49 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
4083
4250
  );
4084
4251
  }
4085
4252
  function isOtherLiveProcess(pid) {
@@ -4106,9 +4273,9 @@ var init_runs = __esm({
4106
4273
  });
4107
4274
 
4108
4275
  // src/batch/run-dir.ts
4109
- import { existsSync as existsSync2 } from "node:fs";
4276
+ import { existsSync as existsSync3 } from "node:fs";
4110
4277
  import { symlink, unlink as unlink2 } from "node:fs/promises";
4111
- import { join as join5, resolve as resolve2 } from "node:path";
4278
+ import { join as join5, resolve as resolve3 } from "node:path";
4112
4279
  async function prepareRunDir(outDir, runId, identical, ctx) {
4113
4280
  const root2 = runsRoot(ctx.env);
4114
4281
  if (outDir === void 0) {
@@ -4117,8 +4284,8 @@ async function prepareRunDir(outDir, runId, identical, ctx) {
4117
4284
  ensurePrivateDir2(dir2);
4118
4285
  return dir2;
4119
4286
  }
4120
- const dir = resolve2(outDir);
4121
- const existing = existsSync2(join5(dir, "run.json")) ? await readRunDir(dir) : null;
4287
+ const dir = resolve3(outDir);
4288
+ const existing = existsSync3(join5(dir, "run.json")) ? await readRunDir(dir) : null;
4122
4289
  if (existing && !identical.some((run) => run.runId === existing.runId)) {
4123
4290
  throw usageError(`${dir} already holds run ${existing.runId} (${existing.command}).`, {
4124
4291
  field: "out",
@@ -5502,7 +5669,7 @@ var init_api2 = __esm({
5502
5669
  state: init_state(options),
5503
5670
  __needMoreData: function(i, bufLen, end) {
5504
5671
  if (end) return false;
5505
- const { encoding, escape, quote: quote3 } = this.options;
5672
+ const { encoding, escape, quote: quote4 } = this.options;
5506
5673
  const { quoting, needMoreDataSize, recordDelimiterMaxLength } = this.state;
5507
5674
  const numOfCharLeft = bufLen - i - 1;
5508
5675
  const requiredLength = Math.max(
@@ -5515,9 +5682,9 @@ var init_api2 = __esm({
5515
5682
  // recordDelimiterMaxLength,
5516
5683
  recordDelimiterMaxLength === 0 ? Buffer.from("\r\n", encoding).length : recordDelimiterMaxLength,
5517
5684
  // Skip if remaining buffer can be an escaped quote
5518
- quoting ? (escape === null ? 0 : escape.length) + quote3.length : 0,
5685
+ quoting ? (escape === null ? 0 : escape.length) + quote4.length : 0,
5519
5686
  // Skip if remaining buffer can be record delimiter following the closing quote
5520
- quoting ? quote3.length + recordDelimiterMaxLength : 0
5687
+ quoting ? quote4.length + recordDelimiterMaxLength : 0
5521
5688
  );
5522
5689
  return numOfCharLeft < requiredLength;
5523
5690
  },
@@ -5538,7 +5705,7 @@ var init_api2 = __esm({
5538
5705
  to,
5539
5706
  to_line
5540
5707
  } = this.options;
5541
- let { comment, escape, quote: quote3, record_delimiter } = this.options;
5708
+ let { comment, escape, quote: quote4, record_delimiter } = this.options;
5542
5709
  const {
5543
5710
  bomSkipped,
5544
5711
  delimiterDiscovered,
@@ -5605,7 +5772,7 @@ var init_api2 = __esm({
5605
5772
  for (const key in options2) {
5606
5773
  this.options[key] = options2[key];
5607
5774
  }
5608
- ({ comment, escape, quote: quote3 } = this.options);
5775
+ ({ comment, escape, quote: quote4 } = this.options);
5609
5776
  break;
5610
5777
  }
5611
5778
  }
@@ -5661,21 +5828,21 @@ var init_api2 = __esm({
5661
5828
  }
5662
5829
  if (this.state.commenting === false && this.__isQuote(buf, pos)) {
5663
5830
  if (this.state.quoting === true) {
5664
- const nextChr = buf[pos + quote3.length];
5665
- const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos + quote3.length);
5666
- const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote3.length, nextChr);
5831
+ const nextChr = buf[pos + quote4.length];
5832
+ const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos + quote4.length);
5833
+ const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote4.length, nextChr);
5667
5834
  const isNextChrDelimiter = this.__isDelimiter(
5668
5835
  buf,
5669
- pos + quote3.length,
5836
+ pos + quote4.length,
5670
5837
  nextChr
5671
5838
  );
5672
- const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote3.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote3.length);
5839
+ const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote4.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote4.length);
5673
5840
  if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) {
5674
5841
  pos += escape.length - 1;
5675
5842
  } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) {
5676
5843
  this.state.quoting = false;
5677
5844
  this.state.wasQuoting = true;
5678
- pos += quote3.length - 1;
5845
+ pos += quote4.length - 1;
5679
5846
  continue;
5680
5847
  } else if (relax_quotes === false) {
5681
5848
  const err = this.__error(
@@ -5696,8 +5863,8 @@ var init_api2 = __esm({
5696
5863
  } else {
5697
5864
  this.state.quoting = false;
5698
5865
  this.state.wasQuoting = true;
5699
- this.state.field.prepend(quote3);
5700
- pos += quote3.length - 1;
5866
+ this.state.field.prepend(quote4);
5867
+ pos += quote4.length - 1;
5701
5868
  }
5702
5869
  } else {
5703
5870
  if (this.state.field.length !== 0) {
@@ -5725,7 +5892,7 @@ var init_api2 = __esm({
5725
5892
  }
5726
5893
  } else {
5727
5894
  this.state.quoting = true;
5728
- pos += quote3.length - 1;
5895
+ pos += quote4.length - 1;
5729
5896
  continue;
5730
5897
  }
5731
5898
  }
@@ -6175,11 +6342,11 @@ var init_api2 = __esm({
6175
6342
  // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
6176
6343
  // }
6177
6344
  __isQuote: function(buf, pos) {
6178
- const { quote: quote3 } = this.options;
6179
- if (quote3 === null) return false;
6180
- const l = quote3.length;
6345
+ const { quote: quote4 } = this.options;
6346
+ if (quote4 === null) return false;
6347
+ const l = quote4.length;
6181
6348
  for (let i = 0; i < l; i++) {
6182
- if (quote3[i] !== buf[pos + i]) {
6349
+ if (quote4[i] !== buf[pos + i]) {
6183
6350
  return false;
6184
6351
  }
6185
6352
  }
@@ -6307,7 +6474,7 @@ var init_sync2 = __esm({
6307
6474
  // src/batch/input.ts
6308
6475
  import { createHash as createHash2 } from "node:crypto";
6309
6476
  import { readFile as readFile5, stat } from "node:fs/promises";
6310
- import { extname, resolve as resolve3 } from "node:path";
6477
+ import { extname as extname2, resolve as resolve4 } from "node:path";
6311
6478
  function tooLarge(source) {
6312
6479
  return usageError(`${source} is larger than 200 MB, the most the CLI reads in one run.`, {
6313
6480
  field: "file",
@@ -6328,7 +6495,7 @@ async function readStdinBytes(stdin) {
6328
6495
  async function readRaw(pathOrDash, stdin) {
6329
6496
  if (pathOrDash === "-") return { path: "-", bytes: await readStdinBytes(stdin ?? process.stdin) };
6330
6497
  if (pathOrDash.trim() === "") throw usageError("Name an input file, or - for stdin.", { field: "file" });
6331
- const path = resolve3(pathOrDash);
6498
+ const path = resolve4(pathOrDash);
6332
6499
  try {
6333
6500
  const info = await stat(path);
6334
6501
  if (info.isDirectory()) throw fileUnreadable(pathOrDash, { code: "EISDIR" });
@@ -6343,7 +6510,7 @@ function stripBom(text4) {
6343
6510
  return text4.charCodeAt(0) === 65279 ? text4.slice(1) : text4;
6344
6511
  }
6345
6512
  function detectFormat(path, text4) {
6346
- const ext = path === "-" ? "" : extname(path).toLowerCase();
6513
+ const ext = path === "-" ? "" : extname2(path).toLowerCase();
6347
6514
  if (ext === ".csv") return "csv";
6348
6515
  if (ext === ".jsonl" || ext === ".ndjson") return "jsonl";
6349
6516
  return stripBom(text4).trimStart().startsWith("{") ? "jsonl" : "csv";
@@ -6431,7 +6598,7 @@ async function readIds(pathOrDash, opts) {
6431
6598
  const text4 = bytes.toString("utf8");
6432
6599
  const source = path === "-" ? "stdin" : pathOrDash;
6433
6600
  const column = opts?.column?.trim() || void 0;
6434
- const ext = path === "-" ? "" : extname(path).toLowerCase();
6601
+ const ext = path === "-" ? "" : extname2(path).toLowerCase();
6435
6602
  let format;
6436
6603
  if (ext === ".csv" || ext === ".jsonl" || ext === ".ndjson") format = detectFormat(path, text4);
6437
6604
  else if (stripBom(text4).trimStart().startsWith("{")) format = "jsonl";
@@ -6672,8 +6839,6 @@ __export(execute_exports, {
6672
6839
  operationToCommand: () => operationToCommand,
6673
6840
  secretParams: () => secretParams
6674
6841
  });
6675
- import { readFileSync as readFileSync5 } from "node:fs";
6676
- import { basename } from "node:path";
6677
6842
  function isRecord3(value) {
6678
6843
  return value !== null && typeof value === "object" && !Array.isArray(value);
6679
6844
  }
@@ -6683,13 +6848,21 @@ function commandOf(op) {
6683
6848
  function isDestructive(op) {
6684
6849
  return op.method === "DELETE" || /(^|-)(delete|archive|remove)(-|$)/.test(op.action);
6685
6850
  }
6686
- function fileProp(op) {
6687
- return op.body?.format === "multipart" ? op.body.props.find((p) => p.flag === "file") : void 0;
6851
+ function fileProps(op) {
6852
+ return op.body?.format === "multipart" ? op.body.props.filter((p) => p.flag === "file") : [];
6853
+ }
6854
+ function fileFlagText(op, files) {
6855
+ const first = files[0];
6856
+ const many = first.type === "array" ? "; repeat for more files" : "";
6857
+ const named = files.length > 1 ? ` Name another file field with <field>=<path> (${files.map((f) => f.name).join(", ")}).` : "";
6858
+ const json = op.body?.json ? " Without --file the body is JSON." : "";
6859
+ return `Path of the file to upload, sent as form field ${first.name}${many}.${named}${json}`;
6688
6860
  }
6689
6861
  function describeParam(param, location, list2) {
6690
6862
  const fallback = list2 && location === "query" && LIST_PARAM_TEXT[param.name] || `${param.name} (${location === "route" ? "path" : location}, ${param.type})`;
6691
6863
  const base = param.description?.replace(/\s*\n\s*/g, " ") ?? fallback;
6692
- return param.enum ? `${base} One of: ${param.enum.join(", ")}.` : base;
6864
+ const text4 = param.enum ? `${base} One of: ${param.enum.join(", ")}.` : base;
6865
+ return param.jsonOnly ? `${text4} JSON body only: not with --file.` : text4;
6693
6866
  }
6694
6867
  function operationFlags(op) {
6695
6868
  const flags = [];
@@ -6707,15 +6880,16 @@ function operationFlags(op) {
6707
6880
  };
6708
6881
  for (const param of op.routeParams) add(param, "route", true);
6709
6882
  for (const param of op.queryParams) add(param, "query", param.required);
6710
- const file = fileProp(op);
6883
+ const files = fileProps(op);
6711
6884
  for (const prop of op.body?.props ?? []) {
6712
- if (prop === file) {
6885
+ if (prop.flag === "file" && files.length > 0) {
6886
+ if (prop !== files[0]) continue;
6713
6887
  flags.push({
6714
6888
  flag: "file",
6715
6889
  type: "file",
6716
6890
  required: prop.required,
6717
- description: `Path of the file to upload (${prop.name})${prop.type === "array" ? "; repeat for more files" : ""}.`,
6718
- ...prop.type === "array" ? { multiple: true } : {},
6891
+ description: fileFlagText(op, files),
6892
+ ...prop.type === "array" || files.length > 1 ? { multiple: true } : {},
6719
6893
  param: prop,
6720
6894
  location: "body"
6721
6895
  });
@@ -6737,6 +6911,14 @@ function operationFlags(op) {
6737
6911
  description: op.idempotencyKey.required ? "Idempotency-Key, required: a unique value. Run the command again with the same key to retry it safely." : "Idempotency-Key: a unique value. Run the command again with the same key to retry it safely. Without it no key is sent."
6738
6912
  });
6739
6913
  }
6914
+ if (op.download) {
6915
+ flags.push({
6916
+ flag: OUT_FLAG,
6917
+ type: "string",
6918
+ required: false,
6919
+ description: `Save the answer (${op.download.contentTypes.join(" or ")}) to this file, byte for byte, and print a summary.`
6920
+ });
6921
+ }
6740
6922
  if (op.body) {
6741
6923
  flags.push({
6742
6924
  flag: "data",
@@ -6776,7 +6958,8 @@ function usageLine(op) {
6776
6958
  function operationExamples(op) {
6777
6959
  const required = operationFlags(op).filter((f) => f.required && f.flag !== "file").map(flagUsage);
6778
6960
  const base = [commandOf(op), ...required].join(" ");
6779
- const first = op.body?.format === "multipart" ? `${base} --file ./file.csv` : base;
6961
+ const upload2 = op.body?.format === "multipart" ? `${base} --file ./file.csv` : base;
6962
+ const first = op.download ? `${upload2} --out ./${op.download.contentTypes.some((t) => t.includes("csv")) ? "export.csv" : "download"}` : upload2;
6780
6963
  const examples = op.method === "GET" ? [first] : [`${first} --dry-run`, isDestructive(op) ? `${first} --yes` : first];
6781
6964
  if (op.body && op.body.format !== "multipart") examples.push(`${base} --data @body.json`);
6782
6965
  if (op.list) examples.push(`${base} --all`);
@@ -6801,18 +6984,6 @@ function parseNumber(raw, flag, integer) {
6801
6984
  function isBlank(value) {
6802
6985
  return value === void 0 || value === null || value === "";
6803
6986
  }
6804
- function readUpload(path, field) {
6805
- if (path instanceof Blob) return { blob: path, name: field };
6806
- const file = String(path);
6807
- try {
6808
- return { blob: new Blob([readFileSync5(file)]), name: basename(file) };
6809
- } catch (err) {
6810
- throw fileUnreadable(file, err);
6811
- }
6812
- }
6813
- function formValue(value) {
6814
- return typeof value === "string" ? value : JSON.stringify(value);
6815
- }
6816
6987
  function buildRequest(op, values) {
6817
6988
  const routeNames = new Set(op.routeParams.map((p) => p.name));
6818
6989
  const queryNames = new Set(op.queryParams.map((p) => p.name));
@@ -6852,18 +7023,28 @@ function buildRequest(op, values) {
6852
7023
  if (key === DATA_KEY || key === IDEMPOTENCY_KEY || routeNames.has(key) || queryNames.has(key) || value === void 0) continue;
6853
7024
  body2[key] = value;
6854
7025
  }
6855
- if (op.body.format === "multipart") {
6856
- const file = fileProp(op);
6857
- if (file?.required && isBlank(body2[file.name])) throw missing(op, "file");
7026
+ const files = fileProps(op);
7027
+ const fileNames = new Set(files.map((p) => p.name));
7028
+ const sendForm = op.body.format === "multipart" && !(op.body.json === true && files.every((p) => isBlank(body2[p.name])));
7029
+ if (sendForm) {
7030
+ if (files[0]?.required && isBlank(body2[files[0].name])) throw missing(op, "file");
7031
+ const jsonOnly = op.body.props.find((p) => p.jsonOnly === true && !isBlank(body2[p.name]));
7032
+ if (jsonOnly) {
7033
+ throw usageError(`--${jsonOnly.flag} goes in the JSON body, which ${commandOf(op)} sends only without --file.`, {
7034
+ field: jsonOnly.flag,
7035
+ hint: `Send either --file or --${jsonOnly.flag}, not both.`
7036
+ });
7037
+ }
6858
7038
  const form = new FormData();
7039
+ const formTypes = new Map(op.body.props.map((p) => [p.name, p.type]));
6859
7040
  for (const [key, value] of Object.entries(body2)) {
6860
7041
  if (value === void 0 || value === null) continue;
6861
- if (file && key === file.name) {
7042
+ if (fileNames.has(key)) {
6862
7043
  for (const path2 of Array.isArray(value) ? value : [value]) {
6863
7044
  const upload2 = readUpload(path2, key);
6864
7045
  form.append(key, upload2.blob, upload2.name);
6865
7046
  }
6866
- } else if (Array.isArray(value)) {
7047
+ } else if (Array.isArray(value) && (formTypes.get(key) ?? "array") === "array") {
6867
7048
  for (const item of value) form.append(key, formValue(item));
6868
7049
  } else {
6869
7050
  form.append(key, formValue(value));
@@ -6882,6 +7063,28 @@ function buildRequest(op, values) {
6882
7063
  request.body = body2;
6883
7064
  return request;
6884
7065
  }
7066
+ function fileValues(op, raw) {
7067
+ const files = fileProps(op);
7068
+ const byField = /* @__PURE__ */ new Map();
7069
+ for (const item of Array.isArray(raw) ? raw : [String(raw)]) {
7070
+ const { field, path } = splitFileArg(item);
7071
+ const prop = field === void 0 ? files[0] : files.find((p) => p.name.toLowerCase() === field.toLowerCase());
7072
+ if (!prop) {
7073
+ throw usageError(`${commandOf(op)} has no file field "${field}".`, {
7074
+ field: "file",
7075
+ hint: `Its file field${files.length > 1 ? "s are" : " is"} ${files.map((p) => p.name).join(", ")}. A path with = in it reads as a path when it starts with ./ (./${item}).`
7076
+ });
7077
+ }
7078
+ if (path === "") throw usageError(`--file ${item} names no file.`, { field: "file" });
7079
+ byField.set(prop, [...byField.get(prop) ?? [], path]);
7080
+ }
7081
+ const values = {};
7082
+ for (const [prop, paths] of byField) {
7083
+ if (prop.type !== "array" && paths.length > 1) throw usageError(`--file takes one file for ${prop.name} (got ${paths.length}).`, { field: "file" });
7084
+ values[prop.name] = prop.type === "array" ? paths : paths[0];
7085
+ }
7086
+ return values;
7087
+ }
6885
7088
  async function collectValues(ctx, op, flags) {
6886
7089
  const values = {};
6887
7090
  const bodyOnly = {};
@@ -6897,7 +7100,8 @@ async function collectValues(ctx, op, flags) {
6897
7100
  } else if (raw === void 0) {
6898
7101
  continue;
6899
7102
  } else if (f.type === "file") {
6900
- value = raw;
7103
+ Object.assign(values, fileValues(op, raw));
7104
+ continue;
6901
7105
  } else if (f.type === "array") {
6902
7106
  value = (Array.isArray(raw) ? raw : [String(raw)]).flatMap((item) => item.split(",")).map((item) => item.trim()).filter((item) => item !== "");
6903
7107
  } else if (f.type === "integer" || f.type === "number") {
@@ -6959,15 +7163,7 @@ function describeRequest(req, op) {
6959
7163
  const out = { method: req.method, path: req.path };
6960
7164
  if (req.query) out.query = req.query;
6961
7165
  if (req.body !== void 0) out.body = maskSecrets(req.body, secrets);
6962
- if (req.form) {
6963
- const form = {};
6964
- for (const [key, value] of req.form.entries()) {
6965
- const shown = typeof value === "string" ? secrets.has(key) ? "***" : value : { file: value.name, bytes: value.size };
6966
- const previous = form[key];
6967
- form[key] = previous === void 0 ? shown : Array.isArray(previous) ? [...previous, shown] : [previous, shown];
6968
- }
6969
- out.form = form;
6970
- }
7166
+ if (req.form) out.form = describeForm(req.form, secrets);
6971
7167
  return out;
6972
7168
  }
6973
7169
  function eachConcurrency(raw) {
@@ -6985,6 +7181,10 @@ async function runOperation(ctx, op, flags) {
6985
7181
  const secrets = secretParams(op);
6986
7182
  checkSecretSources(flags, secrets.map((s) => s.flag));
6987
7183
  const values = await collectValues(ctx, op, flags);
7184
+ const out = typeof flags[OUT_FLAG] === "string" ? flags[OUT_FLAG] : void 0;
7185
+ if (out !== void 0 && typeof flags.each === "string") {
7186
+ throw usageError("--out names one file, so it cannot take an answer per --each row.", { field: OUT_FLAG });
7187
+ }
6988
7188
  const stream = op.stream === "sse" ? streamOptions(flags) : void 0;
6989
7189
  if (typeof flags.each === "string") {
6990
7190
  const { runEach: runEach2 } = await Promise.resolve().then(() => (init_each(), each_exports));
@@ -7007,6 +7207,11 @@ async function runOperation(ctx, op, flags) {
7007
7207
  return ExitCode.Ok;
7008
7208
  }
7009
7209
  const res = await ctx.client.request(req);
7210
+ if (out !== void 0 || res.raw !== void 0 && (op.download !== void 0 || isBinaryResponse(res))) {
7211
+ const next = op.download ? `${sameCommand(ctx, op, flags)} --out ${shellQuote2(suggestedFileName(res))}` : void 0;
7212
+ await writeFileResponse(ctx, res, { out, ...next ? { next } : {} });
7213
+ return ExitCode.Ok;
7214
+ }
7010
7215
  if (res.status === 204 || res.body === null || res.body === "") return ExitCode.Ok;
7011
7216
  if (op.list && isRecord3(res.body) && Array.isArray(res.body.data)) {
7012
7217
  if (res.body.counts !== void 0) {
@@ -7102,7 +7307,7 @@ ${api}` : api,
7102
7307
  run: (ctx, args) => runOperation(ctx, op, args.flags)
7103
7308
  };
7104
7309
  }
7105
- var STREAM_HELP, DATA_KEY, IDEMPOTENCY_KEY, IDEMPOTENCY_KEY_FLAG, SCALAR_TYPES, FLAG_ALIASES, LIST_PARAM_TEXT, HELP_NOTES_MAX, HELP_FLAG_MAX, FOOTER_FLAGS;
7310
+ var STREAM_HELP, DATA_KEY, IDEMPOTENCY_KEY, IDEMPOTENCY_KEY_FLAG, SCALAR_TYPES, FLAG_ALIASES, OUT_FLAG, LIST_PARAM_TEXT, HELP_NOTES_MAX, HELP_FLAG_MAX, FOOTER_FLAGS;
7106
7311
  var init_execute = __esm({
7107
7312
  "src/generated/execute.ts"() {
7108
7313
  "use strict";
@@ -7112,6 +7317,7 @@ var init_execute = __esm({
7112
7317
  init_http();
7113
7318
  init_input();
7114
7319
  init_secret_flags();
7320
+ init_transfer();
7115
7321
  init_stream();
7116
7322
  STREAM_HELP = "A live stream: it prints one JSON line per event ({event, id, data}) as it arrives and runs until Ctrl-C, reconnecting when the server closes it (with Last-Event-ID once events carry an id). --until <event> ends after that event, --max-events <n> after n events, --once when the server closes it.";
7117
7323
  DATA_KEY = "$data";
@@ -7126,6 +7332,7 @@ var init_execute = __esm({
7126
7332
  ["opportunity", "opportunity-id"],
7127
7333
  ["q", "search"]
7128
7334
  ];
7335
+ OUT_FLAG = "out";
7129
7336
  LIST_PARAM_TEXT = {
7130
7337
  limit: "Page size.",
7131
7338
  cursor: "Start at this cursor (the next: hint of a previous page)."
@@ -7244,8 +7451,8 @@ function idValue(value, field) {
7244
7451
  function shellQuote3(arg) {
7245
7452
  return /^[A-Za-z0-9_./:=@%+,-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
7246
7453
  }
7247
- function commandLine2(ctx, command48, args, extra = []) {
7248
- const parts2 = ["kenso", ...command48.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
7454
+ function commandLine2(ctx, command49, args, extra = []) {
7455
+ const parts2 = ["kenso", ...command49.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
7249
7456
  for (const [name, value] of Object.entries(args.flags)) {
7250
7457
  if (value === void 0 || value === false) continue;
7251
7458
  if (value === true) parts2.push(`--${name}`);
@@ -7585,7 +7792,7 @@ var init_crm = __esm({
7585
7792
  var leads_default;
7586
7793
  var init_leads = __esm({
7587
7794
  "docs/leads.md"() {
7588
- leads_default = '# Leads\n\nLeads are contacts in a campaign. The lead commands live under `kenso contacts`, and `kenso leads` is the same thing: `kenso leads import` runs `kenso contacts import`.\n\n| Command | What it does |\n|---|---|\n| `contacts import` | Add leads from a CSV or JSONL file to a campaign, with one result per row |\n| `contacts update` | Edit leads in bulk from a file, matched by id or by email |\n| `contacts remove` / `restore` | Remove (soft-delete) leads by id, and undo it |\n| `contacts pause` / `resume` | Pause and resume the campaign sequence of leads (pause is beta, `pause_leads` flag) |\n| `contacts tag` / `untag` | Add or remove a tag on leads by id |\n| `contacts export` | Download a campaign\'s leads as one CSV file |\n\nAll of them except `export` are batch commands: without `--yes` they print a plan and change nothing. [Batch runs](batch.md) explains plans, run folders, results files and resume.\n\n## Import a CSV into a campaign\n\n```bash\nkenso contacts import --template\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`--template` prints the accepted columns. A minimal file:\n\n```csv\nemail,firstName,lastName,companyName,Pain Point\nann@acme.io,Ann,Lee,Acme,Slow onboarding\ncid@globex.com,Cid,Moe,Globex,Churn\n```\n\n### Columns\n\nHeaders are matched without regard to case, spaces or punctuation. The known fields and the other headers each one reads:\n\n| Field | Also read from | Rule |\n|---|---|---|\n| `email` | email address, e-mail, work email | Required, unless the campaign is LinkedIn-only and the row has a linkedin.com/in/ URL |\n| `firstName` | first name, first, given name | Required |\n| `lastName` | last name, last, surname, family name | Required |\n| `title` | job title, position, role | Optional |\n| `linkedInUrl` | linkedin, linkedin url, linkedin profile, profile url | Optional |\n| `companyName` | company, organization, account, account name | `companyName` or `companyDomain` is required |\n| `companyDomain` | website, domain, company website, url | `companyName` or `companyDomain` is required |\n\nEvery other column becomes a custom variable, named like its header in snake_case: a `Pain Point` column fills `{{pain_point}}` in your sequence. Names Kenso keeps for its own fields (`city`, `country`, `phone_number` and others) are not sent: the CLI warns and the plan lists them under `droppedColumns`. Rename them with `--map`.\n\n### Cells\n\n- A blank cell is never sent, so importing a file never erases data on a lead that is already in the campaign.\n- The literal value `null` clears a custom variable.\n\n### Rename or drop columns with --map\n\n`--map` takes a JSON object, `@file` or `-` for stdin. A value names the target field, and `null` drops the column:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --map \'{"Pain": "customVariables.pain_point", "Notes": null}\' --yes\n```\n\n### JSONL\n\nEach line is one lead. Keys work like CSV headers, and a `customVariables` object is spread into custom variables:\n\n```json\n{"email":"ann@acme.io","firstName":"Ann","lastName":"Lee","companyName":"Acme","customVariables":{"pain_point":"Slow onboarding"}}\n```\n\n```bash\nkenso contacts import --campaign 812 --file leads.jsonl --yes\ncat leads.jsonl | kenso contacts import --campaign 812 --file - --yes\n```\n\nA run read from stdin cannot be resumed with `kenso runs resume`, so prefer a file for large imports.\n\n### What the CLI checks before sending\n\nEvery row is checked locally first. A row that fails goes to `invalid.csv` with one of these reasons and is not sent:\n\n| Reason | Meaning |\n|---|---|\n| `missing_email` | The row has no email (and is not a LinkedIn-only lead) |\n| `invalid_email` | The email is not a valid address |\n| `missing_first_name` | The row has no first name |\n| `missing_last_name` | The row has no last name |\n| `missing_company` | The row has neither a company name nor a company domain |\n| `sales_navigator_url` | An email-less row whose LinkedIn URL is a Sales Navigator link: add the email or a linkedin.com/in/ URL |\n| `duplicate_in_file` | An earlier row of the file has the same email |\n\nKenso stays the authority and checks every row again.\n\n### What the dry run shows\n\nThe dry run maps the columns, checks the rows, reads the campaign, and asks for a credit estimate (`credit-estimates create`, kind `leads`). Its plan holds `rows`, `valid`, `invalid`, `mapping`, `customVariableKeys`, `estimate`, `credits` (`needed`, `available`, `sufficient`) and `next`, the exact apply command. If the estimate call fails, the plan still prints with `"estimate":null` and an `estimateError`.\n\n### How rows are sent\n\nThe CLI sends 1,000 rows per call to `POST /v1/campaigns/{campaignId}/contacts`, one call at a time per campaign, because two overlapping upserts of the same email could create duplicates. After a 5xx answer or a dropped connection it does not retry right away: it waits 130 seconds, so the first request has finished on the server, then resends the chunk once. Rows the first request saved come back `updated`.\n\n### Reading the result\n\nEach row in `results.csv` gets one status:\n\n| Status | Meaning |\n|---|---|\n| `created` | A new lead in the campaign |\n| `updated` | The lead was already there and was updated |\n| `skipped` | Kenso kept the lead out on purpose. `reason` is `duplicate`, `blocklisted`, `already_contacted`, `excluded` or another code |\n| `failed` | Kenso refused the row (`reason` such as `invalid_email` or `validation`, and an `error` message), or the call failed |\n| `invalid` | The CLI refused the row before sending it (see the table above) |\n\nA saved lead that cannot be emailed yet has `sendable` false, and the summary counts those leads in `notSendable` with a warning on stderr.\n\nExit codes: 0 when no row failed (skipped rows are not failures), 5 when some rows failed or were invalid, 6 when the plan\'s or campaign\'s lead limit stopped the run (`limit_reached`; raise the limit, then rerun the same command to send the rest).\n\n## Import a very large file on the server\n\nFor up to 100,000 rows, `--server-import` uploads the CSV as one server import job and waits for it (default 30 minutes, `--timeout`). It reports the job\'s counts but no per-row results.\n\n```bash\nkenso contacts import --campaign 812 --file big.csv --server-import --yes\nkenso contacts import --campaign 812 --file big.csv --server-import --timeout 1h --yes\n```\n\n## Update leads in bulk\n\n```bash\nkenso contacts update --file edits.csv --match id\nkenso contacts update --file edits.csv --match id --yes\nkenso contacts update --file edits.csv --match email --campaign 812 --yes\n```\n\n- `--match id` reads the contact id from an `id` or `contactId` column.\n- `--match email` finds each email among the leads of `--campaign`. An email it cannot find is `not_found`. The email column only finds the lead; it is never sent as an edit.\n- A column that is absent, or a blank cell, leaves that field unchanged. The literal `null` clears it.\n- The lead fields you can edit are `firstName`, `lastName`, `title`, `linkedInUrl`, and `email` with `--match id`. `companyName` and `companyDomain` cannot change here and are not sent. Every other column is a custom variable, mapped the same way as in an import, and `--map` works here too.\n- A row with nothing to change is `skipped` with reason `no_changes` and is not sent. Rows go 1,000 per call to `POST /v1/contacts/bulk-update`.\n\nTo edit one lead, use a one-row file from stdin:\n\n```bash\nprintf \'id,title\\n9001,VP Sales\\n\' | kenso contacts update --file - --match id --yes\n```\n\n## Remove, restore, pause and resume\n\nThese four take contact ids from `--ids` (one id per line, or a CSV or JSONL file with an `id` or `contactId` column, or `-` for stdin), or from a search with `--where` (remove, pause and resume). `--where` takes the body of `POST /v1/contacts/search` as JSON, `@file` or `-`, and does the search itself: its plan shows how many contacts match and the first ids, so run no separate search or list first. `q` matches names and email addresses only; a company is a `filters` condition on `ContactCompany.Name` (`operator` 2 is contains; `kenso describe contacts search` lists the fields and operators).\n\n```bash\nkenso contacts remove --ids ids.txt --dry-run\nkenso contacts remove --ids ids.txt --yes\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --dry-run\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --yes\nkenso contacts remove --ids big.csv --confirm 2500 --yes\n```\n\n- Without `--yes`, the plan prints the count and the first ids.\n- Removing more than 1,000 contacts also needs `--confirm <count>`, and the count must match. The plan\'s `next` already carries the right `--confirm`.\n- Each id comes back `ok`, `skipped` when there was nothing to do (for example `not_deleted` when you restore a contact that is not removed), `not_found` or `failed`.\n- The remove summary carries the undo command, `"undo":"kenso contacts restore --run r_ubqu7wtx"`.\n\n```bash\nkenso contacts restore --run r_ubqu7wtx --yes\nkenso contacts restore --ids ids.txt --yes\nkenso contacts pause --where \'{"campaignIds": [812]}\' --yes\nkenso contacts resume --ids ids.txt --yes\n```\n\n`restore` takes `--ids` or `--run <runId>` of an earlier remove, not `--where`: a search cannot find removed contacts. `pause` is a beta command for workspaces with the `pause_leads` flag.\n\n## Tag and untag\n\n```bash\nkenso tags list\nkenso contacts tag --tag 31 --ids ids.txt --yes\nkenso contacts untag --tag 31 --ids ids.txt --yes\n```\n\n`tag` calls `POST /v1/tags/{tagId}/assignments` once per contact. A contact that already has the tag is `skipped` with reason `already_tagged`.\n\n## Export a campaign\'s leads\n\n```bash\nkenso contacts export --campaign 812 --out contacts.csv\nkenso contacts export --campaign 812 --wait\n```\n\nWith `--out`, the CLI creates the export, waits for the job (default 30 minutes, `--timeout`) and writes one CSV file (mode 0600). Without `--out` it prints the export job; `--wait` waits for it, or run the `next` it prints, `kenso jobs wait <jobId> --type contact_export`.\n\n## Recipes\n\n**Tag every lead of a campaign.** List the ids, then tag them:\n\n```bash\nkenso contacts list --campaign-id 812 --all -o ids > ids.txt\nkenso contacts tag --tag 31 --ids ids.txt --yes\n```\n\n**Fix the invalid rows and send them.** `invalid.csv` keeps each refused row\'s number and reason. Fix those rows in a new file and import it. Rerunning the original file also works: rows Kenso already saved come back `updated` or `skipped`.\n\n**Retry only what failed.** Filter `results.csv` to the `failed` rows, take those rows from the input by `row` number, and import that file.\n\n**Pause leads who replied elsewhere.** Plan with the filter (the plan shows the count), then apply:\n\n```bash\nkenso contacts pause --where @replied.json\nkenso contacts pause --where @replied.json --yes\n```\n\n**Edit one field on many leads by email.**\n\n```bash\nkenso contacts update --file titles.csv --match email --campaign 812 --dry-run\nkenso contacts update --file titles.csv --match email --campaign 812 --yes\n```\n';
7795
+ leads_default = '# Leads\n\nLeads are contacts in a campaign. The lead commands live under `kenso contacts`, and `kenso leads` is the same thing: `kenso leads import` runs `kenso contacts import`.\n\n| Command | What it does |\n|---|---|\n| `contacts import` | Add leads from a CSV or JSONL file to a campaign, with one result per row |\n| `contacts update` | Edit leads in bulk from a file, matched by id or by email |\n| `contacts remove` / `restore` | Remove (soft-delete) leads by id, and undo it |\n| `contacts pause` / `resume` | Pause and resume the campaign sequence of leads (pause is beta, `pause_leads` flag) |\n| `contacts tag` / `untag` | Add or remove a tag on leads by id |\n| `contacts export` | Download a campaign\'s leads as one CSV file |\n\nAll of them except `export` are batch commands: without `--yes` they print a plan and change nothing. [Batch runs](batch.md) explains plans, run folders, results files and resume.\n\n## Import a CSV into a campaign\n\n```bash\nkenso contacts import --template\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`--template` prints the accepted columns. A minimal file:\n\n```csv\nemail,firstName,lastName,companyName,Pain Point\nann@acme.io,Ann,Lee,Acme,Slow onboarding\ncid@globex.com,Cid,Moe,Globex,Churn\n```\n\n### Columns\n\nHeaders are matched without regard to case, spaces or punctuation. The known fields and the other headers each one reads:\n\n| Field | Also read from | Rule |\n|---|---|---|\n| `email` | email address, e-mail, work email | Required, unless the campaign is LinkedIn-only and the row has a linkedin.com/in/ URL |\n| `firstName` | first name, first, given name | Required |\n| `lastName` | last name, last, surname, family name | Required |\n| `title` | job title, position, role | Optional |\n| `linkedInUrl` | linkedin, linkedin url, linkedin profile, profile url | Optional |\n| `companyName` | company, organization, account, account name | `companyName` or `companyDomain` is required |\n| `companyDomain` | website, domain, company website, url | `companyName` or `companyDomain` is required |\n\nEvery other column becomes a custom variable, named like its header in snake_case: a `Pain Point` column fills `{{pain_point}}` in your sequence. Names Kenso keeps for its own fields (`city`, `country`, `phone_number` and others) are not sent: the CLI warns and the plan lists them under `droppedColumns`. Rename them with `--map`.\n\n### Cells\n\n- A blank cell is never sent, so importing a file never erases data on a lead that is already in the campaign.\n- The literal value `null` clears a custom variable.\n\n### Rename or drop columns with --map\n\n`--map` takes a JSON object, `@file` or `-` for stdin. A value names the target field, and `null` drops the column:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --map \'{"Pain": "customVariables.pain_point", "Notes": null}\' --yes\n```\n\n### JSONL\n\nEach line is one lead. Keys work like CSV headers, and a `customVariables` object is spread into custom variables:\n\n```json\n{"email":"ann@acme.io","firstName":"Ann","lastName":"Lee","companyName":"Acme","customVariables":{"pain_point":"Slow onboarding"}}\n```\n\n```bash\nkenso contacts import --campaign 812 --file leads.jsonl --yes\ncat leads.jsonl | kenso contacts import --campaign 812 --file - --yes\n```\n\nA run read from stdin cannot be resumed with `kenso runs resume`, so prefer a file for large imports.\n\n### What the CLI checks before sending\n\nEvery row is checked locally first. A row that fails goes to `invalid.csv` with one of these reasons and is not sent:\n\n| Reason | Meaning |\n|---|---|\n| `missing_email` | The row has no email (and is not a LinkedIn-only lead) |\n| `invalid_email` | The email is not a valid address |\n| `missing_first_name` | The row has no first name |\n| `missing_last_name` | The row has no last name |\n| `missing_company` | The row has neither a company name nor a company domain |\n| `sales_navigator_url` | An email-less row whose LinkedIn URL is a Sales Navigator link: add the email or a linkedin.com/in/ URL |\n| `duplicate_in_file` | An earlier row of the file has the same email |\n\nKenso stays the authority and checks every row again.\n\n### What the dry run shows\n\nThe dry run maps the columns, checks the rows, reads the campaign, and asks for a credit estimate (`credit-estimates create`, kind `leads`). Its plan holds `rows`, `valid`, `invalid`, `mapping`, `customVariableKeys`, `estimate`, `credits` (`needed`, `available`, `sufficient`) and `next`, the exact apply command. If the estimate call fails, the plan still prints with `"estimate":null` and an `estimateError`.\n\n### How rows are sent\n\nThe CLI sends 1,000 rows per call to `POST /v1/campaigns/{campaignId}/contacts`, one call at a time per campaign, because two overlapping upserts of the same email could create duplicates. After a 5xx answer or a dropped connection it does not retry right away: it waits 130 seconds, so the first request has finished on the server, then resends the chunk once. Rows the first request saved come back `updated`.\n\n### Reading the result\n\nEach row in `results.csv` gets one status:\n\n| Status | Meaning |\n|---|---|\n| `created` | A new lead in the campaign |\n| `updated` | The lead was already there and was updated |\n| `skipped` | Kenso kept the lead out on purpose. `reason` is `duplicate`, `blocklisted`, `already_contacted`, `excluded` or another code |\n| `failed` | Kenso refused the row (`reason` such as `invalid_email` or `validation`, and an `error` message), or the call failed |\n| `invalid` | The CLI refused the row before sending it (see the table above) |\n\nA saved lead that cannot be emailed yet has `sendable` false, and the summary counts those leads in `notSendable` with a warning on stderr.\n\nExit codes: 0 when no row failed (skipped rows are not failures), 5 when some rows failed or were invalid, 6 when the plan\'s or campaign\'s lead limit stopped the run (`limit_reached`; raise the limit, then rerun the same command to send the rest).\n\n## Import a very large file on the server\n\nFor up to 100,000 rows, `--server-import` uploads the CSV as one server import job and waits for it (default 30 minutes, `--timeout`). It reports the job\'s counts but no per-row results.\n\n```bash\nkenso contacts import --campaign 812 --file big.csv --server-import --yes\nkenso contacts import --campaign 812 --file big.csv --server-import --timeout 1h --yes\n```\n\n## Update leads in bulk\n\n```bash\nkenso contacts update --file edits.csv --match id\nkenso contacts update --file edits.csv --match id --yes\nkenso contacts update --file edits.csv --match email --campaign 812 --yes\n```\n\n- `--match id` reads the contact id from an `id` or `contactId` column.\n- `--match email` finds each email among the leads of `--campaign`. An email it cannot find is `not_found`. The email column only finds the lead; it is never sent as an edit.\n- A column that is absent, or a blank cell, leaves that field unchanged. The literal `null` clears it.\n- The lead fields you can edit are `firstName`, `lastName`, `title`, `linkedInUrl`, and `email` with `--match id`. `companyName` and `companyDomain` cannot change here and are not sent. Every other column is a custom variable, mapped the same way as in an import, and `--map` works here too.\n- A row with nothing to change is `skipped` with reason `no_changes` and is not sent. Rows go 1,000 per call to `POST /v1/contacts/bulk-update`.\n\nTo edit one lead, use a one-row file from stdin:\n\n```bash\nprintf \'id,title\\n9001,VP Sales\\n\' | kenso contacts update --file - --match id --yes\n```\n\n## Remove, restore, pause and resume\n\nThese four take contact ids from `--ids` (one id per line, or a CSV or JSONL file with an `id` or `contactId` column, or `-` for stdin), or from a search with `--where` (remove, pause and resume). `--where` takes the body of `POST /v1/contacts/search` as JSON, `@file` or `-`, and does the search itself: its plan shows how many contacts match and the first ids, so run no separate search or list first. `q` matches names and email addresses only; a company is a `filters` condition on `ContactCompany.Name` (`operator` 2 is contains; `kenso describe contacts search` lists the fields and operators).\n\n```bash\nkenso contacts remove --ids ids.txt --dry-run\nkenso contacts remove --ids ids.txt --yes\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --dry-run\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --yes\nkenso contacts remove --ids big.csv --confirm 2500 --yes\n```\n\n- Without `--yes`, the plan prints the count and the first ids.\n- Removing more than 1,000 contacts also needs `--confirm <count>`, and the count must match. The plan\'s `next` already carries the right `--confirm`.\n- Each id comes back `ok`, `skipped` when there was nothing to do (for example `not_deleted` when you restore a contact that is not removed), `not_found` or `failed`.\n- The remove summary carries the undo command, `"undo":"kenso contacts restore --run r_ubqu7wtx"`.\n\n```bash\nkenso contacts restore --run r_ubqu7wtx --yes\nkenso contacts restore --ids ids.txt --yes\nkenso contacts pause --where \'{"campaignIds": [812]}\' --yes\nkenso contacts resume --ids ids.txt --yes\n```\n\n`restore` takes `--ids` or `--run <runId>` of an earlier remove, not `--where`: a search cannot find removed contacts. `pause` is a beta command for workspaces with the `pause_leads` flag.\n\n## Tag and untag\n\n```bash\nkenso tags list\nkenso contacts tag --tag 31 --ids ids.txt --yes\nkenso contacts untag --tag 31 --ids ids.txt --yes\n```\n\n`tag` calls `POST /v1/tags/{tagId}/assignments` once per contact. A contact that already has the tag is `skipped` with reason `already_tagged`.\n\n## Export a campaign\'s leads\n\n```bash\nkenso contacts export --campaign 812 --out contacts.csv\nkenso contacts export --campaign 812 --wait\n```\n\nWith `--out`, the CLI creates the export, waits for the job (default 30 minutes, `--timeout`) and writes one CSV file (mode 0600). An audience-based campaign exports one CSV per segment in a ZIP: the CLI saves the ZIP as it came, prints `"format": "zip"` and its size instead of a row count, and warns when `--out` does not end in `.zip`. Without `--out` it prints the export job; `--wait` waits for it, or run the `next` it prints, `kenso jobs wait <jobId> --type contact_export`.\n\n## Recipes\n\n**Tag every lead of a campaign.** List the ids, then tag them:\n\n```bash\nkenso contacts list --campaign-id 812 --all -o ids > ids.txt\nkenso contacts tag --tag 31 --ids ids.txt --yes\n```\n\n**Fix the invalid rows and send them.** `invalid.csv` keeps each refused row\'s number and reason. Fix those rows in a new file and import it. Rerunning the original file also works: rows Kenso already saved come back `updated` or `skipped`.\n\n**Retry only what failed.** Filter `results.csv` to the `failed` rows, take those rows from the input by `row` number, and import that file.\n\n**Pause leads who replied elsewhere.** Plan with the filter (the plan shows the count), then apply:\n\n```bash\nkenso contacts pause --where @replied.json\nkenso contacts pause --where @replied.json --yes\n```\n\n**Edit one field on many leads by email.**\n\n```bash\nkenso contacts update --file titles.csv --match email --campaign 812 --dry-run\nkenso contacts update --file titles.csv --match email --campaign 812 --yes\n```\n';
7589
7796
  }
7590
7797
  });
7591
7798
 
@@ -7593,7 +7800,7 @@ var init_leads = __esm({
7593
7800
  var output_and_errors_default;
7594
7801
  var init_output_and_errors = __esm({
7595
7802
  "docs/output-and-errors.md"() {
7596
- output_and_errors_default = '# Output and errors\n\nEvery command follows one contract, so a script or an agent can parse any of them the same way.\n\n## stdout and stderr\n\n- **stdout carries data only.** Progress, warnings, notices and errors go to stderr.\n- No colors, spinners or pagers. On a terminal you get readable tables; in a pipe you get JSON.\n- A batch command (an import, update, remove, tag or `--each` write) takes `--yes`; without it, the command plans or refuses.\n- A command that deletes, archives or removes, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive` or `kenso api DELETE /v1/tags/7`, needs `--yes` too. Without it, a person at a terminal is asked to confirm; anywhere else (a pipe, a script, CI, a coding agent) it sends nothing and fails with `confirmation_required`, whose `next` is the same command with `--yes`.\n- Any other single write, such as `kenso tags create` or a write through `kenso api` or `kenso mcp call`, sends at once: add `--dry-run` to print the request first (it sends nothing), then run the command without it.\n- A command with no dry run, such as `kenso contacts export`, `kenso auth logout` or `kenso workspace use`, refuses `--dry-run` with `usage_error` (exit 2) and does nothing. Its help ends with `No --dry-run`, and `kenso describe <resource> <action>` shows `"dryRun": false`.\n\n## Formats\n\n| What the command returns | stdout is a terminal | stdout is a pipe or file |\n|---|---|---|\n| One object | key-value lines | compact JSON on one line |\n| A list | a table (first 8 scalar fields, cells cut at 60 characters) | NDJSON: one JSON object per line |\n| A batch run | key-value lines | one JSON summary object |\n| No content (HTTP 204) | nothing | nothing |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table` or `ids`. `--json` is the same as `-o json`.\n\n- `-o json` on a list prints one JSON array. On a terminal, `-o json` pretty-prints an object.\n- `-o ids` prints one id per line, ready for `--ids -`. Items without an `id` are skipped with one warning.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso contacts list --campaign-id 812 --all -o ids\n```\n\n## Shape the output\n\n- `--fields a,b.c` keeps only those fields (dots reach into nested objects).\n- `--query <JMESPath>` filters or reshapes in-process, so you need no `jq`. On a list it sees the whole list. There is no `--jq`: `--query` takes JMESPath, not jq syntax.\n- Neither applies to a batch summary, which always prints in full.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\n```\n\n## Lists and pages\n\nA list command prints one page. When there are more, it prints the command for the next page on stderr, for example `next: kenso tags list --limit 1 --cursor MQ`. `--all` follows every page and streams the items. `--limit` sets the page size and `--cursor` starts at a cursor.\n\n`accounts search`, `contacts search` and `people search` page the same way: one page with the `next:` command, or every page with `--all`. A search that asks for counts (`countBy` in `--data`) prints the whole answer instead: `data`, `pagination` and `counts`. Counts cover every match whatever the page, so ask for them on one page (`--limit 1`): `--all` with `countBy` is a usage error.\n\n```bash\nkenso tags list --limit 50\nkenso tags list --all\n```\n\n## Live streams\n\n`kenso sync events` and `kenso onboarding-builds events` follow a live stream of server-sent events. They print one JSON line per event as it arrives, on a terminal too, with the event\'s name, its id when it has one, and its data:\n\n```json\n{"event":"hello","data":{"buildId":"obd_2x","status":"building","stage":"read","lastEventId":0}}\n{"event":"stage","id":"41","data":{"stage":"plan"}}\n{"event":"done","id":"42","data":{}}\n```\n\nA stream has no time limit while events arrive. The server ends each connection after 15 minutes with a `bye` event; the command then connects again at once, and after a dropped connection or 60 s without even a keepalive, after a second. A connection that brought nothing but `hello` and `bye` (a server that is restarting) backs off 1, 2, 4 ... 30 s. Once events carry an id (`onboarding-builds events`), it sends the last whole event\'s id as `Last-Event-ID`, so no event is lost or printed twice. A refusal (401, 403, 404) ends it at once; eight failed or empty connects in a row end it with the last error.\n\nIt runs until Ctrl-C (exit 130; every line printed is whole), or until one of these:\n\n| Flag | Ends the command |\n|---|---|\n| `--until <event>` | After the first event with that name; several names are comma-separated: `--until done,error` |\n| `--max-events <n>` | After n events, `hello` and `bye` included |\n| `--once` | When the server closes the connection, instead of connecting again |\n\n```bash\nkenso onboarding-builds events --build-id obd_2x --until done,error\nkenso sync events --max-events 2 # hello, then the first poke\n```\n\n`--output`, `--fields` and `--query` do not apply to a stream. `--last-event-id` starts an onboarding build stream after that id.\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';
7803
+ output_and_errors_default = '# Output and errors\n\nEvery command follows one contract, so a script or an agent can parse any of them the same way.\n\n## stdout and stderr\n\n- **stdout carries data only.** Progress, warnings, notices and errors go to stderr.\n- No colors, spinners or pagers. On a terminal you get readable tables; in a pipe you get JSON.\n- A batch command (an import, update, remove, tag or `--each` write) takes `--yes`; without it, the command plans or refuses.\n- A command that deletes, archives or removes, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive` or `kenso api DELETE /v1/tags/7`, needs `--yes` too. Without it, a person at a terminal is asked to confirm; anywhere else (a pipe, a script, CI, a coding agent) it sends nothing and fails with `confirmation_required`, whose `next` is the same command with `--yes`.\n- Any other single write, such as `kenso tags create` or a write through `kenso api` or `kenso mcp call`, sends at once: add `--dry-run` to print the request first (it sends nothing), then run the command without it.\n- A command with no dry run, such as `kenso contacts export`, `kenso auth logout` or `kenso workspace use`, refuses `--dry-run` with `usage_error` (exit 2) and does nothing. Its help ends with `No --dry-run`, and `kenso describe <resource> <action>` shows `"dryRun": false`.\n\n## Formats\n\n| What the command returns | stdout is a terminal | stdout is a pipe or file |\n|---|---|---|\n| One object | key-value lines | compact JSON on one line |\n| A list | a table (first 8 scalar fields, cells cut at 60 characters) | NDJSON: one JSON object per line |\n| A batch run | key-value lines | one JSON summary object |\n| No content (HTTP 204) | nothing | nothing |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table` or `ids`. `--json` is the same as `-o json`.\n\n- `-o json` on a list prints one JSON array. On a terminal, `-o json` pretty-prints an object.\n- `-o ids` prints one id per line, ready for `--ids -`. Items without an `id` are skipped with one warning.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso contacts list --campaign-id 812 --all -o ids\n```\n\n## Shape the output\n\n- `--fields a,b.c` keeps only those fields (dots reach into nested objects).\n- `--query <JMESPath>` filters or reshapes in-process, so you need no `jq`. On a list it sees the whole list. There is no `--jq`: `--query` takes JMESPath, not jq syntax.\n- Neither applies to a batch summary, which always prints in full.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\n```\n\n## Lists and pages\n\nA list command prints one page. When there are more, it prints the command for the next page on stderr, for example `next: kenso tags list --limit 1 --cursor MQ`. `--all` follows every page and streams the items. `--limit` sets the page size and `--cursor` starts at a cursor.\n\n`accounts search`, `contacts search` and `people search` page the same way: one page with the `next:` command, or every page with `--all`. A search that asks for counts (`countBy` in `--data`) prints the whole answer instead: `data`, `pagination` and `counts`. Counts cover every match whatever the page, so ask for them on one page (`--limit 1`): `--all` with `countBy` is a usage error.\n\n```bash\nkenso tags list --limit 50\nkenso tags list --all\n```\n\n## Files: uploads and downloads\n\nA command whose API action takes a multipart upload takes `--file <path>`: the CLI reads the file and sends it in the form, with a content type from its extension (a `.png` goes as `image/png`), and the other flags as form fields. `--file <field>=<path>` names the form field, for a form with more than one file. An upload that also takes JSON, such as a logo from a URL instead of a file, sends JSON when you leave `--file` out.\n\nA command whose API action answers with a file (a CSV, an image, a ZIP) takes `--out <path>`: it saves the answer byte for byte (mode 0600) and prints `out`, `bytes` and `contentType`, so the file never passes through an agent\'s context. Without `--out`, a CSV prints as it came, and a binary file goes to stdout only when stdout is a pipe or a file: on a terminal it fails with `binary_output`, whose `next` adds `--out`.\n\n`kenso api` takes both, for any route: `--file` (repeat it for more files) sends multipart with the keys of a `--data` object as form fields, and `--out` saves any answer.\n\n```bash\nkenso saved-lists create-upload --saved-list-id 12 --file people.csv\nkenso workspaces replace-logo --workspace-id 42 --file ./logo.png\nkenso workspaces replace-logo --workspace-id 42 --source-url https://example.com/logo.png\nkenso attachments get-content --attachment-id att_123 --out ./invoice.pdf\nkenso api POST /v1/campaigns/812/email-sequence/images --file ./hero.png\nkenso api GET /v1/knowledge/exports/77/content --out knowledge.zip\n```\n\n## Live streams\n\n`kenso sync events` and `kenso onboarding-builds events` follow a live stream of server-sent events. They print one JSON line per event as it arrives, on a terminal too, with the event\'s name, its id when it has one, and its data:\n\n```json\n{"event":"hello","data":{"buildId":"obd_2x","status":"building","stage":"read","lastEventId":0}}\n{"event":"stage","id":"41","data":{"stage":"plan"}}\n{"event":"done","id":"42","data":{}}\n```\n\nA stream has no time limit while events arrive. The server ends each connection after 15 minutes with a `bye` event; the command then connects again at once, and after a dropped connection or 60 s without even a keepalive, after a second. A connection that brought nothing but `hello` and `bye` (a server that is restarting) backs off 1, 2, 4 ... 30 s. Once events carry an id (`onboarding-builds events`), it sends the last whole event\'s id as `Last-Event-ID`, so no event is lost or printed twice. A refusal (401, 403, 404) ends it at once; eight failed or empty connects in a row end it with the last error.\n\nIt runs until Ctrl-C (exit 130; every line printed is whole), or until one of these:\n\n| Flag | Ends the command |\n|---|---|\n| `--until <event>` | After the first event with that name; several names are comma-separated: `--until done,error` |\n| `--max-events <n>` | After n events, `hello` and `bye` included |\n| `--once` | When the server closes the connection, instead of connecting again |\n\n```bash\nkenso onboarding-builds events --build-id obd_2x --until done,error\nkenso sync events --max-events 2 # hello, then the first poke\n```\n\n`--output`, `--fields` and `--query` do not apply to a stream. `--last-event-id` starts an onboarding build stream after that id.\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: `--out` on `contacts export`, `kenso api` or a download command (2), `skill install` (1) |\n| `binary_output` | 2 | The answer is a binary file and stdout is a terminal: nothing was printed; `next` saves it with `--out` |\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';
7597
7804
  }
7598
7805
  });
7599
7806
 
@@ -7601,7 +7808,7 @@ var init_output_and_errors = __esm({
7601
7808
  var README_default;
7602
7809
  var init_README = __esm({
7603
7810
  "docs/README.md"() {
7604
- 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\nOn macOS or Linux, with or without Node, run the [install script](https://ken.so/install.sh): fetch it with `curl -fsSL` and pipe it to `sh`. It installs a standalone build that brings its own Node.js, checks the download against the release\'s `SHA256SUMS`, puts the CLI in `~/.local/share/kenso` and links `~/.local/bin/kenso`. Run it again to update.\n\nWith Homebrew, on macOS or Linux, the same standalone build:\n\n```bash\nbrew install ken-technology/tap/kenso\n```\n\n`brew upgrade kenso` updates it.\n\nWith Node 22 or newer, on any system, Windows included:\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`. On an older Node, kenso stops with one line that says so.\n\nEvery way to install:\n\n| Way | Systems | Needs |\n|---|---|---|\n| Install script, above | macOS, Linux (glibc) | Nothing |\n| Homebrew, above | macOS, Linux | Homebrew |\n| npm, above | Any | Node 22 or newer |\n| Standalone build: unpack it and put its `bin` folder on your PATH | macOS, Linux, Windows | Nothing |\n\nThe standalone builds are at `https://downloads.ken.so/desktop/cli/<version>/`, one per system: `kenso-<version>-darwin-arm64.tar.gz`, `darwin-x64`, `linux-arm64`, `linux-x64` and `kenso-<version>-windows-x64.zip`, with their `SHA256SUMS`. `https://downloads.ken.so/desktop/cli/latest.yml` names the newest version. The builds come out nightly and Homebrew follows them, so a command added that day reaches npm first.\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. A standalone build checks `latest.yml` on `downloads.ken.so` instead and names its own update: the install script, or `brew upgrade kenso` when Homebrew installed it. 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, live streams |\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\'s 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| [Developer sandbox](sandbox.md) | `sandbox` | `kenso sandbox`: a workspace of your own where sends are simulated, its test key, the reserved test leads |\n| [Connect accounts](connect.md) | `connect` | `kenso connect`: an inbox, calendar, CRM, GitHub or other OAuth account, signed in by the person in a browser |\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';
7811
+ 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 canonical 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`. The legacy routes with no canonical successor, such as sequence images, AI variables or thread opens, have no command: reach them with `kenso api <METHOD> <path>`.\n\n## Install\n\nOn macOS or Linux, with or without Node, run the [install script](https://ken.so/install.sh): fetch it with `curl -fsSL` and pipe it to `sh`. It installs a standalone build that brings its own Node.js, checks the download against the release\'s `SHA256SUMS`, puts the CLI in `~/.local/share/kenso` and links `~/.local/bin/kenso`. Run it again to update.\n\nWith Homebrew, on macOS or Linux, the same standalone build:\n\n```bash\nbrew install ken-technology/tap/kenso\n```\n\n`brew upgrade kenso` updates it.\n\nWith Node 22 or newer, on any system, Windows included:\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`. On an older Node, kenso stops with one line that says so.\n\nEvery way to install:\n\n| Way | Systems | Needs |\n|---|---|---|\n| Install script, above | macOS, Linux (glibc) | Nothing |\n| Homebrew, above | macOS, Linux | Homebrew |\n| npm, above | Any | Node 22 or newer |\n| Standalone build: unpack it and put its `bin` folder on your PATH | macOS, Linux, Windows | Nothing |\n\nThe standalone builds are at `https://downloads.ken.so/desktop/cli/<version>/`, one per system: `kenso-<version>-darwin-arm64.tar.gz`, `darwin-x64`, `linux-arm64`, `linux-x64` and `kenso-<version>-windows-x64.zip`, with their `SHA256SUMS`. `https://downloads.ken.so/desktop/cli/latest.yml` names the newest version. The builds come out nightly and Homebrew follows them, so a command added that day reaches npm first.\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. A standalone build checks `latest.yml` on `downloads.ken.so` instead and names its own update: the install script, or `brew upgrade kenso` when Homebrew installed it. 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, live streams |\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\'s 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| [Developer sandbox](sandbox.md) | `sandbox` | `kenso sandbox`: a workspace of your own where sends are simulated, its test key, the reserved test leads |\n| [Connect accounts](connect.md) | `connect` | `kenso connect`: an inbox, calendar, CRM, GitHub or other OAuth account, signed in by the person in a browser |\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';
7605
7812
  }
7606
7813
  });
7607
7814
 
@@ -7961,13 +8168,13 @@ __export(install_exports, {
7961
8168
  readExisting: () => readExisting,
7962
8169
  write: () => write
7963
8170
  });
7964
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync7, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
7965
- import { basename as basename2, dirname, join as join8, resolve as resolve4 } from "node:path";
8171
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync7, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
8172
+ import { basename as basename2, dirname, join as join8, resolve as resolve5 } from "node:path";
7966
8173
  function quote(value) {
7967
8174
  return /^[A-Za-z0-9_\-.,:/@=+%~]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
7968
8175
  }
7969
8176
  function readExisting(path) {
7970
- if (!existsSync3(path)) return void 0;
8177
+ if (!existsSync4(path)) return void 0;
7971
8178
  try {
7972
8179
  return readFileSync7(path, "utf8");
7973
8180
  } catch (err) {
@@ -7987,7 +8194,7 @@ function write(path, text4) {
7987
8194
  }
7988
8195
  }
7989
8196
  function folders(ctx, client, dir) {
7990
- if (dir !== void 0) return [{ client, folder: resolve4(dir) }];
8197
+ if (dir !== void 0) return [{ client, folder: resolve5(dir) }];
7991
8198
  const clients = client === "all" ? CLIENTS : [client];
7992
8199
  return clients.map((c) => ({ client: c, folder: join8(skillsFolder(c, ctx.env), SKILL_NAME) }));
7993
8200
  }
@@ -8055,8 +8262,8 @@ var init_install = __esm({
8055
8262
  for (const target of targets) {
8056
8263
  if (target.status !== "unchanged") write(target.path, text4);
8057
8264
  }
8058
- if (dir !== void 0 && basename2(resolve4(dir)) !== SKILL_NAME) {
8059
- ctx.output.warn(`Agents expect the skill's folder to be named ${SKILL_NAME}, like the skill: ${resolve4(dir)} is not.`);
8265
+ if (dir !== void 0 && basename2(resolve5(dir)) !== SKILL_NAME) {
8266
+ ctx.output.warn(`Agents expect the skill's folder to be named ${SKILL_NAME}, like the skill: ${resolve5(dir)} is not.`);
8060
8267
  }
8061
8268
  ctx.output.object({ installed: targets });
8062
8269
  return ExitCode.Ok;
@@ -8068,7 +8275,7 @@ var init_install = __esm({
8068
8275
 
8069
8276
  // src/commands/agent/mcp-config.ts
8070
8277
  import { spawnSync } from "node:child_process";
8071
- import { existsSync as existsSync4, readFileSync as readFileSync8 } from "node:fs";
8278
+ import { existsSync as existsSync5, readFileSync as readFileSync8 } from "node:fs";
8072
8279
  import { delimiter, join as join9 } from "node:path";
8073
8280
  function parse2(text4) {
8074
8281
  try {
@@ -8127,7 +8334,7 @@ function tomlServers(text4) {
8127
8334
  }
8128
8335
  function opencodeFile(env) {
8129
8336
  const dir = join9(xdgConfigDir(env), "opencode");
8130
- const existing = ["opencode.jsonc", "opencode.json", "config.json"].map((f) => join9(dir, f)).find((f) => existsSync4(f));
8337
+ const existing = ["opencode.jsonc", "opencode.json", "config.json"].map((f) => join9(dir, f)).find((f) => existsSync5(f));
8131
8338
  return existing ?? join9(dir, "opencode.json");
8132
8339
  }
8133
8340
  function canonical(url) {
@@ -8140,11 +8347,11 @@ function canonical(url) {
8140
8347
  }
8141
8348
  function onPath(bin, env) {
8142
8349
  const names = process.platform === "win32" ? [`${bin}.cmd`, `${bin}.exe`, bin] : [bin];
8143
- return (env.PATH ?? env.Path ?? "").split(delimiter).some((dir) => dir !== "" && names.some((n) => existsSync4(join9(dir, n))));
8350
+ return (env.PATH ?? env.Path ?? "").split(delimiter).some((dir) => dir !== "" && names.some((n) => existsSync5(join9(dir, n))));
8144
8351
  }
8145
8352
  function isPresent(client, env) {
8146
8353
  const t = TARGETS[client];
8147
- return t.bins.some((b) => onPath(b, env)) || existsSync4(t.folder(env));
8354
+ return t.bins.some((b) => onPath(b, env)) || existsSync5(t.folder(env));
8148
8355
  }
8149
8356
  function readText(path) {
8150
8357
  try {
@@ -8413,7 +8620,30 @@ function normalizePath(raw, apiUrl) {
8413
8620
  }
8414
8621
  return raw;
8415
8622
  }
8416
- var METHODS, command4, actions3;
8623
+ function quote3(value) {
8624
+ return /^[\w\-./]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8625
+ }
8626
+ function multipartBody(files, data) {
8627
+ const form = new FormData();
8628
+ if (data !== void 0) {
8629
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
8630
+ throw usageError("With --file, --data must be a JSON object: its keys become form fields.", { field: "data" });
8631
+ }
8632
+ for (const [key, value] of Object.entries(data)) {
8633
+ if (value === void 0 || value === null) continue;
8634
+ for (const item of Array.isArray(value) ? value : [value]) form.append(key, formValue(item));
8635
+ }
8636
+ }
8637
+ for (const item of files) {
8638
+ const { field, path } = splitFileArg(item);
8639
+ if (path === "") throw usageError(`--file ${item} names no file.`, { field: "file" });
8640
+ const name = field ?? DEFAULT_FILE_FIELD;
8641
+ const upload2 = readUpload(path, name);
8642
+ form.append(name, upload2.blob, upload2.name);
8643
+ }
8644
+ return form;
8645
+ }
8646
+ var METHODS, DEFAULT_FILE_FIELD, command4, actions3;
8417
8647
  var init_api3 = __esm({
8418
8648
  "src/commands/api/index.ts"() {
8419
8649
  "use strict";
@@ -8421,15 +8651,23 @@ var init_api3 = __esm({
8421
8651
  init_errors();
8422
8652
  init_exit_codes();
8423
8653
  init_input();
8654
+ init_transfer();
8424
8655
  METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
8656
+ DEFAULT_FILE_FIELD = "file";
8425
8657
  command4 = {
8426
8658
  resource: "api",
8427
8659
  action: "",
8428
8660
  summary: "Call any API route, only when no command fits",
8429
8661
  brief: "only when no command fits",
8430
- description: "The raw escape hatch: sends Authorization, Ken-Version: 1.1 and X-Ken-Workspace-Id, prints the full JSON body. The path may carry a query string. --all (GET only) follows pagination.nextCursor and prints the data[] items as a list. POST, PUT and PATCH send at once; DELETE needs --yes (on a terminal it asks). --dry-run prints the request (method, path, body) and sends nothing.",
8662
+ description: "The raw escape hatch: sends Authorization, Ken-Version: 1.1 and X-Ken-Workspace-Id, prints the full JSON body. It reaches the legacy routes that have no command. The path may carry a query string. --all (GET only) follows pagination.nextCursor and prints the data[] items as a list. --file sends a multipart upload. An answer that is not JSON (a CSV, an image, a ZIP) prints as it came; --out saves it byte for byte, and a binary one is never printed to a terminal. POST, PUT and PATCH send at once; DELETE needs --yes (on a terminal it asks). --dry-run prints the request (method, path, body) and sends nothing.",
8431
8663
  flags: {
8432
- data: { type: "string", description: "Request body: inline JSON, @file or - for stdin" },
8664
+ data: { type: "string", description: "Request body: inline JSON, @file or - for stdin. With --file, its keys are form fields" },
8665
+ file: {
8666
+ type: "string",
8667
+ multiple: true,
8668
+ description: "Upload as multipart/form-data: <field>=<path>, or <path> for field file. Repeat for more files"
8669
+ },
8670
+ out: { type: "string", description: "Save the answer to this file, byte for byte, and print a summary" },
8433
8671
  all: { type: "boolean", description: "GET only: follow every page and print the data[] items" },
8434
8672
  "no-workspace": { type: "boolean", description: "Do not send X-Ken-Workspace-Id" }
8435
8673
  },
@@ -8442,6 +8680,8 @@ var init_api3 = __esm({
8442
8680
  "kenso api GET '/v1/campaigns?limit=200' --all --output ids",
8443
8681
  `kenso api PATCH /v1/campaigns/123 --data '{"name":"Q4 outbound"}'`,
8444
8682
  "kenso api POST /v1/tags --data @tag.json",
8683
+ "kenso api POST /v1/campaigns/123/email-sequence/images --file ./hero.png",
8684
+ "kenso api GET /v1/attachments/att_123/content --out ./attachment.pdf",
8445
8685
  "kenso api DELETE /v1/tags/7 --dry-run"
8446
8686
  ],
8447
8687
  dryRun: true,
@@ -8452,14 +8692,21 @@ var init_api3 = __esm({
8452
8692
  }
8453
8693
  const path = normalizePath(positionals[1] ?? "", ctx.auth.apiUrl);
8454
8694
  const all = flags.all === true;
8695
+ const files = Array.isArray(flags.file) ? flags.file : typeof flags.file === "string" ? [flags.file] : [];
8696
+ const out = typeof flags.out === "string" ? flags.out : void 0;
8455
8697
  if (all && method !== "GET") throw usageError("--all works with GET only.", { field: "all" });
8698
+ if (all && out !== void 0) throw usageError("--all prints the items of every page; --out saves one answer.", { field: "out" });
8456
8699
  if (method === "GET" && typeof flags.data === "string") {
8457
8700
  throw usageError("--data cannot be used with GET.", { field: "data", hint: "Put the values in the query string, or use POST, PUT or PATCH." });
8458
8701
  }
8459
- const body2 = typeof flags.data === "string" ? await readDataArg(flags.data, ctx.stdin) : void 0;
8702
+ if (method === "GET" && files.length > 0) throw usageError("--file cannot be used with GET.", { field: "file", hint: "Upload with POST, PUT or PATCH." });
8703
+ const data = typeof flags.data === "string" ? await readDataArg(flags.data, ctx.stdin) : void 0;
8704
+ const form = files.length > 0 ? multipartBody(files, data) : void 0;
8705
+ const body2 = form ? void 0 : data;
8460
8706
  const noWorkspace = flags["no-workspace"] === true;
8461
8707
  if (ctx.flags.dryRun) {
8462
- ctx.output.object({ dryRun: true, request: { method, path, ...body2 !== void 0 ? { body: body2 } : {} } });
8708
+ const request = { method, path, ...form ? { form: describeForm(form) } : body2 !== void 0 ? { body: body2 } : {} };
8709
+ ctx.output.object({ dryRun: true, request });
8463
8710
  return ExitCode.Ok;
8464
8711
  }
8465
8712
  if (all) {
@@ -8467,10 +8714,14 @@ var init_api3 = __esm({
8467
8714
  return ExitCode.Ok;
8468
8715
  }
8469
8716
  if (method === "DELETE") {
8470
- const quoted = /^[\w\-./]+$/.test(path) ? path : `'${path.replace(/'/g, `'\\''`)}'`;
8471
- await confirmDestructive(ctx, `kenso api sends DELETE ${path}`, `kenso api DELETE ${quoted} --yes`);
8717
+ await confirmDestructive(ctx, `kenso api sends DELETE ${path}`, `kenso api DELETE ${quote3(path)} --yes`);
8718
+ }
8719
+ const res = await ctx.client.request({ method, path, body: body2, ...form ? { form } : {}, noWorkspace, signal: ctx.signal });
8720
+ if (out !== void 0 || res.raw !== void 0) {
8721
+ const next = `kenso api ${method} ${quote3(path)}${noWorkspace ? " --no-workspace" : ""} --out ${quote3(suggestedFileName(res))}`;
8722
+ await writeFileResponse(ctx, res, { out, next });
8723
+ return ExitCode.Ok;
8472
8724
  }
8473
- const res = await ctx.client.request({ method, path, body: body2, noWorkspace, signal: ctx.signal });
8474
8725
  if (res.body !== null && res.body !== "") ctx.output.object(res.body);
8475
8726
  return ExitCode.Ok;
8476
8727
  }
@@ -8725,8 +8976,8 @@ var init_browser_login = __esm({
8725
8976
  defaultDeps = {
8726
8977
  sleep: (ms, signal) => delay2(ms, void 0, signal ? { signal } : void 0),
8727
8978
  now: () => Date.now(),
8728
- spawn: (command48, args) => {
8729
- const child = nodeSpawn(command48, args, { detached: true, stdio: "ignore" });
8979
+ spawn: (command49, args) => {
8980
+ const child = nodeSpawn(command49, args, { detached: true, stdio: "ignore" });
8730
8981
  child.on("error", () => {
8731
8982
  });
8732
8983
  child.unref();
@@ -9915,8 +10166,8 @@ var init_run = __esm({
9915
10166
  defaultDeps2 = {
9916
10167
  sleep: (ms, signal) => delay3(ms, void 0, signal ? { signal } : void 0),
9917
10168
  now: () => Date.now(),
9918
- spawn: (command48, args) => {
9919
- const child = nodeSpawn2(command48, args, { detached: true, stdio: "ignore" });
10169
+ spawn: (command49, args) => {
10170
+ const child = nodeSpawn2(command49, args, { detached: true, stdio: "ignore" });
9920
10171
  child.on("error", () => {
9921
10172
  });
9922
10173
  child.unref();
@@ -9950,16 +10201,16 @@ var init_connect3 = __esm({
9950
10201
  // src/commands/contacts/common.ts
9951
10202
  import { createHash as createHash3 } from "node:crypto";
9952
10203
  import { readFile as readFile6 } from "node:fs/promises";
9953
- import { resolve as resolve5 } from "node:path";
10204
+ import { resolve as resolve6 } from "node:path";
9954
10205
  function stringFlag2(flags, name) {
9955
10206
  const value = flags[name];
9956
10207
  if (typeof value !== "string") return void 0;
9957
10208
  const text4 = value.trim();
9958
10209
  return text4 === "" ? void 0 : text4;
9959
10210
  }
9960
- function requireFlag(flags, name, command48, hint) {
10211
+ function requireFlag(flags, name, command49, hint) {
9961
10212
  const value = stringFlag2(flags, name);
9962
- if (value === void 0) throw usageError(`--${name} is required for ${command48}.`, { field: name, next: `${command48} --help`, ...hint ? { hint } : {} });
10213
+ if (value === void 0) throw usageError(`--${name} is required for ${command49}.`, { field: name, next: `${command49} --help`, ...hint ? { hint } : {} });
9963
10214
  return value;
9964
10215
  }
9965
10216
  function positiveId(value) {
@@ -9968,8 +10219,8 @@ function positiveId(value) {
9968
10219
  const id = Number(text4);
9969
10220
  return Number.isSafeInteger(id) && id > 0 ? id : void 0;
9970
10221
  }
9971
- function idFlag(flags, name, command48) {
9972
- const raw = requireFlag(flags, name, command48);
10222
+ function idFlag(flags, name, command49) {
10223
+ const raw = requireFlag(flags, name, command49);
9973
10224
  const id = positiveId(raw);
9974
10225
  if (id === void 0) throw usageError(`--${name} must be a positive whole number (got "${raw}").`, { field: name });
9975
10226
  return id;
@@ -9989,8 +10240,8 @@ function isDryRun(ctx) {
9989
10240
  function shellQuote4(value) {
9990
10241
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
9991
10242
  }
9992
- function sameCommand2(command48, flags, ctx, extra = []) {
9993
- const parts2 = [command48];
10243
+ function sameCommand2(command49, flags, ctx, extra = []) {
10244
+ const parts2 = [command49];
9994
10245
  for (const [name, value] of Object.entries(flags)) {
9995
10246
  if (value === void 0 || value === false) continue;
9996
10247
  if (value === true) parts2.push(`--${name}`);
@@ -10004,7 +10255,7 @@ function sameCommand2(command48, flags, ctx, extra = []) {
10004
10255
  return parts2.join(" ");
10005
10256
  }
10006
10257
  async function fileSha256(path) {
10007
- return createHash3("sha256").update(await readFile6(resolve5(path))).digest("hex");
10258
+ return createHash3("sha256").update(await readFile6(resolve6(path))).digest("hex");
10008
10259
  }
10009
10260
  function rateLimitRemaining3(headers) {
10010
10261
  const raw = headers.get("ratelimit-remaining");
@@ -10033,13 +10284,13 @@ function warnDropped(ctx, mapping) {
10033
10284
  const list2 = dropped.map(([header, reason]) => `"${header}" (${reason})`).join(", ");
10034
10285
  ctx.output.warn(`Not sent: ${list2}. Rename a column with --map '{"<column>": "customVariables.<name>"}'.`);
10035
10286
  }
10036
- var OUT_FLAG, CONCURRENCY_FLAG;
10287
+ var OUT_FLAG2, CONCURRENCY_FLAG;
10037
10288
  var init_common = __esm({
10038
10289
  "src/commands/contacts/common.ts"() {
10039
10290
  "use strict";
10040
10291
  init_errors();
10041
10292
  init_exit_codes();
10042
- OUT_FLAG = { type: "string", description: "Keep the run's files (results.csv, invalid.csv, plan.json) in this directory" };
10293
+ OUT_FLAG2 = { type: "string", description: "Keep the run's files (results.csv, invalid.csv, plan.json) in this directory" };
10043
10294
  CONCURRENCY_FLAG = { type: "string", description: "Requests in flight at once (default 4, max 16)" };
10044
10295
  }
10045
10296
  });
@@ -10643,7 +10894,7 @@ var init_wait = __esm({
10643
10894
 
10644
10895
  // src/commands/contacts/server-import.ts
10645
10896
  import { readFile as readFile7 } from "node:fs/promises";
10646
- import { basename as basename3, extname as extname2, resolve as resolve6 } from "node:path";
10897
+ import { basename as basename3, extname as extname3, resolve as resolve7 } from "node:path";
10647
10898
  function csvTargetOf(header, mapping) {
10648
10899
  if (mapping.dropped[header] !== "reserved_name") return void 0;
10649
10900
  const key = normalizeVariableName(header);
@@ -10666,14 +10917,14 @@ function notUploaded(mapping) {
10666
10917
  }
10667
10918
  async function readUpload2(file) {
10668
10919
  if (file === "-") throw usageError("--server-import uploads a file: name the CSV file instead of - (stdin).", { field: "file" });
10669
- const ext = extname2(file).toLowerCase();
10920
+ const ext = extname3(file).toLowerCase();
10670
10921
  if (ext === ".jsonl" || ext === ".ndjson" || ext === ".json") {
10671
10922
  throw usageError("--server-import uploads a CSV file. Convert the file to CSV, or leave --server-import off.", { field: "file" });
10672
10923
  }
10673
- const path = resolve6(file);
10924
+ const path = resolve7(file);
10674
10925
  try {
10675
10926
  const bytes = await readFile7(path);
10676
- const name = ext === ".csv" ? basename3(path) : `${basename3(path, extname2(path))}.csv`;
10927
+ const name = ext === ".csv" ? basename3(path) : `${basename3(path, extname3(path))}.csv`;
10677
10928
  return { bytes, name, path };
10678
10929
  } catch (err) {
10679
10930
  const code = err.code;
@@ -10851,7 +11102,7 @@ var init_import2 = __esm({
10851
11102
  "server-import": { type: "boolean", description: "Upload the CSV as a server import job (up to 100,000 rows; no per-row results)" },
10852
11103
  template: { type: "boolean", description: "Print a sample header and the accepted fields, then exit" },
10853
11104
  timeout: { type: "string", description: "With --server-import: how long to wait for the job (default 30m)" },
10854
- out: OUT_FLAG
11105
+ out: OUT_FLAG2
10855
11106
  },
10856
11107
  examples: [
10857
11108
  "kenso contacts import --campaign 812 --file leads.csv --dry-run",
@@ -11056,7 +11307,7 @@ var init_update = __esm({
11056
11307
  match: { type: "string", description: "id (an id or contactId column) or email (needs --campaign)" },
11057
11308
  campaign: { type: "string", description: "With --match email: the campaign whose contacts the emails are matched in", aliases: ["campaign-id"] },
11058
11309
  map: { type: "string", description: 'Column overrides as JSON, @file or -: {"Pain": "customVariables.pain_point", "Notes": null}' },
11059
- out: OUT_FLAG,
11310
+ out: OUT_FLAG2,
11060
11311
  concurrency: CONCURRENCY_FLAG
11061
11312
  },
11062
11313
  examples: [
@@ -11121,20 +11372,20 @@ var init_update = __esm({
11121
11372
  });
11122
11373
 
11123
11374
  // src/commands/contacts/bulk-store.ts
11124
- import { existsSync as existsSync5 } from "node:fs";
11125
- import { appendFile as appendFile2, readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises";
11375
+ import { existsSync as existsSync6 } from "node:fs";
11376
+ import { appendFile as appendFile2, readFile as readFile8, writeFile as writeFile3 } from "node:fs/promises";
11126
11377
  import { join as join11 } from "node:path";
11127
11378
  function whereDir(env) {
11128
11379
  return join11(runsRoot(env), WHERE_DIR);
11129
11380
  }
11130
- async function unfinishedWhereIds(ctx, command48, args) {
11381
+ async function unfinishedWhereIds(ctx, command49, args) {
11131
11382
  const dir = whereDir(ctx.env);
11132
11383
  const identity = argsIdentity(args);
11133
11384
  const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
11134
11385
  for (const run of await listRuns(ctx.env)) {
11135
- if (run.command !== command48 || run.status === "done" || run.status === "planned") continue;
11386
+ if (run.command !== command49 || run.status === "done" || run.status === "planned") continue;
11136
11387
  if ((run.workspaceId || void 0) !== (workspaceId || void 0) || argsIdentity(run.args) !== identity) continue;
11137
- if (run.inputPath?.startsWith(`${dir}/`) && existsSync5(run.inputPath)) return run.inputPath;
11388
+ if (run.inputPath?.startsWith(`${dir}/`) && existsSync6(run.inputPath)) return run.inputPath;
11138
11389
  }
11139
11390
  return void 0;
11140
11391
  }
@@ -11142,7 +11393,7 @@ async function saveWhereIds(ctx, kind, ids2) {
11142
11393
  const dir = whereDir(ctx.env);
11143
11394
  ensurePrivateDir2(dir);
11144
11395
  const path = join11(dir, `${kind}-${Date.now()}-${newRunId().slice(2)}.txt`);
11145
- await writeFile2(path, ids2.map((id) => `${id}
11396
+ await writeFile3(path, ids2.map((id) => `${id}
11146
11397
  `).join(""), { mode: 384 });
11147
11398
  return path;
11148
11399
  }
@@ -11188,7 +11439,7 @@ __export(bulk_ids_exports, {
11188
11439
  resume: () => resume
11189
11440
  });
11190
11441
  import { createHash as createHash4 } from "node:crypto";
11191
- import { resolve as resolve7 } from "node:path";
11442
+ import { resolve as resolve8 } from "node:path";
11192
11443
  import { Readable } from "node:stream";
11193
11444
  function idItems(raw) {
11194
11445
  const items = [];
@@ -11220,7 +11471,7 @@ async function idsFromFile(ctx, path) {
11220
11471
  input = { path: "-", sha256: createHash4("sha256").update(text4).digest("hex") };
11221
11472
  } else {
11222
11473
  ids2 = await readIds(path);
11223
- input = { path: resolve7(path), sha256: await fileSha256(path) };
11474
+ input = { path: resolve8(path), sha256: await fileSha256(path) };
11224
11475
  }
11225
11476
  return { ...idItems(ids2), source: "ids", input };
11226
11477
  }
@@ -11278,14 +11529,14 @@ async function idsFromRun(ctx, runId) {
11278
11529
  return { ...idItems(ids2), source: "run" };
11279
11530
  }
11280
11531
  async function collectIds(ctx, flags, kind, dryRun2) {
11281
- const command48 = `kenso contacts ${kind}`;
11532
+ const command49 = `kenso contacts ${kind}`;
11282
11533
  const ids2 = stringFlag2(flags, "ids");
11283
11534
  const where = kind === "restore" ? void 0 : stringFlag2(flags, "where");
11284
11535
  const run = kind === "restore" ? stringFlag2(flags, "run") : void 0;
11285
11536
  const given = [ids2, where, run].filter((v) => v !== void 0).length;
11286
11537
  if (given !== 1) {
11287
11538
  const choices = kind === "restore" ? "--ids <file|-> or --run <runId>" : "--ids <file|-> or --where '<json>'";
11288
- throw usageError(`${command48} needs exactly one of ${choices}.`, { field: "ids", next: `${command48} --help` });
11539
+ throw usageError(`${command49} needs exactly one of ${choices}.`, { field: "ids", next: `${command49} --help` });
11289
11540
  }
11290
11541
  if (ids2 !== void 0) return idsFromFile(ctx, ids2);
11291
11542
  if (where !== void 0) return idsFromWhere(ctx, kind, flags, where, dryRun2);
@@ -11326,7 +11577,7 @@ function bulkCommand(kind) {
11326
11577
  if (kind === "restore") flags.run = { type: "string", description: "Restore what an earlier contacts remove run removed" };
11327
11578
  else flags.where = { type: "string", description: "contacts search filters as JSON, @file or - (the body of POST /v1/contacts/search: campaignIds, q matches names and emails, filters match fields such as ContactCompany.Name). Its dry-run plan shows the count and first ids: check the match there, never with a search or list first" };
11328
11579
  if (kind === "remove") flags.confirm = { type: "string", description: "Required to remove more than 1,000 contacts: the exact count" };
11329
- flags.out = OUT_FLAG;
11580
+ flags.out = OUT_FLAG2;
11330
11581
  flags.concurrency = CONCURRENCY_FLAG;
11331
11582
  return {
11332
11583
  resource: "contacts",
@@ -11486,7 +11737,7 @@ function tagCommand(kind) {
11486
11737
  flags: {
11487
11738
  tag: { type: "string", description: "The tag id (see kenso tags list)", aliases: ["tag-id"] },
11488
11739
  ids: { type: "string", description: "Contact ids: one per line, or a CSV/JSONL with an id column; - for stdin" },
11489
- out: OUT_FLAG,
11740
+ out: OUT_FLAG2,
11490
11741
  concurrency: CONCURRENCY_FLAG
11491
11742
  },
11492
11743
  examples: [`kenso contacts ${kind} --tag 31 --ids ids.txt --dry-run`, `kenso contacts ${kind} --tag 31 --ids ids.txt --yes`],
@@ -11539,8 +11790,7 @@ __export(export_exports, {
11539
11790
  default: () => export_default,
11540
11791
  exportIdOf: () => exportIdOf
11541
11792
  });
11542
- import { writeFile as writeFile3 } from "node:fs/promises";
11543
- import { resolve as resolve8 } from "node:path";
11793
+ import { extname as extname4 } from "node:path";
11544
11794
  function idText3(value) {
11545
11795
  return typeof value === "number" || typeof value === "string" && value !== "" ? String(value) : void 0;
11546
11796
  }
@@ -11567,25 +11817,16 @@ function countRows(csv) {
11567
11817
  return Math.max(0, records.length - 1);
11568
11818
  }
11569
11819
  async function download(ctx, job, exportId, out) {
11570
- const res = await ctx.client.request({ method: "GET", path: contentPath(ctx, job, exportId), headers: { Accept: "text/csv, */*" }, signal: ctx.signal });
11820
+ const res = await ctx.client.request({ method: "GET", path: contentPath(ctx, job, exportId), headers: { Accept: "text/csv, application/zip, */*" }, signal: ctx.signal });
11571
11821
  const type = res.headers.get("content-type") ?? "";
11572
11822
  if (type.includes("zip")) {
11573
- throw new KensoError({
11574
- code: "unexpected_response",
11575
- message: "The export came back as a ZIP file, which this command cannot save.",
11576
- exitCode: ExitCode.Error,
11577
- hint: `Download it with: kenso contact-exports content --export-id ${exportId}`
11578
- });
11823
+ const bytes = res.raw ?? (Buffer.isBuffer(res.body) ? res.body : Buffer.alloc(0));
11824
+ const path = await saveFile(out, bytes);
11825
+ if (extname4(out).toLowerCase() !== ".zip") ctx.output.warn(`the export is a ZIP of CSV files (one per segment); ${out} holds the ZIP as it came.`);
11826
+ return { format: "zip", bytes: bytes.length, path };
11579
11827
  }
11580
11828
  const body2 = typeof res.body === "string" ? res.body : res.body === null ? "" : JSON.stringify(res.body);
11581
- const path = resolve8(out);
11582
- try {
11583
- await writeFile3(path, body2, { mode: 384 });
11584
- } catch (err) {
11585
- const code = err.code;
11586
- throw new KensoError({ code: "file_unwritable", message: `Cannot write ${out}${code ? ` (${code})` : ""}.`, exitCode: ExitCode.Usage, field: "out" });
11587
- }
11588
- return { rows: countRows(body2), path };
11829
+ return { format: "csv", rows: countRows(body2), path: await saveFile(out, res.raw ?? Buffer.from(body2, "utf8")) };
11589
11830
  }
11590
11831
  var COMMAND4, JOB_TYPE, DEFAULT_TIMEOUT2, CONTENT_PATH, command17, export_default;
11591
11832
  var init_export = __esm({
@@ -11596,6 +11837,7 @@ var init_export = __esm({
11596
11837
  init_errors();
11597
11838
  init_exit_codes();
11598
11839
  init_http();
11840
+ init_transfer();
11599
11841
  init_wait();
11600
11842
  init_common();
11601
11843
  COMMAND4 = "kenso contacts export";
@@ -11610,7 +11852,7 @@ var init_export = __esm({
11610
11852
  description: "Creates a contact export of the campaign (POST /v1/contact-exports, kind contacts), waits for the contact_export job, then downloads GET /v1/contact-exports/{exportId}/content to --out. Without --out it prints the job (add --wait to wait for it).",
11611
11853
  flags: {
11612
11854
  campaign: { type: "string", description: "The campaign id", aliases: ["campaign-id"] },
11613
- out: { type: "string", description: "Write the CSV to this file (waits for the job)" },
11855
+ out: { type: "string", description: "Write the CSV (a ZIP of one CSV per segment for an audience-based campaign) to this file; waits for the job" },
11614
11856
  wait: { type: "boolean", description: "Wait for the export job to finish (on when --out is set)" },
11615
11857
  timeout: { type: "string", description: "How long to wait for the job (default 30m)" }
11616
11858
  },
@@ -11655,8 +11897,9 @@ var init_export = __esm({
11655
11897
  ctx.output.object({ exportId, jobId, status: job.status, downloadUrl: job.downloadUrl ?? `/v1/contact-exports/${exportId}/content` });
11656
11898
  return ExitCode.Ok;
11657
11899
  }
11658
- const { rows, path } = await download(ctx, job, exportId, out);
11659
- ctx.output.object({ exportId, jobId, status: job.status, rows, out: path });
11900
+ const saved = await download(ctx, job, exportId, out);
11901
+ const counts2 = saved.format === "zip" ? { format: "zip", bytes: saved.bytes } : { rows: saved.rows };
11902
+ ctx.output.object({ exportId, jobId, status: job.status, ...counts2, out: saved.path });
11660
11903
  return ExitCode.Ok;
11661
11904
  }
11662
11905
  };
@@ -11765,7 +12008,13 @@ function detailOf(entry) {
11765
12008
  operationIds: ids2,
11766
12009
  flags: flagsOf(entry),
11767
12010
  positionals: (spec?.positionals ?? []).map((p) => ({ name: p.name, required: p.required === true, description: p.description })),
11768
- body: body2 ? { format: body2.format, ...body2.schema !== void 0 ? { schema: body2.schema } : {}, ...body2.schemaTruncated ? { schemaTruncated: true } : {} } : null,
12011
+ body: body2 ? {
12012
+ format: body2.format,
12013
+ // An upload that also takes JSON: without --file the command sends JSON (DEV-11921).
12014
+ ...body2.json ? { json: true } : {},
12015
+ ...body2.schema !== void 0 ? { schema: body2.schema } : {},
12016
+ ...body2.schemaTruncated ? { schemaTruncated: true } : {}
12017
+ } : null,
11769
12018
  list: op?.list ?? false,
11770
12019
  examples: entry.op ? operationExamples(entry.op) : spec?.examples ?? [],
11771
12020
  beta: entry.gates !== void 0,
@@ -11773,6 +12022,7 @@ function detailOf(entry) {
11773
12022
  dryRun: entry.op !== void 0 || spec?.dryRun === true
11774
12023
  };
11775
12024
  if (entry.gates) out.featureGates = entry.gates;
12025
+ if (entry.op?.download) out.download = entry.op.download;
11776
12026
  return out;
11777
12027
  }
11778
12028
  function unknown(words) {
@@ -12594,19 +12844,108 @@ var init_people = __esm({
12594
12844
  }
12595
12845
  });
12596
12846
 
12847
+ // src/commands/reports/run.ts
12848
+ var run_exports2 = {};
12849
+ __export(run_exports2, {
12850
+ default: () => run_default
12851
+ });
12852
+ var REPORTS, command26, run_default;
12853
+ var init_run2 = __esm({
12854
+ "src/commands/reports/run.ts"() {
12855
+ "use strict";
12856
+ init_errors();
12857
+ init_exit_codes();
12858
+ init_http();
12859
+ REPORTS = ["pipeline_by_stage", "won_by_month", "stage_conversion", "time_in_stage", "won_by_source_campaign", "activity_by_member"];
12860
+ command26 = {
12861
+ resource: "reports",
12862
+ action: "run",
12863
+ summary: "Run a stock pipeline report and print its table",
12864
+ description: `Reads GET /v1/reports/{reportKey} and prints one row per bucket: the bucket's label under the dimension's name (stage, closedAt, sourceCampaignId) and each measure under its key (count, sumAmount, weightedAmount, avgAmount). Amounts are in the workspace currency. The report's title, its finding, the days it covers and the totals are printed to stderr. --full prints the whole answer as one object: headline, finding, stats, chart, the stored query, and result with each bucket's filter for opportunities search. Reports: ${REPORTS.join(", ")}; kenso reports list prints the ones your workspace has now.`,
12865
+ flags: {
12866
+ period: {
12867
+ type: "string",
12868
+ description: "this_month, last_month, this_quarter (default), last_quarter, this_year, last_year, last_30_days, last_90_days, a month (2026-03), a quarter (2026-Q1), a year (2026) or a day range (2026-03-01..2026-03-31)"
12869
+ },
12870
+ owner: { type: "string", description: "Only this member's deals (a member id)", aliases: ["owner-member-id"] },
12871
+ "time-zone": { type: "string", description: "IANA zone days start in when you have no app time zone (default UTC)" },
12872
+ full: { type: "boolean", description: "Print the API's whole answer instead of the table" }
12873
+ },
12874
+ positionals: [{ name: "report", required: true, description: `A report key from kenso reports list, such as ${REPORTS.join(", ")}` }],
12875
+ examples: [
12876
+ "kenso reports run pipeline_by_stage",
12877
+ "kenso reports run won_by_month --period this_year --owner 41",
12878
+ "kenso reports run won_by_source_campaign --period 2026-Q4 --full"
12879
+ ],
12880
+ beta: { featureGates: { all: ["opportunities", "reports"] } },
12881
+ operationIds: ["reports.get"],
12882
+ async run(ctx, { flags, positionals }) {
12883
+ const report2 = (positionals[0] ?? "").trim();
12884
+ if (!/^[a-z][a-z0-9_]*$/.test(report2)) {
12885
+ throw usageError(`"${report2}" is not a report key. Reports: ${REPORTS.join(", ")}.`, { field: "report", next: "kenso reports list" });
12886
+ }
12887
+ const owner = typeof flags.owner === "string" ? flags.owner.trim() : void 0;
12888
+ if (owner !== void 0 && !/^[1-9]\d*$/.test(owner)) {
12889
+ throw usageError(`--owner must be a member id (got "${owner}").`, { field: "owner", next: "kenso members list" });
12890
+ }
12891
+ const res = await ctx.client.request({
12892
+ method: "GET",
12893
+ path: `/v1/reports/${report2}`,
12894
+ query: {
12895
+ period: typeof flags.period === "string" ? flags.period : void 0,
12896
+ ownerMemberId: owner,
12897
+ timeZone: typeof flags["time-zone"] === "string" ? flags["time-zone"] : void 0
12898
+ },
12899
+ signal: ctx.signal
12900
+ });
12901
+ const data = unwrap(res.body);
12902
+ if (flags.full === true) {
12903
+ ctx.output.object(data);
12904
+ return ExitCode.Ok;
12905
+ }
12906
+ const { result } = data;
12907
+ const names = result.dimensions.map((d) => d.field);
12908
+ ctx.output.info(data.title + (data.period ? ` (${data.period.from} to ${data.period.to})` : ""));
12909
+ ctx.output.info(data.finding);
12910
+ ctx.output.info(`Totals (${result.currency}): ${result.measures.map((m) => `${m.key} ${result.totals[m.key] ?? 0}`).join(", ")}`);
12911
+ await ctx.output.list(
12912
+ result.buckets.map((bucket) => ({
12913
+ ...Object.fromEntries(names.map((name, i) => [name, bucket.labels[i] ?? bucket.keys[i] ?? ""])),
12914
+ // A measure a row has no value for (a rate with nothing to divide by) prints as null.
12915
+ ...Object.fromEntries(result.measures.map((m) => [m.key, bucket.values[m.key] ?? null]))
12916
+ }))
12917
+ );
12918
+ return ExitCode.Ok;
12919
+ }
12920
+ };
12921
+ run_default = command26;
12922
+ }
12923
+ });
12924
+
12925
+ // src/commands/reports/index.ts
12926
+ var actions17;
12927
+ var init_reports = __esm({
12928
+ "src/commands/reports/index.ts"() {
12929
+ "use strict";
12930
+ actions17 = {
12931
+ run: () => Promise.resolve().then(() => (init_run2(), run_exports2)).then((m) => m.default)
12932
+ };
12933
+ }
12934
+ });
12935
+
12597
12936
  // src/commands/runs/list.ts
12598
12937
  var list_exports = {};
12599
12938
  __export(list_exports, {
12600
12939
  default: () => list_default
12601
12940
  });
12602
- var command26, list_default;
12941
+ var command27, list_default;
12603
12942
  var init_list = __esm({
12604
12943
  "src/commands/runs/list.ts"() {
12605
12944
  "use strict";
12606
12945
  init_runs();
12607
12946
  init_errors();
12608
12947
  init_exit_codes();
12609
- command26 = {
12948
+ command27 = {
12610
12949
  resource: "runs",
12611
12950
  action: "list",
12612
12951
  summary: "List batch runs, newest first (finds an interrupted run)",
@@ -12627,7 +12966,7 @@ var init_list = __esm({
12627
12966
  return ExitCode.Ok;
12628
12967
  }
12629
12968
  };
12630
- list_default = command26;
12969
+ list_default = command27;
12631
12970
  }
12632
12971
  });
12633
12972
 
@@ -12636,9 +12975,9 @@ var show_exports = {};
12636
12975
  __export(show_exports, {
12637
12976
  default: () => show_default
12638
12977
  });
12639
- import { existsSync as existsSync6, readFileSync as readFileSync9 } from "node:fs";
12978
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "node:fs";
12640
12979
  import { join as join12 } from "node:path";
12641
- var FILES, command27, show_default;
12980
+ var FILES, command28, show_default;
12642
12981
  var init_show = __esm({
12643
12982
  "src/commands/runs/show.ts"() {
12644
12983
  "use strict";
@@ -12653,7 +12992,7 @@ var init_show = __esm({
12653
12992
  ["plan", "plan.json"],
12654
12993
  ["summary", "summary.json"]
12655
12994
  ];
12656
- command27 = {
12995
+ command28 = {
12657
12996
  resource: "runs",
12658
12997
  action: "show",
12659
12998
  summary: "Show one batch run and its files",
@@ -12666,7 +13005,7 @@ var init_show = __esm({
12666
13005
  const files = { dir };
12667
13006
  for (const [key, name] of FILES) {
12668
13007
  const path = join12(dir, name);
12669
- if (existsSync6(path)) files[key] = path;
13008
+ if (existsSync7(path)) files[key] = path;
12670
13009
  }
12671
13010
  let summary;
12672
13011
  if (files.summary) {
@@ -12680,7 +13019,7 @@ var init_show = __esm({
12680
13019
  return ExitCode.Ok;
12681
13020
  }
12682
13021
  };
12683
- show_default = command27;
13022
+ show_default = command28;
12684
13023
  }
12685
13024
  });
12686
13025
 
@@ -12691,7 +13030,7 @@ __export(resume_exports, {
12691
13030
  resumeArgv: () => resumeArgv
12692
13031
  });
12693
13032
  import { createHash as createHash5 } from "node:crypto";
12694
- import { existsSync as existsSync7 } from "node:fs";
13033
+ import { existsSync as existsSync8 } from "node:fs";
12695
13034
  import { readFile as readFile9 } from "node:fs/promises";
12696
13035
  import { resolve as resolve9 } from "node:path";
12697
13036
  function kebab(key) {
@@ -12739,14 +13078,14 @@ function resumeArgv(run, globals = {}) {
12739
13078
  async function sha256(path) {
12740
13079
  return createHash5("sha256").update(await readFile9(path)).digest("hex");
12741
13080
  }
12742
- var SKIPPED_KEYS, command28, resume_default;
13081
+ var SKIPPED_KEYS, command29, resume_default;
12743
13082
  var init_resume = __esm({
12744
13083
  "src/commands/runs/resume.ts"() {
12745
13084
  "use strict";
12746
13085
  init_runs();
12747
13086
  init_errors();
12748
13087
  SKIPPED_KEYS = /* @__PURE__ */ new Set(["positionals", "yes", "dryRun", "dry-run", "help", "version"]);
12749
- command28 = {
13088
+ command29 = {
12750
13089
  resource: "runs",
12751
13090
  action: "resume",
12752
13091
  summary: "Continue an interrupted batch run (its command with --yes, no dry run)",
@@ -12771,7 +13110,7 @@ var init_resume = __esm({
12771
13110
  });
12772
13111
  }
12773
13112
  if (run.inputPath !== void 0) {
12774
- if (!existsSync7(run.inputPath)) {
13113
+ if (!existsSync8(run.inputPath)) {
12775
13114
  throw usageError(`The input file of run ${run.runId} is gone: ${run.inputPath}.`, { field: "file", next });
12776
13115
  }
12777
13116
  if (await sha256(run.inputPath) !== run.inputSha256) {
@@ -12786,7 +13125,7 @@ var init_resume = __esm({
12786
13125
  if (ctx.env.KENSO_CONFIG_DIR?.trim()) env.KENSO_CONFIG_DIR = resolve9(ctx.env.KENSO_CONFIG_DIR.trim());
12787
13126
  const previousCwd = process.cwd();
12788
13127
  if (run.cwd && run.cwd !== previousCwd) {
12789
- if (!existsSync7(run.cwd)) throw usageError(`Run ${run.runId} started in ${run.cwd}, which no longer exists.`, { next });
13128
+ if (!existsSync8(run.cwd)) throw usageError(`Run ${run.runId} started in ${run.cwd}, which no longer exists.`, { next });
12790
13129
  process.chdir(run.cwd);
12791
13130
  }
12792
13131
  try {
@@ -12801,16 +13140,16 @@ var init_resume = __esm({
12801
13140
  }
12802
13141
  }
12803
13142
  };
12804
- resume_default = command28;
13143
+ resume_default = command29;
12805
13144
  }
12806
13145
  });
12807
13146
 
12808
13147
  // src/commands/runs/index.ts
12809
- var actions17;
13148
+ var actions18;
12810
13149
  var init_runs2 = __esm({
12811
13150
  "src/commands/runs/index.ts"() {
12812
13151
  "use strict";
12813
- actions17 = {
13152
+ actions18 = {
12814
13153
  list: () => Promise.resolve().then(() => (init_list(), list_exports)).then((m) => m.default),
12815
13154
  show: () => Promise.resolve().then(() => (init_show(), show_exports)).then((m) => m.default),
12816
13155
  resume: () => Promise.resolve().then(() => (init_resume(), resume_exports)).then((m) => m.default)
@@ -12909,7 +13248,7 @@ var create_exports = {};
12909
13248
  __export(create_exports, {
12910
13249
  default: () => create_default
12911
13250
  });
12912
- var command29, create_default;
13251
+ var command30, create_default;
12913
13252
  var init_create = __esm({
12914
13253
  "src/commands/sandbox/create.ts"() {
12915
13254
  "use strict";
@@ -12917,7 +13256,7 @@ var init_create = __esm({
12917
13256
  init_exit_codes();
12918
13257
  init_http();
12919
13258
  init_shared();
12920
- command29 = {
13259
+ command30 = {
12921
13260
  resource: "sandbox",
12922
13261
  action: "create",
12923
13262
  summary: "Create your developer sandbox and save its test key as the sandbox profile",
@@ -12959,7 +13298,7 @@ var init_create = __esm({
12959
13298
  return ExitCode.Ok;
12960
13299
  }
12961
13300
  };
12962
- create_default = command29;
13301
+ create_default = command30;
12963
13302
  }
12964
13303
  });
12965
13304
 
@@ -12968,7 +13307,7 @@ var delete_exports = {};
12968
13307
  __export(delete_exports, {
12969
13308
  default: () => delete_default
12970
13309
  });
12971
- var command30, delete_default;
13310
+ var command31, delete_default;
12972
13311
  var init_delete = __esm({
12973
13312
  "src/commands/sandbox/delete.ts"() {
12974
13313
  "use strict";
@@ -12976,7 +13315,7 @@ var init_delete = __esm({
12976
13315
  init_confirm();
12977
13316
  init_exit_codes();
12978
13317
  init_shared();
12979
- command30 = {
13318
+ command31 = {
12980
13319
  resource: "sandbox",
12981
13320
  action: "delete",
12982
13321
  summary: "Delete your sandbox and its test keys",
@@ -13003,7 +13342,7 @@ var init_delete = __esm({
13003
13342
  return ExitCode.Ok;
13004
13343
  }
13005
13344
  };
13006
- delete_default = command30;
13345
+ delete_default = command31;
13007
13346
  }
13008
13347
  });
13009
13348
 
@@ -13012,14 +13351,14 @@ var key_exports = {};
13012
13351
  __export(key_exports, {
13013
13352
  default: () => key_default
13014
13353
  });
13015
- var command31, key_default;
13354
+ var command32, key_default;
13016
13355
  var init_key = __esm({
13017
13356
  "src/commands/sandbox/key.ts"() {
13018
13357
  "use strict";
13019
13358
  init_exit_codes();
13020
13359
  init_http();
13021
13360
  init_shared();
13022
- command31 = {
13361
+ command32 = {
13023
13362
  resource: "sandbox",
13024
13363
  action: "key",
13025
13364
  summary: "Create a new test key for your sandbox and save it as the sandbox profile",
@@ -13039,7 +13378,7 @@ var init_key = __esm({
13039
13378
  return ExitCode.Ok;
13040
13379
  }
13041
13380
  };
13042
- key_default = command31;
13381
+ key_default = command32;
13043
13382
  }
13044
13383
  });
13045
13384
 
@@ -13048,13 +13387,13 @@ var list_exports2 = {};
13048
13387
  __export(list_exports2, {
13049
13388
  default: () => list_default2
13050
13389
  });
13051
- var command32, list_default2;
13390
+ var command33, list_default2;
13052
13391
  var init_list2 = __esm({
13053
13392
  "src/commands/sandbox/list.ts"() {
13054
13393
  "use strict";
13055
13394
  init_exit_codes();
13056
13395
  init_shared();
13057
- command32 = {
13396
+ command33 = {
13058
13397
  resource: "sandbox",
13059
13398
  action: "list",
13060
13399
  summary: "List your developer sandbox",
@@ -13070,7 +13409,7 @@ var init_list2 = __esm({
13070
13409
  return ExitCode.Ok;
13071
13410
  }
13072
13411
  };
13073
- list_default2 = command32;
13412
+ list_default2 = command33;
13074
13413
  }
13075
13414
  });
13076
13415
 
@@ -13079,14 +13418,14 @@ var reset_exports = {};
13079
13418
  __export(reset_exports, {
13080
13419
  default: () => reset_default
13081
13420
  });
13082
- var command33, reset_default;
13421
+ var command34, reset_default;
13083
13422
  var init_reset = __esm({
13084
13423
  "src/commands/sandbox/reset.ts"() {
13085
13424
  "use strict";
13086
13425
  init_exit_codes();
13087
13426
  init_http();
13088
13427
  init_shared();
13089
- command33 = {
13428
+ command34 = {
13090
13429
  resource: "sandbox",
13091
13430
  action: "reset",
13092
13431
  summary: "Reset your sandbox to its seed data",
@@ -13104,16 +13443,16 @@ var init_reset = __esm({
13104
13443
  return ExitCode.Ok;
13105
13444
  }
13106
13445
  };
13107
- reset_default = command33;
13446
+ reset_default = command34;
13108
13447
  }
13109
13448
  });
13110
13449
 
13111
13450
  // src/commands/sandbox/index.ts
13112
- var actions18;
13451
+ var actions19;
13113
13452
  var init_sandbox2 = __esm({
13114
13453
  "src/commands/sandbox/index.ts"() {
13115
13454
  "use strict";
13116
- actions18 = {
13455
+ actions19 = {
13117
13456
  create: () => Promise.resolve().then(() => (init_create(), create_exports)).then((m) => m.default),
13118
13457
  delete: () => Promise.resolve().then(() => (init_delete(), delete_exports)).then((m) => m.default),
13119
13458
  key: () => Promise.resolve().then(() => (init_key(), key_exports)).then((m) => m.default),
@@ -13124,11 +13463,11 @@ var init_sandbox2 = __esm({
13124
13463
  });
13125
13464
 
13126
13465
  // src/commands/skill/index.ts
13127
- var actions19;
13466
+ var actions20;
13128
13467
  var init_skill = __esm({
13129
13468
  "src/commands/skill/index.ts"() {
13130
13469
  "use strict";
13131
- actions19 = {
13470
+ actions20 = {
13132
13471
  install: () => Promise.resolve().then(() => (init_install(), install_exports)).then((m) => m.default)
13133
13472
  };
13134
13473
  }
@@ -13165,7 +13504,7 @@ var init_common2 = __esm({
13165
13504
 
13166
13505
  // src/commands/studio/folder.ts
13167
13506
  import { readdir as readdir2, readFile as readFile10, stat as stat2 } from "node:fs/promises";
13168
- import { extname as extname3, isAbsolute, join as join13, relative, resolve as resolve10, sep } from "node:path";
13507
+ import { extname as extname5, isAbsolute, join as join13, relative, resolve as resolve10, sep } from "node:path";
13169
13508
  function textOf2(bytes) {
13170
13509
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
13171
13510
  try {
@@ -13213,7 +13552,7 @@ function safeJoin(root2, bundlePath) {
13213
13552
  return target;
13214
13553
  }
13215
13554
  function contentTypeOf(path) {
13216
- return CONTENT_TYPES[extname3(path).toLowerCase()] ?? "application/octet-stream";
13555
+ return CONTENT_TYPES2[extname5(path).toLowerCase()] ?? "application/octet-stream";
13217
13556
  }
13218
13557
  async function mapLimit(items, limit, fn) {
13219
13558
  const out = new Array(items.length);
@@ -13233,7 +13572,7 @@ async function mapLimit(items, limit, fn) {
13233
13572
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
13234
13573
  return out;
13235
13574
  }
13236
- var TEXT_MAX_BYTES, UPLOAD_MAX_BYTES, utf8, CONTENT_TYPES;
13575
+ var TEXT_MAX_BYTES, UPLOAD_MAX_BYTES, utf8, CONTENT_TYPES2;
13237
13576
  var init_folder = __esm({
13238
13577
  "src/commands/studio/folder.ts"() {
13239
13578
  "use strict";
@@ -13242,7 +13581,7 @@ var init_folder = __esm({
13242
13581
  TEXT_MAX_BYTES = 1024 * 1024;
13243
13582
  UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
13244
13583
  utf8 = new TextDecoder("utf-8", { fatal: true });
13245
- CONTENT_TYPES = {
13584
+ CONTENT_TYPES2 = {
13246
13585
  ".png": "image/png",
13247
13586
  ".jpg": "image/jpeg",
13248
13587
  ".jpeg": "image/jpeg",
@@ -13346,7 +13685,7 @@ async function download2(url, path, sha2563, signal) {
13346
13685
  return bytes;
13347
13686
  }
13348
13687
  var PARALLEL_TRANSFERS;
13349
- var init_transfer = __esm({
13688
+ var init_transfer2 = __esm({
13350
13689
  "src/commands/studio/transfer.ts"() {
13351
13690
  "use strict";
13352
13691
  init_errors();
@@ -13364,7 +13703,7 @@ __export(pull_exports, {
13364
13703
  });
13365
13704
  import { mkdir, writeFile as writeFile4 } from "node:fs/promises";
13366
13705
  import { dirname as dirname2, resolve as resolve11 } from "node:path";
13367
- var command34, pull_default;
13706
+ var command35, pull_default;
13368
13707
  var init_pull = __esm({
13369
13708
  "src/commands/studio/pull.ts"() {
13370
13709
  "use strict";
@@ -13373,8 +13712,8 @@ var init_pull = __esm({
13373
13712
  init_http();
13374
13713
  init_common2();
13375
13714
  init_folder();
13376
- init_transfer();
13377
- command34 = {
13715
+ init_transfer2();
13716
+ command35 = {
13378
13717
  resource: "studio",
13379
13718
  action: "pull",
13380
13719
  summary: "Write a template version's files to a folder",
@@ -13421,7 +13760,7 @@ var init_pull = __esm({
13421
13760
  return ExitCode.Ok;
13422
13761
  }
13423
13762
  };
13424
- pull_default = command34;
13763
+ pull_default = command35;
13425
13764
  }
13426
13765
  });
13427
13766
 
@@ -13445,7 +13784,7 @@ var init_read = __esm({
13445
13784
  "use strict";
13446
13785
  init_errors();
13447
13786
  init_folder();
13448
- init_transfer();
13787
+ init_transfer2();
13449
13788
  }
13450
13789
  });
13451
13790
 
@@ -13454,7 +13793,7 @@ var push_exports = {};
13454
13793
  __export(push_exports, {
13455
13794
  default: () => push_default
13456
13795
  });
13457
- var BUILT_BY, DEFAULT_MESSAGE, command35, push_default;
13796
+ var BUILT_BY, DEFAULT_MESSAGE, command36, push_default;
13458
13797
  var init_push = __esm({
13459
13798
  "src/commands/studio/push.ts"() {
13460
13799
  "use strict";
@@ -13466,7 +13805,7 @@ var init_push = __esm({
13466
13805
  init_read();
13467
13806
  BUILT_BY = "customer_agent";
13468
13807
  DEFAULT_MESSAGE = "Pushed with the Kenso CLI";
13469
- command35 = {
13808
+ command36 = {
13470
13809
  resource: "studio",
13471
13810
  action: "push",
13472
13811
  summary: "Save a folder's files to a template's draft and print the validation",
@@ -13558,7 +13897,7 @@ var init_push = __esm({
13558
13897
  );
13559
13898
  }
13560
13899
  };
13561
- push_default = command35;
13900
+ push_default = command36;
13562
13901
  }
13563
13902
  });
13564
13903
 
@@ -13567,7 +13906,7 @@ var validate_exports = {};
13567
13906
  __export(validate_exports, {
13568
13907
  default: () => validate_default
13569
13908
  });
13570
- var command36, validate_default;
13909
+ var command37, validate_default;
13571
13910
  var init_validate = __esm({
13572
13911
  "src/commands/studio/validate.ts"() {
13573
13912
  "use strict";
@@ -13576,7 +13915,7 @@ var init_validate = __esm({
13576
13915
  init_columns();
13577
13916
  init_common2();
13578
13917
  init_read();
13579
- command36 = {
13918
+ command37 = {
13580
13919
  resource: "studio",
13581
13920
  action: "validate",
13582
13921
  summary: "Validate a folder's files against a template without saving them",
@@ -13605,7 +13944,7 @@ var init_validate = __esm({
13605
13944
  throw validationFailed(validation, "The files have validation errors", commandLine2(ctx, "studio validate", args));
13606
13945
  }
13607
13946
  };
13608
- validate_default = command36;
13947
+ validate_default = command37;
13609
13948
  }
13610
13949
  });
13611
13950
 
@@ -13654,7 +13993,7 @@ function accountIds(value) {
13654
13993
  }
13655
13994
  return ids2.map(Number);
13656
13995
  }
13657
- var SHOWN, command37, preview_default;
13996
+ var SHOWN, command38, preview_default;
13658
13997
  var init_preview = __esm({
13659
13998
  "src/commands/studio/preview.ts"() {
13660
13999
  "use strict";
@@ -13666,7 +14005,7 @@ var init_preview = __esm({
13666
14005
  init_common2();
13667
14006
  init_folder();
13668
14007
  SHOWN = 5;
13669
- command37 = {
14008
+ command38 = {
13670
14009
  resource: "studio",
13671
14010
  action: "preview",
13672
14011
  summary: "Render a saved version for up to 3 accounts; for local edits, studio push them to the draft first",
@@ -13715,7 +14054,7 @@ var init_preview = __esm({
13715
14054
  return ExitCode.Ok;
13716
14055
  }
13717
14056
  };
13718
- preview_default = command37;
14057
+ preview_default = command38;
13719
14058
  }
13720
14059
  });
13721
14060
 
@@ -13916,7 +14255,7 @@ function estimateOutput(templateId, target, estimate2) {
13916
14255
  ...target.campaignId !== void 0 ? { estimateNote: "An upper bound: it counts one page per lead, and a campaign run builds one page per company." } : {}
13917
14256
  };
13918
14257
  }
13919
- var COMMAND6, sha2562, command38, fill_default;
14258
+ var COMMAND6, sha2562, command39, fill_default;
13920
14259
  var init_fill = __esm({
13921
14260
  "src/commands/studio/fill.ts"() {
13922
14261
  "use strict";
@@ -13932,7 +14271,7 @@ var init_fill = __esm({
13932
14271
  init_fill_runs();
13933
14272
  COMMAND6 = "studio fill";
13934
14273
  sha2562 = (data) => createHash8("sha256").update(data).digest("hex");
13935
- command38 = {
14274
+ command39 = {
13936
14275
  resource: "studio",
13937
14276
  action: "fill",
13938
14277
  summary: "Fill a template on many accounts or campaign leads (estimate first)",
@@ -13992,16 +14331,16 @@ var init_fill = __esm({
13992
14331
  return outcome.exitCode;
13993
14332
  }
13994
14333
  };
13995
- fill_default = command38;
14334
+ fill_default = command39;
13996
14335
  }
13997
14336
  });
13998
14337
 
13999
14338
  // src/commands/studio/index.ts
14000
- var actions20;
14339
+ var actions21;
14001
14340
  var init_studio2 = __esm({
14002
14341
  "src/commands/studio/index.ts"() {
14003
14342
  "use strict";
14004
- actions20 = {
14343
+ actions21 = {
14005
14344
  pull: () => Promise.resolve().then(() => (init_pull(), pull_exports)).then((m) => m.default),
14006
14345
  push: () => Promise.resolve().then(() => (init_push(), push_exports)).then((m) => m.default),
14007
14346
  validate: () => Promise.resolve().then(() => (init_validate(), validate_exports)).then((m) => m.default),
@@ -14143,7 +14482,7 @@ function readBody(req) {
14143
14482
  function reply(res, status, body2) {
14144
14483
  res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body2));
14145
14484
  }
14146
- var MIN_POLL_MS, MAX_POLL_MS, MAX_TRIGGER_BYTES, command39, listen_default;
14485
+ var MIN_POLL_MS, MAX_POLL_MS, MAX_TRIGGER_BYTES, command40, listen_default;
14147
14486
  var init_listen = __esm({
14148
14487
  "src/commands/webhooks/listen.ts"() {
14149
14488
  "use strict";
@@ -14154,7 +14493,7 @@ var init_listen = __esm({
14154
14493
  MIN_POLL_MS = 1e3;
14155
14494
  MAX_POLL_MS = 6e4;
14156
14495
  MAX_TRIGGER_BYTES = 1e6;
14157
- command39 = {
14496
+ command40 = {
14158
14497
  resource: "webhooks",
14159
14498
  action: "listen",
14160
14499
  summary: "Stream the workspace's events and forward them, signed, to a local handler",
@@ -14260,7 +14599,7 @@ var init_listen = __esm({
14260
14599
  return ExitCode.Ok;
14261
14600
  }
14262
14601
  };
14263
- listen_default = command39;
14602
+ listen_default = command40;
14264
14603
  }
14265
14604
  });
14266
14605
 
@@ -14279,7 +14618,7 @@ function notRunning() {
14279
14618
  next: LISTEN_NEXT
14280
14619
  });
14281
14620
  }
14282
- var LISTEN_NEXT, command40, trigger_default;
14621
+ var LISTEN_NEXT, command41, trigger_default;
14283
14622
  var init_trigger = __esm({
14284
14623
  "src/commands/webhooks/trigger.ts"() {
14285
14624
  "use strict";
@@ -14288,7 +14627,7 @@ var init_trigger = __esm({
14288
14627
  init_http();
14289
14628
  init_local();
14290
14629
  LISTEN_NEXT = "kenso webhooks listen --forward-to http://localhost:3000/hook";
14291
- command40 = {
14630
+ command41 = {
14292
14631
  resource: "webhooks",
14293
14632
  action: "trigger",
14294
14633
  summary: "Send a sample event of one type through the running kenso webhooks listen",
@@ -14345,16 +14684,16 @@ var init_trigger = __esm({
14345
14684
  return ExitCode.Ok;
14346
14685
  }
14347
14686
  };
14348
- trigger_default = command40;
14687
+ trigger_default = command41;
14349
14688
  }
14350
14689
  });
14351
14690
 
14352
14691
  // src/commands/webhooks/index.ts
14353
- var actions21;
14692
+ var actions22;
14354
14693
  var init_webhooks2 = __esm({
14355
14694
  "src/commands/webhooks/index.ts"() {
14356
14695
  "use strict";
14357
- actions21 = {
14696
+ actions22 = {
14358
14697
  listen: () => Promise.resolve().then(() => (init_listen(), listen_exports)).then((m) => m.default),
14359
14698
  trigger: () => Promise.resolve().then(() => (init_trigger(), trigger_exports)).then((m) => m.default)
14360
14699
  };
@@ -14517,7 +14856,7 @@ async function releaseClaim(ctx, claimId, headers = {}) {
14517
14856
  const data = unwrap(res.body);
14518
14857
  return isRecord8(data) && typeof data.released === "number" ? data.released : 0;
14519
14858
  }
14520
- var BETA, KINDS_TEXT, MAX_PER_FILE, MIN_LEASE_MINUTES, MAX_LEASE_MINUTES, KIND_FLAG, CAMPAIGN_FLAG, LIVE_ONLY_FLAG, PER_FILE_FLAG, LEASE_FLAG, OUT_FLAG2, UNTIL_DONE, WORK_TIMING, MAX_UNAVAILABLE_WAITS;
14859
+ var BETA, KINDS_TEXT, MAX_PER_FILE, MIN_LEASE_MINUTES, MAX_LEASE_MINUTES, KIND_FLAG, CAMPAIGN_FLAG, LIVE_ONLY_FLAG, PER_FILE_FLAG, LEASE_FLAG, OUT_FLAG3, UNTIL_DONE, WORK_TIMING, MAX_UNAVAILABLE_WAITS;
14521
14860
  var init_common3 = __esm({
14522
14861
  "src/commands/work/common.ts"() {
14523
14862
  "use strict";
@@ -14537,7 +14876,7 @@ var init_common3 = __esm({
14537
14876
  };
14538
14877
  PER_FILE_FLAG = { type: "string", default: "10", description: "Items per work file (one claim), 1-50" };
14539
14878
  LEASE_FLAG = { type: "string", default: "30m", description: "How long a claim holds its items, 5m to 4h; unanswered items go back after it" };
14540
- OUT_FLAG2 = { type: "string", description: "Keep the files in this directory instead of a new folder under the runs directory" };
14879
+ OUT_FLAG3 = { type: "string", description: "Keep the files in this directory instead of a new folder under the runs directory" };
14541
14880
  UNTIL_DONE = new AbortController().signal;
14542
14881
  WORK_TIMING = { watchMs: 6e4, unavailableMs: 3e4, retryMs: 2e3 };
14543
14882
  MAX_UNAVAILABLE_WAITS = 10;
@@ -14549,14 +14888,14 @@ var status_exports3 = {};
14549
14888
  __export(status_exports3, {
14550
14889
  default: () => status_default3
14551
14890
  });
14552
- var command41, status_default3;
14891
+ var command42, status_default3;
14553
14892
  var init_status3 = __esm({
14554
14893
  "src/commands/work/status.ts"() {
14555
14894
  "use strict";
14556
14895
  init_exit_codes();
14557
14896
  init_http();
14558
14897
  init_common3();
14559
- command41 = {
14898
+ command42 = {
14560
14899
  resource: "work",
14561
14900
  action: "status",
14562
14901
  summary: "Show the Kenso AI work waiting for your own agent, per kind",
@@ -14590,7 +14929,7 @@ var init_status3 = __esm({
14590
14929
  return ExitCode.Ok;
14591
14930
  }
14592
14931
  };
14593
- status_default3 = command41;
14932
+ status_default3 = command42;
14594
14933
  }
14595
14934
  });
14596
14935
 
@@ -14722,9 +15061,9 @@ var init_files = __esm({
14722
15061
  import { execFile, spawnSync as spawnSync2 } from "node:child_process";
14723
15062
  import { readFileSync as readFileSync12 } from "node:fs";
14724
15063
  import { isAbsolute as isAbsolute2 } from "node:path";
14725
- function sudoArgs(user, command48, args, keep = [], set = {}) {
15064
+ function sudoArgs(user, command49, args, keep = [], set = {}) {
14726
15065
  const assignments = Object.entries(set).map(([name, value]) => `${name}=${value}`);
14727
- return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command48, ...args];
15066
+ return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command49, ...args];
14728
15067
  }
14729
15068
  function agentKensoEnv(opts) {
14730
15069
  return {
@@ -14734,12 +15073,12 @@ function agentKensoEnv(opts) {
14734
15073
  AI_AGENT: opts.agentName
14735
15074
  };
14736
15075
  }
14737
- function sudoExec(user, command48, args, opts = {}) {
15076
+ function sudoExec(user, command49, args, opts = {}) {
14738
15077
  const [sudo = "/usr/bin/sudo", ...lead] = user.sudo;
14739
15078
  return new Promise((resolve16) => {
14740
15079
  execFile(
14741
15080
  sudo,
14742
- [...lead, ...sudoArgs(user.name, command48, args)],
15081
+ [...lead, ...sudoArgs(user.name, command49, args)],
14743
15082
  { env: { PATH: SUDO_PATH }, cwd: "/", timeout: opts.timeoutMs ?? PROBE_TIMEOUT_MS, maxBuffer: opts.maxBuffer ?? 1024 * 1024, encoding: "utf8", windowsHide: true, shell: false },
14744
15083
  (err, stdout, stderr) => {
14745
15084
  const code = err ? err.code : 0;
@@ -14837,7 +15176,7 @@ var init_agent_user = __esm({
14837
15176
  });
14838
15177
 
14839
15178
  // src/commands/work/folder.ts
14840
- import { existsSync as existsSync8 } from "node:fs";
15179
+ import { existsSync as existsSync9 } from "node:fs";
14841
15180
  import { appendFile as appendFile3, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
14842
15181
  import { dirname as dirname3, join as join18, resolve as resolve13 } from "node:path";
14843
15182
  var WorkRunFolder;
@@ -14849,9 +15188,9 @@ var init_folder2 = __esm({
14849
15188
  init_redact();
14850
15189
  init_agent_user();
14851
15190
  WorkRunFolder = class {
14852
- constructor(ctx, command48, args, outDir, shared = false) {
15191
+ constructor(ctx, command49, args, outDir, shared = false) {
14853
15192
  this.ctx = ctx;
14854
- this.command = command48;
15193
+ this.command = command49;
14855
15194
  this.args = args;
14856
15195
  this.outDir = outDir;
14857
15196
  this.shared = shared;
@@ -14886,7 +15225,7 @@ var init_folder2 = __esm({
14886
15225
  makeDir(dir);
14887
15226
  } else {
14888
15227
  dir = resolve13(this.outDir);
14889
- const existing = existsSync8(join18(dir, "run.json")) ? await readRunDir(dir) : null;
15228
+ const existing = existsSync9(join18(dir, "run.json")) ? await readRunDir(dir) : null;
14890
15229
  if (existing && !existing.command.startsWith("work ")) {
14891
15230
  throw usageError(`${dir} already holds run ${existing.runId} (${existing.command}).`, {
14892
15231
  field: "out",
@@ -14966,7 +15305,7 @@ var pull_exports2 = {};
14966
15305
  __export(pull_exports2, {
14967
15306
  default: () => pull_default2
14968
15307
  });
14969
- var MAX_FILES, command42, pull_default2;
15308
+ var MAX_FILES, command43, pull_default2;
14970
15309
  var init_pull2 = __esm({
14971
15310
  "src/commands/work/pull.ts"() {
14972
15311
  "use strict";
@@ -14975,7 +15314,7 @@ var init_pull2 = __esm({
14975
15314
  init_common3();
14976
15315
  init_folder2();
14977
15316
  MAX_FILES = 100;
14978
- command42 = {
15317
+ command43 = {
14979
15318
  resource: "work",
14980
15319
  action: "pull",
14981
15320
  summary: "Claim waiting work into local work files, to answer by hand",
@@ -14987,7 +15326,7 @@ var init_pull2 = __esm({
14987
15326
  "live-only": LIVE_ONLY_FLAG,
14988
15327
  files: { type: "string", default: "16", description: `Work files (claims) to take, 1-${MAX_FILES}` },
14989
15328
  "per-file": PER_FILE_FLAG,
14990
- out: OUT_FLAG2,
15329
+ out: OUT_FLAG3,
14991
15330
  lease: LEASE_FLAG
14992
15331
  },
14993
15332
  examples: [
@@ -15053,13 +15392,13 @@ var init_pull2 = __esm({
15053
15392
  return interrupted7 ? ExitCode.Interrupted : ExitCode.Ok;
15054
15393
  }
15055
15394
  };
15056
- pull_default2 = command42;
15395
+ pull_default2 = command43;
15057
15396
  }
15058
15397
  });
15059
15398
 
15060
15399
  // src/commands/work/answers.ts
15061
15400
  import { randomUUID as randomUUID3 } from "node:crypto";
15062
- import { existsSync as existsSync9 } from "node:fs";
15401
+ import { existsSync as existsSync10 } from "node:fs";
15063
15402
  import { basename as basename4, dirname as dirname4, join as join19 } from "node:path";
15064
15403
  function zeroTotals() {
15065
15404
  return { accepted: 0, rejected: 0, expired: 0, duplicate: 0, dropped: 0 };
@@ -15162,7 +15501,7 @@ function workFileNextTo(answersPath) {
15162
15501
  });
15163
15502
  }
15164
15503
  const workPath = join19(dirname4(answersPath), `${claimId}.work.json`);
15165
- if (!existsSync9(workPath)) {
15504
+ if (!existsSync10(workPath)) {
15166
15505
  throw usageError(`${workPath} is missing: kenso work submit reads it next to the answers file.`, { field: "answers-file" });
15167
15506
  }
15168
15507
  let work;
@@ -15195,7 +15534,7 @@ __export(submit_exports, {
15195
15534
  default: () => submit_default
15196
15535
  });
15197
15536
  import { resolve as resolve14 } from "node:path";
15198
- var command43, submit_default;
15537
+ var command44, submit_default;
15199
15538
  var init_submit = __esm({
15200
15539
  "src/commands/work/submit.ts"() {
15201
15540
  "use strict";
@@ -15204,7 +15543,7 @@ var init_submit = __esm({
15204
15543
  init_files();
15205
15544
  init_answers();
15206
15545
  init_common3();
15207
- command43 = {
15546
+ command44 = {
15208
15547
  resource: "work",
15209
15548
  action: "submit",
15210
15549
  summary: "Send answers files to Kenso and write each one's results",
@@ -15236,7 +15575,7 @@ var init_submit = __esm({
15236
15575
  return totals.rejected > 0 ? ExitCode.Partial : ExitCode.Ok;
15237
15576
  }
15238
15577
  };
15239
- submit_default = command43;
15578
+ submit_default = command44;
15240
15579
  }
15241
15580
  });
15242
15581
 
@@ -15245,9 +15584,9 @@ var release_exports = {};
15245
15584
  __export(release_exports, {
15246
15585
  default: () => release_default
15247
15586
  });
15248
- import { existsSync as existsSync10 } from "node:fs";
15587
+ import { existsSync as existsSync11 } from "node:fs";
15249
15588
  function claimIdOf(arg) {
15250
- if (arg.endsWith(".json") || existsSync10(arg)) {
15589
+ if (arg.endsWith(".json") || existsSync11(arg)) {
15251
15590
  try {
15252
15591
  return readWorkFile(arg).claimId;
15253
15592
  } catch (err) {
@@ -15257,7 +15596,7 @@ function claimIdOf(arg) {
15257
15596
  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..." });
15258
15597
  return arg;
15259
15598
  }
15260
- var CLAIM_ID, command44, release_default;
15599
+ var CLAIM_ID, command45, release_default;
15261
15600
  var init_release = __esm({
15262
15601
  "src/commands/work/release.ts"() {
15263
15602
  "use strict";
@@ -15266,7 +15605,7 @@ var init_release = __esm({
15266
15605
  init_files();
15267
15606
  init_common3();
15268
15607
  CLAIM_ID = /^[A-Za-z0-9_-]{1,64}$/;
15269
- command44 = {
15608
+ command45 = {
15270
15609
  resource: "work",
15271
15610
  action: "release",
15272
15611
  summary: "Give claimed work back to the queue now",
@@ -15285,7 +15624,7 @@ var init_release = __esm({
15285
15624
  return ExitCode.Ok;
15286
15625
  }
15287
15626
  };
15288
- release_default = command44;
15627
+ release_default = command45;
15289
15628
  }
15290
15629
  });
15291
15630
 
@@ -15624,12 +15963,12 @@ function plain(text4) {
15624
15963
  return text4.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
15625
15964
  }
15626
15965
  function runStatus(bin, args, env, adapter, runAs) {
15627
- const command48 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
15966
+ const command49 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
15628
15967
  const commandArgs2 = runAs ? [...runAs.sudo.slice(1), ...sudoArgs(runAs.name, bin, args)] : args;
15629
15968
  const options = runAs ? { env: { PATH: SUDO_PATH }, cwd: "/" } : { env: childEnv(env, adapter) };
15630
15969
  return new Promise((resolve16) => {
15631
15970
  execFile2(
15632
- command48,
15971
+ command49,
15633
15972
  commandArgs2,
15634
15973
  { ...options, timeout: STATUS_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
15635
15974
  (err, stdout, stderr) => {
@@ -16707,12 +17046,12 @@ var init_stop = __esm({
16707
17046
  });
16708
17047
 
16709
17048
  // src/commands/work/run.ts
16710
- var run_exports2 = {};
16711
- __export(run_exports2, {
16712
- default: () => run_default
17049
+ var run_exports3 = {};
17050
+ __export(run_exports3, {
17051
+ default: () => run_default2
16713
17052
  });
16714
- var FAILURES_IN_A_ROW, command45, run_default;
16715
- var init_run2 = __esm({
17053
+ var FAILURES_IN_A_ROW, command46, run_default2;
17054
+ var init_run3 = __esm({
16716
17055
  "src/commands/work/run.ts"() {
16717
17056
  "use strict";
16718
17057
  init_errors();
@@ -16732,7 +17071,7 @@ var init_run2 = __esm({
16732
17071
  init_folder2();
16733
17072
  init_stop();
16734
17073
  FAILURES_IN_A_ROW = 3;
16735
- command45 = {
17074
+ command46 = {
16736
17075
  resource: "work",
16737
17076
  action: "run",
16738
17077
  summary: "Run your own coding agent on the waiting work until the queue is empty",
@@ -16753,7 +17092,7 @@ var init_run2 = __esm({
16753
17092
  "agent-bin": { type: "string", description: "The agent's binary, when it is not on PATH under its usual name" },
16754
17093
  "allow-unconfined": { type: "boolean", description: "Run an agent Kenso cannot hold to the job folder (every agent but claude)" },
16755
17094
  lease: LEASE_FLAG,
16756
- out: OUT_FLAG2,
17095
+ out: OUT_FLAG3,
16757
17096
  // --token-stdin, --agent-user and --agent-tools: how a Kenso sandbox runs it (src/commands/work/box.ts).
16758
17097
  ...BOX_FLAGS
16759
17098
  },
@@ -17057,21 +17396,21 @@ var init_run2 = __esm({
17057
17396
  return exitCodeFor(reason, totals.rejected > 0 || jobsFailed > 0);
17058
17397
  }
17059
17398
  };
17060
- run_default = command45;
17399
+ run_default2 = command46;
17061
17400
  }
17062
17401
  });
17063
17402
 
17064
17403
  // src/commands/work/index.ts
17065
- var actions22;
17404
+ var actions23;
17066
17405
  var init_work2 = __esm({
17067
17406
  "src/commands/work/index.ts"() {
17068
17407
  "use strict";
17069
- actions22 = {
17408
+ actions23 = {
17070
17409
  status: () => Promise.resolve().then(() => (init_status3(), status_exports3)).then((m) => m.default),
17071
17410
  pull: () => Promise.resolve().then(() => (init_pull2(), pull_exports2)).then((m) => m.default),
17072
17411
  submit: () => Promise.resolve().then(() => (init_submit(), submit_exports)).then((m) => m.default),
17073
17412
  release: () => Promise.resolve().then(() => (init_release(), release_exports)).then((m) => m.default),
17074
- run: () => Promise.resolve().then(() => (init_run2(), run_exports2)).then((m) => m.default)
17413
+ run: () => Promise.resolve().then(() => (init_run3(), run_exports3)).then((m) => m.default)
17075
17414
  };
17076
17415
  }
17077
17416
  });
@@ -17090,14 +17429,14 @@ function parseLimit(value) {
17090
17429
  }
17091
17430
  return limit;
17092
17431
  }
17093
- var MAX_LIMIT, command46, list_default3;
17432
+ var MAX_LIMIT, command47, list_default3;
17094
17433
  var init_list3 = __esm({
17095
17434
  "src/commands/workspace/list.ts"() {
17096
17435
  "use strict";
17097
17436
  init_errors();
17098
17437
  init_exit_codes();
17099
17438
  MAX_LIMIT = 200;
17100
- command46 = {
17439
+ command47 = {
17101
17440
  resource: "workspace",
17102
17441
  action: "list",
17103
17442
  summary: "List the workspaces your key can use",
@@ -17125,7 +17464,7 @@ var init_list3 = __esm({
17125
17464
  return ExitCode.Ok;
17126
17465
  }
17127
17466
  };
17128
- list_default3 = command46;
17467
+ list_default3 = command47;
17129
17468
  }
17130
17469
  });
17131
17470
 
@@ -17134,7 +17473,7 @@ var use_exports = {};
17134
17473
  __export(use_exports, {
17135
17474
  default: () => use_default
17136
17475
  });
17137
- var command47, use_default;
17476
+ var command48, use_default;
17138
17477
  var init_use = __esm({
17139
17478
  "src/commands/workspace/use.ts"() {
17140
17479
  "use strict";
@@ -17142,7 +17481,7 @@ var init_use = __esm({
17142
17481
  init_errors();
17143
17482
  init_exit_codes();
17144
17483
  init_http();
17145
- command47 = {
17484
+ command48 = {
17146
17485
  resource: "workspace",
17147
17486
  action: "use",
17148
17487
  summary: "Set the profile's default workspace",
@@ -17199,16 +17538,16 @@ var init_use = __esm({
17199
17538
  return ExitCode.Ok;
17200
17539
  }
17201
17540
  };
17202
- use_default = command47;
17541
+ use_default = command48;
17203
17542
  }
17204
17543
  });
17205
17544
 
17206
17545
  // src/commands/workspace/index.ts
17207
- var actions23;
17546
+ var actions24;
17208
17547
  var init_workspace = __esm({
17209
17548
  "src/commands/workspace/index.ts"() {
17210
17549
  "use strict";
17211
- actions23 = {
17550
+ actions24 = {
17212
17551
  list: () => Promise.resolve().then(() => (init_list3(), list_exports3)).then((m) => m.default),
17213
17552
  use: () => Promise.resolve().then(() => (init_use(), use_exports)).then((m) => m.default)
17214
17553
  };
@@ -17244,6 +17583,7 @@ var init_registry = __esm({
17244
17583
  init_mcp();
17245
17584
  init_opportunities();
17246
17585
  init_people();
17586
+ init_reports();
17247
17587
  init_runs2();
17248
17588
  init_sandbox2();
17249
17589
  init_skill();
@@ -17270,14 +17610,15 @@ var init_registry = __esm({
17270
17610
  mcp: actions14,
17271
17611
  opportunities: actions15,
17272
17612
  people: actions16,
17273
- runs: actions17,
17274
- sandbox: actions18,
17275
- skill: actions19,
17276
- studio: actions20,
17277
- webhooks: actions21,
17613
+ reports: actions17,
17614
+ runs: actions18,
17615
+ sandbox: actions19,
17616
+ skill: actions20,
17617
+ studio: actions21,
17618
+ webhooks: actions22,
17278
17619
  whoami: topLevel("whoami", actions4.status, "kenso auth status"),
17279
- work: actions22,
17280
- workspace: actions23
17620
+ work: actions23,
17621
+ workspace: actions24
17281
17622
  };
17282
17623
  resourceAliases = { leads: "contacts" };
17283
17624
  }
@@ -17414,8 +17755,8 @@ async function renderTopHelp(opts) {
17414
17755
  names.push(withPositionals(spec, spec.action));
17415
17756
  groups.set(hint, names);
17416
17757
  }
17417
- const actions25 = [...groups.entries()].map(([hint, names]) => `${names.join(", ")}${hint}`);
17418
- if (actions25.length > 0) rows.push([resource, actions25.join(", ")]);
17758
+ const actions26 = [...groups.entries()].map(([hint, names]) => `${names.join(", ")}${hint}`);
17759
+ if (actions26.length > 0) rows.push([resource, actions26.join(", ")]);
17419
17760
  }
17420
17761
  const at = 4 + Math.min(22, Math.max(0, ...rows.map(([left]) => left.length)));
17421
17762
  lines.push(
@@ -17428,7 +17769,7 @@ async function renderTopHelp(opts) {
17428
17769
  const [area = "", action = ""] = name.split(" ");
17429
17770
  byArea.set(area, [...byArea.get(area) ?? [], action]);
17430
17771
  }
17431
- const named = [...byArea.entries()].map(([area, actions25]) => `${area} ${actions25.join("|")}`);
17772
+ const named = [...byArea.entries()].map(([area, actions26]) => `${area} ${actions26.join("|")}`);
17432
17773
  lines.push(wrap(`Beta, hidden here but they run (the server decides): ${named.join(", ")}.`, " "));
17433
17774
  }
17434
17775
  const generated = await listGenerated({ features: opts.allCommands ? [] : getFeatures, env: opts.env });
@@ -17436,13 +17777,13 @@ async function renderTopHelp(opts) {
17436
17777
  if (visible.length > 0) {
17437
17778
  const byResource = /* @__PURE__ */ new Map();
17438
17779
  for (const g of visible) {
17439
- const actions25 = byResource.get(g.resource) ?? [];
17440
- actions25.push(`${g.action}${g.beta ? " (beta)" : ""}`);
17441
- byResource.set(g.resource, actions25);
17780
+ const actions26 = byResource.get(g.resource) ?? [];
17781
+ actions26.push(`${g.action}${g.beta ? " (beta)" : ""}`);
17782
+ byResource.set(g.resource, actions26);
17442
17783
  }
17443
17784
  const sorted2 = [...byResource.entries()].sort(([a], [b]) => a.localeCompare(b));
17444
17785
  if (opts.allCommands) {
17445
- const generatedRows = sorted2.map(([resource, actions25]) => [resource, actions25.sort().join(", ")]);
17786
+ const generatedRows = sorted2.map(([resource, actions26]) => [resource, actions26.sort().join(", ")]);
17446
17787
  lines.push("", "API resources (kenso <resource> <action>):", columns(generatedRows));
17447
17788
  } else {
17448
17789
  const names = new Set(sorted2.map(([resource]) => resource));
@@ -17758,8 +18099,8 @@ function startUpdateNotice(argv, opts = {}) {
17758
18099
  if (!found) return;
17759
18100
  writeCheck(file, { checkedAt: new Date(now).toISOString(), latest: found });
17760
18101
  if (isNewer(found, version)) {
17761
- const command48 = updateCommand(install, opts.platform ?? process.platform);
17762
- stderr.write(`kenso ${found} is out (you have ${version}): ${command48}
18102
+ const command49 = updateCommand(install, opts.platform ?? process.platform);
18103
+ stderr.write(`kenso ${found} is out (you have ${version}): ${command49}
17763
18104
  Turn this off with KENSO_NO_UPDATE_NOTIFIER=1.
17764
18105
  `);
17765
18106
  }
@@ -17801,7 +18142,7 @@ function resources() {
17801
18142
  const names = Object.entries(handWritten).filter(([, area]) => Object.keys(area).length > 0).map(([resource]) => resource);
17802
18143
  return sorted([...names, ...Object.keys(resourceAliases), ...loadManifest().operations.map((op) => op.resource)]);
17803
18144
  }
17804
- function actions24(resource) {
18145
+ function actions25(resource) {
17805
18146
  const own = Object.keys(handWritten[resource] ?? {}).filter((action) => action !== "");
17806
18147
  return sorted([...own, ...loadManifest().operations.filter((op) => op.resource === resource).map((op) => op.action)]);
17807
18148
  }
@@ -17866,7 +18207,7 @@ async function completions(words, globals) {
17866
18207
  return flagsOf2(spec, globals, positionals.length === 0);
17867
18208
  }
17868
18209
  if (positionals.length === 0) return resources();
17869
- if (!spec) return positionals.length === 1 ? actions24(resourceAliases[positionals[0]] ?? positionals[0]) : [];
18210
+ if (!spec) return positionals.length === 1 ? actions25(resourceAliases[positionals[0]] ?? positionals[0]) : [];
17870
18211
  const given = positionals.length - commandWords;
17871
18212
  const declared = spec.positionals ?? [];
17872
18213
  if (given < declared.length || declared.at(-1)?.variadic === true) {
@@ -17960,9 +18301,9 @@ function normalizeBooleans(argv, names, strict) {
17960
18301
  async function knownCommands() {
17961
18302
  const commands = /* @__PURE__ */ new Set();
17962
18303
  for (const [resource, area] of Object.entries(handWritten)) {
17963
- const actions25 = Object.keys(area);
17964
- if (actions25.length > 0) commands.add(resource);
17965
- for (const action of actions25) commands.add(action ? `${resource} ${action}` : resource);
18304
+ const actions26 = Object.keys(area);
18305
+ if (actions26.length > 0) commands.add(resource);
18306
+ for (const action of actions26) commands.add(action ? `${resource} ${action}` : resource);
17966
18307
  }
17967
18308
  for (const g of await listGenerated({ features: [] })) {
17968
18309
  commands.add(g.resource);