kenso 0.1.111 → 0.1.113

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
@@ -282,18 +282,18 @@ function readConfig(env = process.env) {
282
282
  }
283
283
  return config;
284
284
  }
285
- function ensurePrivateDir(dir) {
286
- mkdirSync(dir, { recursive: true, mode: 448 });
285
+ function ensurePrivateDir(dir2) {
286
+ mkdirSync(dir2, { recursive: true, mode: 448 });
287
287
  try {
288
- chmodSync(dir, 448);
288
+ chmodSync(dir2, 448);
289
289
  } catch {
290
290
  }
291
291
  }
292
292
  function writeConfig(config, env) {
293
- const dir = configDir(env);
294
- ensurePrivateDir(dir);
295
- const file = join(dir, CONFIG_FILE);
296
- const temp = join(dir, `.${CONFIG_FILE}.${process.pid}.${Date.now()}.tmp`);
293
+ const dir2 = configDir(env);
294
+ ensurePrivateDir(dir2);
295
+ const file = join(dir2, CONFIG_FILE);
296
+ const temp = join(dir2, `.${CONFIG_FILE}.${process.pid}.${Date.now()}.tmp`);
297
297
  try {
298
298
  writeFileSync(temp, `${JSON.stringify(config, null, 2)}
299
299
  `, { mode: 384 });
@@ -321,13 +321,13 @@ function removeProfile(name, env = process.env) {
321
321
  writeConfig(config, env);
322
322
  }
323
323
  function cacheDir(env = process.env) {
324
- const dir = join(configDir(env), "cache");
325
- ensurePrivateDir(dir);
326
- return dir;
324
+ const dir2 = join(configDir(env), "cache");
325
+ ensurePrivateDir(dir2);
326
+ return dir2;
327
327
  }
328
328
  function clearCache(env = process.env) {
329
- const dir = join(configDir(env), "cache");
330
- if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
329
+ const dir2 = join(configDir(env), "cache");
330
+ if (existsSync(dir2)) rmSync(dir2, { recursive: true, force: true });
331
331
  }
332
332
  function nonEmpty(value) {
333
333
  const trimmed = value?.trim();
@@ -1353,14 +1353,14 @@ var require_jmespath = __commonJS({
1353
1353
  },
1354
1354
  _parseSliceExpression: function() {
1355
1355
  var parts2 = [null, null, null];
1356
- var index = 0;
1356
+ var index2 = 0;
1357
1357
  var currentToken = this._lookahead(0);
1358
- while (currentToken !== TOK_RBRACKET && index < 3) {
1358
+ while (currentToken !== TOK_RBRACKET && index2 < 3) {
1359
1359
  if (currentToken === TOK_COLON) {
1360
- index++;
1360
+ index2++;
1361
1361
  this._advance();
1362
1362
  } else if (currentToken === TOK_NUMBER) {
1363
- parts2[index] = this._lookaheadToken(0).value;
1363
+ parts2[index2] = this._lookaheadToken(0).value;
1364
1364
  this._advance();
1365
1365
  } else {
1366
1366
  var t = this._lookahead(0);
@@ -1489,11 +1489,11 @@ var require_jmespath = __commonJS({
1489
1489
  if (!isArray(value)) {
1490
1490
  return null;
1491
1491
  }
1492
- var index = node.value;
1493
- if (index < 0) {
1494
- index = value.length + index;
1492
+ var index2 = node.value;
1493
+ if (index2 < 0) {
1494
+ index2 = value.length + index2;
1495
1495
  }
1496
- result = value[index];
1496
+ result = value[index2];
1497
1497
  if (result === void 0) {
1498
1498
  result = null;
1499
1499
  }
@@ -2477,7 +2477,7 @@ var VERSION;
2477
2477
  var init_version = __esm({
2478
2478
  "src/core/version.ts"() {
2479
2479
  "use strict";
2480
- VERSION = true ? "0.1.111" : "0.0.0-dev";
2480
+ VERSION = true ? "0.1.113" : "0.0.0-dev";
2481
2481
  }
2482
2482
  });
2483
2483
 
@@ -2629,13 +2629,17 @@ var manifest_exports = {};
2629
2629
  __export(manifest_exports, {
2630
2630
  findOperation: () => findOperation,
2631
2631
  findOperationById: () => findOperationById,
2632
+ listOperations: () => listOperations,
2632
2633
  loadManifest: () => loadManifest,
2634
+ useManifestDirForTest: () => useManifestDirForTest,
2633
2635
  useManifestForTest: () => useManifestForTest
2634
2636
  });
2635
- import { readFileSync as readFileSync3 } from "node:fs";
2636
- function readFromDisk() {
2637
+ import { closeSync, openSync, readFileSync as readFileSync3, readSync } from "node:fs";
2638
+ import { join as join3 } from "node:path";
2639
+ import { pathToFileURL } from "node:url";
2640
+ function readText(name) {
2637
2641
  try {
2638
- return readFileSync3(new URL("./operations.json", import.meta.url), "utf8");
2642
+ return readFileSync3(new URL(name, dir), "utf8");
2639
2643
  } catch {
2640
2644
  return void 0;
2641
2645
  }
@@ -2643,24 +2647,66 @@ function readFromDisk() {
2643
2647
  function loadManifest() {
2644
2648
  if (override) return override;
2645
2649
  if (!parsed) {
2646
- const text4 = readFromDisk();
2650
+ const text4 = readText(MANIFEST_FILE);
2647
2651
  parsed = text4 ? JSON.parse(text4) : EMPTY;
2648
2652
  }
2649
2653
  return parsed;
2650
2654
  }
2655
+ function loadIndex() {
2656
+ if (index === void 0) {
2657
+ const text4 = readText(INDEX_FILE);
2658
+ try {
2659
+ const value = text4 ? JSON.parse(text4) : null;
2660
+ index = Array.isArray(value?.operations) ? value : null;
2661
+ } catch {
2662
+ index = null;
2663
+ }
2664
+ }
2665
+ return index;
2666
+ }
2667
+ function listOperations() {
2668
+ if (override) return override.operations;
2669
+ return loadIndex()?.operations ?? loadManifest().operations;
2670
+ }
2651
2671
  function indexes() {
2652
2672
  if (!byCommand || !byId) {
2653
- const operations = loadManifest().operations;
2673
+ const operations = listOperations();
2654
2674
  byCommand = new Map(operations.map((op) => [`${op.resource} ${op.action}`, op]));
2655
2675
  byId = new Map(operations.map((op) => [op.id, op]));
2656
2676
  }
2657
2677
  return { byCommand, byId };
2658
2678
  }
2679
+ function readRange(entry) {
2680
+ const [offset, length] = entry.at;
2681
+ let fd;
2682
+ try {
2683
+ fd = openSync(new URL(MANIFEST_FILE, dir), "r");
2684
+ const buffer = Buffer.alloc(length);
2685
+ if (readSync(fd, buffer, 0, length, offset) !== length) return void 0;
2686
+ const op = JSON.parse(buffer.toString("utf8"));
2687
+ return op.id === entry.id && op.resource === entry.resource && op.action === entry.action ? op : void 0;
2688
+ } catch {
2689
+ return void 0;
2690
+ } finally {
2691
+ if (fd !== void 0) closeSync(fd);
2692
+ }
2693
+ }
2694
+ function operationOf(listing) {
2695
+ if (!listing) return void 0;
2696
+ if (!("at" in listing)) return listing;
2697
+ return readRange(listing) ?? loadManifest().operations.find((op) => op.id === listing.id);
2698
+ }
2659
2699
  function findOperation(resource, action) {
2660
- return indexes().byCommand.get(`${resource} ${action}`);
2700
+ return operationOf(indexes().byCommand.get(`${resource} ${action}`));
2661
2701
  }
2662
2702
  function findOperationById(id) {
2663
- return indexes().byId.get(id);
2703
+ return operationOf(indexes().byId.get(id));
2704
+ }
2705
+ function reset() {
2706
+ parsed = void 0;
2707
+ index = void 0;
2708
+ byCommand = void 0;
2709
+ byId = void 0;
2664
2710
  }
2665
2711
  function useManifestForTest(manifest) {
2666
2712
  const previous = override;
@@ -2672,11 +2718,23 @@ function useManifestForTest(manifest) {
2672
2718
  set2(manifest);
2673
2719
  return () => set2(previous);
2674
2720
  }
2675
- var EMPTY, parsed, override, byCommand, byId;
2721
+ function useManifestDirForTest(folder) {
2722
+ const previous = dir;
2723
+ const set2 = (value) => {
2724
+ dir = value;
2725
+ reset();
2726
+ };
2727
+ set2(folder === void 0 ? new URL("./", import.meta.url) : pathToFileURL(join3(folder, "/")));
2728
+ return () => set2(previous);
2729
+ }
2730
+ var EMPTY, MANIFEST_FILE, INDEX_FILE, dir, parsed, index, override, byCommand, byId;
2676
2731
  var init_manifest = __esm({
2677
2732
  "src/manifest/index.ts"() {
2678
2733
  "use strict";
2679
2734
  EMPTY = { generatedAt: "", contractsHash: "", operations: [] };
2735
+ MANIFEST_FILE = "operations.json";
2736
+ INDEX_FILE = "operations.index.json";
2737
+ dir = new URL("./", import.meta.url);
2680
2738
  }
2681
2739
  });
2682
2740
 
@@ -3318,12 +3376,12 @@ var init_get = __esm({
3318
3376
  };
3319
3377
  get = function(object, path) {
3320
3378
  path = castPath(path, object);
3321
- let index = 0;
3379
+ let index2 = 0;
3322
3380
  const length = path.length;
3323
- while (object != null && index < length) {
3324
- object = object[toKey(path[index++])];
3381
+ while (object != null && index2 < length) {
3382
+ object = object[toKey(path[index2++])];
3325
3383
  }
3326
- return index && index === length ? object : void 0;
3384
+ return index2 && index2 === length ? object : void 0;
3327
3385
  };
3328
3386
  }
3329
3387
  });
@@ -3964,16 +4022,16 @@ var init_sync = __esm({
3964
4022
  import { createHash } from "node:crypto";
3965
4023
  import { readFileSync as readFileSync5 } from "node:fs";
3966
4024
  import { readFile as readFile3 } from "node:fs/promises";
3967
- import { join as join3 } from "node:path";
3968
- function filesOf(dir) {
4025
+ import { join as join4 } from "node:path";
4026
+ function filesOf(dir2) {
3969
4027
  return {
3970
- runJson: join3(dir, "run.json"),
3971
- stateJson: join3(dir, "state.json"),
3972
- resultsCsv: join3(dir, "results.csv"),
3973
- resultsNdjson: join3(dir, "results.ndjson"),
3974
- invalidCsv: join3(dir, "invalid.csv"),
3975
- planJson: join3(dir, "plan.json"),
3976
- summaryJson: join3(dir, "summary.json")
4028
+ runJson: join4(dir2, "run.json"),
4029
+ stateJson: join4(dir2, "state.json"),
4030
+ resultsCsv: join4(dir2, "results.csv"),
4031
+ resultsNdjson: join4(dir2, "results.ndjson"),
4032
+ invalidCsv: join4(dir2, "invalid.csv"),
4033
+ planJson: join4(dir2, "plan.json"),
4034
+ summaryJson: join4(dir2, "summary.json")
3977
4035
  };
3978
4036
  }
3979
4037
  function hashItems(items) {
@@ -4092,10 +4150,10 @@ var init_results = __esm({
4092
4150
  import { randomBytes } from "node:crypto";
4093
4151
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync2 } from "node:fs";
4094
4152
  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";
4153
+ import { join as join5, resolve as resolve2 } from "node:path";
4096
4154
  function runsRoot(env = process.env) {
4097
4155
  const override2 = env.KENSO_RUNS_DIR?.trim();
4098
- return resolve2(override2 ? override2 : join4(configDir(env), "runs"));
4156
+ return resolve2(override2 ? override2 : join5(configDir(env), "runs"));
4099
4157
  }
4100
4158
  function newRunId() {
4101
4159
  const bytes = randomBytes(5);
@@ -4128,15 +4186,15 @@ function argsIdentity(args) {
4128
4186
  }
4129
4187
  return JSON.stringify(stable(kept));
4130
4188
  }
4131
- function ensureDir(dir, mode) {
4132
- mkdirSync2(dir, { recursive: true, mode: mode & 511 });
4189
+ function ensureDir(dir2, mode) {
4190
+ mkdirSync2(dir2, { recursive: true, mode: mode & 511 });
4133
4191
  try {
4134
- chmodSync2(dir, mode);
4192
+ chmodSync2(dir2, mode);
4135
4193
  } catch {
4136
4194
  }
4137
4195
  }
4138
- function ensurePrivateDir2(dir) {
4139
- ensureDir(dir, 448);
4196
+ function ensurePrivateDir2(dir2) {
4197
+ ensureDir(dir2, 448);
4140
4198
  }
4141
4199
  async function writeFileAtomic(path, content) {
4142
4200
  const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
@@ -4153,8 +4211,8 @@ async function writeJsonAtomic(path, value) {
4153
4211
  `);
4154
4212
  }
4155
4213
  async function writeRunRecord(record3) {
4156
- const { dir, ...rest } = record3;
4157
- await writeJsonAtomic(join4(dir, "run.json"), rest);
4214
+ const { dir: dir2, ...rest } = record3;
4215
+ await writeJsonAtomic(join5(dir2, "run.json"), rest);
4158
4216
  }
4159
4217
  async function readJson(path) {
4160
4218
  return JSON.parse(await readFile4(path, "utf8"));
@@ -4166,10 +4224,10 @@ function chunkList(value) {
4166
4224
  if (!Array.isArray(value)) return void 0;
4167
4225
  return value.filter((n) => Number.isInteger(n) && n >= 0);
4168
4226
  }
4169
- async function readRunDir(dir) {
4227
+ async function readRunDir(dir2) {
4170
4228
  let raw;
4171
4229
  try {
4172
- raw = asRecord3(await readJson(join4(dir, "run.json")));
4230
+ raw = asRecord3(await readJson(join5(dir2, "run.json")));
4173
4231
  } catch {
4174
4232
  return null;
4175
4233
  }
@@ -4180,7 +4238,7 @@ async function readRunDir(dir) {
4180
4238
  if (typeof status !== "string" || !STATUSES.includes(status)) return null;
4181
4239
  let chunksDone = chunkList(raw.chunksDone) ?? [];
4182
4240
  try {
4183
- const state = asRecord3(await readJson(join4(dir, "state.json")));
4241
+ const state = asRecord3(await readJson(join5(dir2, "state.json")));
4184
4242
  chunksDone = chunkList(state?.chunksDone) ?? chunksDone;
4185
4243
  } catch {
4186
4244
  }
@@ -4193,7 +4251,7 @@ async function readRunDir(dir) {
4193
4251
  status,
4194
4252
  chunkCount: typeof raw.chunkCount === "number" ? raw.chunkCount : 0,
4195
4253
  chunksDone: [...new Set(chunksDone)].sort((a, b) => a - b),
4196
- dir
4254
+ dir: dir2
4197
4255
  };
4198
4256
  return record3;
4199
4257
  }
@@ -4208,13 +4266,13 @@ async function listRuns(env = process.env) {
4208
4266
  const runs = [];
4209
4267
  for (const name of names) {
4210
4268
  if (!RUN_ID_PATTERN.test(name)) continue;
4211
- let dir;
4269
+ let dir2;
4212
4270
  try {
4213
- dir = await realpath(join4(root2, name));
4271
+ dir2 = await realpath(join5(root2, name));
4214
4272
  } catch {
4215
4273
  continue;
4216
4274
  }
4217
- const run = await readRunDir(dir);
4275
+ const run = await readRunDir(dir2);
4218
4276
  if (run && run.runId === name) runs.push(run);
4219
4277
  }
4220
4278
  return runs.sort((a, b) => a.createdAt === b.createdAt ? b.runId.localeCompare(a.runId) : b.createdAt.localeCompare(a.createdAt));
@@ -4224,13 +4282,13 @@ async function loadRun(runId, env = process.env) {
4224
4282
  if (!RUN_ID_PATTERN.test(id)) {
4225
4283
  throw usageError(`"${runId}" is not a run id: run ids look like r_ab3dxk2q.`, { field: "runId", next: "kenso runs list" });
4226
4284
  }
4227
- let dir;
4285
+ let dir2;
4228
4286
  try {
4229
- dir = await realpath(join4(runsRoot(env), id));
4287
+ dir2 = await realpath(join5(runsRoot(env), id));
4230
4288
  } catch {
4231
- dir = void 0;
4289
+ dir2 = void 0;
4232
4290
  }
4233
- const run = dir ? await readRunDir(dir) : null;
4291
+ const run = dir2 ? await readRunDir(dir2) : null;
4234
4292
  if (!run || run.runId !== id) {
4235
4293
  throw new KensoError({
4236
4294
  code: "run_not_found",
@@ -4275,34 +4333,34 @@ var init_runs = __esm({
4275
4333
  // src/batch/run-dir.ts
4276
4334
  import { existsSync as existsSync3 } from "node:fs";
4277
4335
  import { symlink, unlink as unlink2 } from "node:fs/promises";
4278
- import { join as join5, resolve as resolve3 } from "node:path";
4336
+ import { join as join6, resolve as resolve3 } from "node:path";
4279
4337
  async function prepareRunDir(outDir, runId, identical, ctx) {
4280
4338
  const root2 = runsRoot(ctx.env);
4281
4339
  if (outDir === void 0) {
4282
- const dir2 = join5(root2, runId);
4340
+ const dir3 = join6(root2, runId);
4283
4341
  ensurePrivateDir2(root2);
4284
- ensurePrivateDir2(dir2);
4285
- return dir2;
4342
+ ensurePrivateDir2(dir3);
4343
+ return dir3;
4286
4344
  }
4287
- const dir = resolve3(outDir);
4288
- const existing = existsSync3(join5(dir, "run.json")) ? await readRunDir(dir) : null;
4345
+ const dir2 = resolve3(outDir);
4346
+ const existing = existsSync3(join6(dir2, "run.json")) ? await readRunDir(dir2) : null;
4289
4347
  if (existing && !identical.some((run) => run.runId === existing.runId)) {
4290
- throw usageError(`${dir} already holds run ${existing.runId} (${existing.command}).`, {
4348
+ throw usageError(`${dir2} already holds run ${existing.runId} (${existing.command}).`, {
4291
4349
  field: "out",
4292
4350
  hint: "Pick an empty --out directory, or leave --out off to keep the run under the runs directory."
4293
4351
  });
4294
4352
  }
4295
- ensurePrivateDir2(dir);
4353
+ ensurePrivateDir2(dir2);
4296
4354
  for (const name of ["results.csv", "invalid.csv", "plan.json", "summary.json", "state.json"]) {
4297
- await unlink2(join5(dir, name)).catch(() => void 0);
4355
+ await unlink2(join6(dir2, name)).catch(() => void 0);
4298
4356
  }
4299
4357
  try {
4300
4358
  ensurePrivateDir2(root2);
4301
- await symlink(dir, join5(root2, runId), "junction");
4359
+ await symlink(dir2, join6(root2, runId), "junction");
4302
4360
  } catch (err) {
4303
- ctx.output.warn(`Could not link ${dir} into ${root2} (${errorText(err)}): kenso runs will not list this run.`);
4361
+ ctx.output.warn(`Could not link ${dir2} into ${root2} (${errorText(err)}): kenso runs will not list this run.`);
4304
4362
  }
4305
- return dir;
4363
+ return dir2;
4306
4364
  }
4307
4365
  async function allSucceeded(run, totalRows) {
4308
4366
  const previous = await readResults(filesOf(run.dir).resultsNdjson);
@@ -4339,14 +4397,14 @@ async function alreadyDone(run, totalRows, started, ctx) {
4339
4397
  }
4340
4398
  async function dryRun(spec, ctx, plan) {
4341
4399
  let runId;
4342
- let dir;
4400
+ let dir2;
4343
4401
  const target2 = plan.finished ?? plan.resumable;
4344
4402
  if (target2) {
4345
4403
  runId = target2.runId;
4346
- dir = target2.dir;
4404
+ dir2 = target2.dir;
4347
4405
  } else {
4348
4406
  runId = newRunId();
4349
- dir = await prepareRunDir(spec.outDir, runId, plan.identical, ctx);
4407
+ dir2 = await prepareRunDir(spec.outDir, runId, plan.identical, ctx);
4350
4408
  const now = (/* @__PURE__ */ new Date()).toISOString();
4351
4409
  await writeRunRecord({
4352
4410
  runId,
@@ -4359,7 +4417,7 @@ async function dryRun(spec, ctx, plan) {
4359
4417
  status: "planned",
4360
4418
  chunkCount: plan.chunkCount,
4361
4419
  chunksDone: [],
4362
- dir,
4420
+ dir: dir2,
4363
4421
  rows: plan.totalRows,
4364
4422
  chunkSize: spec.chunkSize,
4365
4423
  itemsSha256: plan.itemsSha256,
@@ -4367,7 +4425,7 @@ async function dryRun(spec, ctx, plan) {
4367
4425
  updatedAt: now
4368
4426
  });
4369
4427
  }
4370
- const files = filesOf(dir);
4428
+ const files = filesOf(dir2);
4371
4429
  const planBody = {
4372
4430
  dryRun: true,
4373
4431
  command: spec.command,
@@ -4394,7 +4452,7 @@ async function dryRun(spec, ctx, plan) {
4394
4452
  ctx.output.summary(summary);
4395
4453
  return {
4396
4454
  runId,
4397
- dir,
4455
+ dir: dir2,
4398
4456
  resultsCsv: files.resultsCsv,
4399
4457
  resultsNdjson: files.resultsNdjson,
4400
4458
  invalidCsv: plan.invalid.length > 0 ? files.invalidCsv : void 0,
@@ -4416,7 +4474,7 @@ var init_run_dir = __esm({
4416
4474
 
4417
4475
  // src/batch/engine.ts
4418
4476
  import { appendFile } from "node:fs/promises";
4419
- import { join as join6 } from "node:path";
4477
+ import { join as join7 } from "node:path";
4420
4478
  function clampConcurrency(value) {
4421
4479
  if (value === void 0 || !Number.isFinite(value)) return DEFAULT_CONCURRENCY;
4422
4480
  return Math.min(MAX_CONCURRENCY, Math.max(1, Math.floor(value)));
@@ -4450,7 +4508,7 @@ async function runBatch(spec, ctx) {
4450
4508
  code: "run_in_progress",
4451
4509
  message: `Run ${resumable.runId} is already running in process ${resumable.pid}.`,
4452
4510
  exitCode: ExitCode.Conflict,
4453
- hint: `Wait for it to finish, or stop it, then run the same command again to continue it. If process ${resumable.pid} is not a kenso command, delete the "pid" line from ${join6(resumable.dir, "run.json")} and run the command again.`,
4511
+ hint: `Wait for it to finish, or stop it, then run the same command again to continue it. If process ${resumable.pid} is not a kenso command, delete the "pid" line from ${join7(resumable.dir, "run.json")} and run the command again.`,
4454
4512
  next: `kenso runs show ${resumable.runId}`
4455
4513
  });
4456
4514
  }
@@ -4473,7 +4531,7 @@ async function runBatch(spec, ctx) {
4473
4531
  };
4474
4532
  } else {
4475
4533
  const runId = newRunId();
4476
- const dir = await prepareRunDir(spec.outDir, runId, identical, ctx);
4534
+ const dir2 = await prepareRunDir(spec.outDir, runId, identical, ctx);
4477
4535
  record3 = {
4478
4536
  runId,
4479
4537
  command: spec.command,
@@ -4485,7 +4543,7 @@ async function runBatch(spec, ctx) {
4485
4543
  status: "running",
4486
4544
  chunkCount,
4487
4545
  chunksDone: [],
4488
- dir,
4546
+ dir: dir2,
4489
4547
  rows: totalRows,
4490
4548
  chunkSize: spec.chunkSize,
4491
4549
  itemsSha256,
@@ -4501,10 +4559,10 @@ async function runBatch(spec, ctx) {
4501
4559
  for (const result of invalid) results.set(result.row, result);
4502
4560
  if (chunksDone.size > 0) {
4503
4561
  const previous = await readResults(files.resultsNdjson);
4504
- for (const index of [...chunksDone]) {
4505
- const rows = (chunks[index] ?? []).map((item) => spec.rowOf(item));
4562
+ for (const index2 of [...chunksDone]) {
4563
+ const rows = (chunks[index2] ?? []).map((item) => spec.rowOf(item));
4506
4564
  if (rows.some((row) => !previous.has(row))) {
4507
- chunksDone.delete(index);
4565
+ chunksDone.delete(index2);
4508
4566
  continue;
4509
4567
  }
4510
4568
  for (const row of rows) results.set(row, previous.get(row));
@@ -4534,8 +4592,8 @@ async function runBatch(spec, ctx) {
4534
4592
  });
4535
4593
  return next;
4536
4594
  };
4537
- const recordChunk = async (index, outcome) => {
4538
- const chunk = chunks[index];
4595
+ const recordChunk = async (index2, outcome) => {
4596
+ const chunk = chunks[index2];
4539
4597
  const rows = chunk.map((item) => spec.rowOf(item));
4540
4598
  const wanted = new Set(rows);
4541
4599
  const given = /* @__PURE__ */ new Map();
@@ -4552,7 +4610,7 @@ async function runBatch(spec, ctx) {
4552
4610
  await serialWrite(async () => {
4553
4611
  if (chunkResults.length > 0) await appendFile(files.resultsNdjson, ndjson(chunkResults), { mode: 384 });
4554
4612
  if (!outcome.stop) {
4555
- chunksDone.add(index);
4613
+ chunksDone.add(index2);
4556
4614
  await writeState();
4557
4615
  }
4558
4616
  });
@@ -4570,10 +4628,10 @@ async function runBatch(spec, ctx) {
4570
4628
  }
4571
4629
  ctx.output.progress(`chunk ${chunksDone.size}/${chunkCount}, ${rowsDone} rows, ${failed} failed`);
4572
4630
  };
4573
- const runChunk = async (index) => {
4631
+ const runChunk = async (index2) => {
4574
4632
  let outcome;
4575
4633
  try {
4576
- outcome = await spec.execChunk(chunks[index], { client: ctx.client, runId: record3.runId, chunkIndex: index, signal: chunkSignal });
4634
+ outcome = await spec.execChunk(chunks[index2], { client: ctx.client, runId: record3.runId, chunkIndex: index2, signal: chunkSignal });
4577
4635
  } catch (err) {
4578
4636
  if (chunkSignal.aborted) return;
4579
4637
  if (err instanceof KensoError && err.exitCode === ExitCode.Interrupted) {
@@ -4592,32 +4650,32 @@ async function runBatch(spec, ctx) {
4592
4650
  const error = errorText(err);
4593
4651
  const reason = err instanceof KensoError ? err.code : void 0;
4594
4652
  outcome = {
4595
- results: chunks[index].map((item) => ({ row: spec.rowOf(item), status: "failed", ...reason ? { reason } : {}, error }))
4653
+ results: chunks[index2].map((item) => ({ row: spec.rowOf(item), status: "failed", ...reason ? { reason } : {}, error }))
4596
4654
  };
4597
4655
  }
4598
- await recordChunk(index, outcome);
4656
+ await recordChunk(index2, outcome);
4599
4657
  };
4600
4658
  const halted = () => stop !== void 0 || interruptedByError || fatal !== void 0 || ctx.signal.aborted;
4601
4659
  for (; ; ) {
4602
4660
  if (!halted()) {
4603
4661
  for (let p = 0; p < pending.length; ) {
4604
4662
  if (running.size >= (throttled ? 1 : limit)) break;
4605
- const index = pending[p];
4606
- const keys = chunkKeys[index];
4663
+ const index2 = pending[p];
4664
+ const keys = chunkKeys[index2];
4607
4665
  if (keys.some((key) => busyKeys.has(key))) {
4608
4666
  p++;
4609
4667
  continue;
4610
4668
  }
4611
4669
  pending.splice(p, 1);
4612
4670
  for (const key of keys) busyKeys.add(key);
4613
- const task = runChunk(index).catch((err) => {
4671
+ const task = runChunk(index2).catch((err) => {
4614
4672
  fatal ??= err;
4615
4673
  engineAbort.abort();
4616
4674
  }).finally(() => {
4617
- running.delete(index);
4675
+ running.delete(index2);
4618
4676
  for (const key of keys) busyKeys.delete(key);
4619
4677
  });
4620
- running.set(index, task);
4678
+ running.set(index2, task);
4621
4679
  }
4622
4680
  }
4623
4681
  if (running.size === 0) break;
@@ -6657,10 +6715,10 @@ function shellQuote(value) {
6657
6715
  }
6658
6716
  function paramIndex(op) {
6659
6717
  const all = [...op.routeParams, ...op.queryParams, ...op.body?.props ?? []];
6660
- const index = /* @__PURE__ */ new Map();
6661
- for (const param of all) if (!index.has(param.name)) index.set(param.name, param);
6662
- for (const param of all) if (!index.has(param.flag)) index.set(param.flag, param);
6663
- return index;
6718
+ const index2 = /* @__PURE__ */ new Map();
6719
+ for (const param of all) if (!index2.has(param.name)) index2.set(param.name, param);
6720
+ for (const param of all) if (!index2.has(param.flag)) index2.set(param.flag, param);
6721
+ return index2;
6664
6722
  }
6665
6723
  function convert(text4, param, key) {
6666
6724
  if (!param) return text4;
@@ -6690,11 +6748,11 @@ function convert(text4, param, key) {
6690
6748
  return text4;
6691
6749
  }
6692
6750
  }
6693
- function rowToValues(row, index) {
6751
+ function rowToValues(row, index2) {
6694
6752
  const values = {};
6695
6753
  for (const [key, raw] of Object.entries(row)) {
6696
6754
  if (raw === void 0) continue;
6697
- const param = index.get(key);
6755
+ const param = index2.get(key);
6698
6756
  const name = param?.name ?? key;
6699
6757
  if (typeof raw === "string") {
6700
6758
  const text4 = raw.trim();
@@ -6775,13 +6833,13 @@ async function runEach(ctx, op, values, file, opts = {}) {
6775
6833
  throw usageError(`--each sends one ${op.method} per row: add --yes to send them, or --dry-run to see the plan first.`, { field: "yes", next: applyCommand });
6776
6834
  }
6777
6835
  const input = await readInput(file, { stdin: ctx.stdin });
6778
- const index = paramIndex(op);
6836
+ const index2 = paramIndex(op);
6779
6837
  const items = [];
6780
6838
  const invalid = [];
6781
6839
  input.rows.forEach((raw, i) => {
6782
6840
  const row = i + 1;
6783
6841
  try {
6784
- items.push({ row, request: buildRequest(op, { ...values, ...rowToValues(raw, index) }) });
6842
+ items.push({ row, request: buildRequest(op, { ...values, ...rowToValues(raw, index2) }) });
6785
6843
  } catch (err) {
6786
6844
  if (!(err instanceof KensoError) || err.exitCode !== ExitCode.Usage) throw err;
6787
6845
  invalid.push({ row, status: "invalid", reason: err.code, error: err.message, ...err.field ? { field: err.field } : {} });
@@ -6826,6 +6884,7 @@ var init_each = __esm({
6826
6884
  // src/generated/execute.ts
6827
6885
  var execute_exports = {};
6828
6886
  __export(execute_exports, {
6887
+ COMPACT_FIELDS: () => COMPACT_FIELDS,
6829
6888
  DATA_KEY: () => DATA_KEY,
6830
6889
  HELP_FLAG_MAX: () => HELP_FLAG_MAX,
6831
6890
  HELP_NOTES_MAX: () => HELP_NOTES_MAX,
@@ -6935,6 +6994,15 @@ function operationFlags(op) {
6935
6994
  if (!taken.has("limit")) flags.push({ flag: "limit", type: "integer", required: false, description: "Page size." });
6936
6995
  if (!taken.has("cursor")) flags.push({ flag: "cursor", type: "string", required: false, description: "Start at this cursor (from a previous page)." });
6937
6996
  flags.push({ flag: "all", type: "boolean", required: false, description: "Follow every page and stream all items (NDJSON when piped)." });
6997
+ const compact = COMPACT_FIELDS[op.id];
6998
+ if (compact && !taken.has(FULL_FLAG)) {
6999
+ flags.push({
7000
+ flag: FULL_FLAG,
7001
+ type: "boolean",
7002
+ required: false,
7003
+ description: `Print every field of each row. Without it a row holds ${compact.join(", ")}; --fields picks your own.`
7004
+ });
7005
+ }
6938
7006
  }
6939
7007
  flags.push({
6940
7008
  flag: "each",
@@ -7183,6 +7251,14 @@ function printWarnings(ctx, body2) {
7183
7251
  if (isRecord3(warning) && typeof warning.message === "string") ctx.output.warn(warning.message);
7184
7252
  }
7185
7253
  }
7254
+ function compactRow(ctx, op, flags) {
7255
+ const fields = COMPACT_FIELDS[op.id];
7256
+ if (!fields || flags[FULL_FLAG] === true || ctx.flags.fields !== void 0 || ctx.flags.query !== void 0) return void 0;
7257
+ return (row) => isRecord3(row) ? Object.fromEntries(fields.filter((field) => field in row).map((field) => [field, row[field]])) : row;
7258
+ }
7259
+ async function* mapRows(rows, shape) {
7260
+ for await (const row of rows) yield shape(row);
7261
+ }
7186
7262
  async function runOperation(ctx, op, flags) {
7187
7263
  const secrets = secretParams(op);
7188
7264
  checkSecretSources(flags, secrets.map((s) => s.flag));
@@ -7205,11 +7281,13 @@ async function runOperation(ctx, op, flags) {
7205
7281
  if (isDestructive(op)) await confirmDestructive(ctx, `${commandOf(op)} sends ${req.method} ${req.path}`, `${sameCommand(ctx, op, flags)} --yes`);
7206
7282
  req.signal = ctx.signal;
7207
7283
  if (stream) return followEventStream(ctx, req, stream);
7284
+ const shape = compactRow(ctx, op, flags);
7208
7285
  if (op.list && flags.all === true) {
7209
7286
  if (isRecord3(req.body) && Array.isArray(req.body.countBy) && req.body.countBy.length > 0) {
7210
7287
  throw usageError("--all prints rows, not counts. Ask for countBy on one page (--limit 1), or leave it out.", { field: "all" });
7211
7288
  }
7212
- await ctx.output.list(ctx.client.paginate(req, op.method === "POST" ? { cursorIn: "body" } : void 0));
7289
+ const rows = ctx.client.paginate(req, op.method === "POST" ? { cursorIn: "body" } : void 0);
7290
+ await ctx.output.list(shape ? mapRows(rows, shape) : rows);
7213
7291
  return ExitCode.Ok;
7214
7292
  }
7215
7293
  const res = await ctx.client.request(req);
@@ -7225,7 +7303,7 @@ async function runOperation(ctx, op, flags) {
7225
7303
  ctx.output.object({ data: res.body.data, pagination: res.body.pagination, counts: res.body.counts });
7226
7304
  return ExitCode.Ok;
7227
7305
  }
7228
- await ctx.output.list(res.body.data);
7306
+ await ctx.output.list(shape ? res.body.data.map(shape) : res.body.data);
7229
7307
  const pagination = isRecord3(res.body.pagination) ? res.body.pagination : void 0;
7230
7308
  const next = pagination?.nextCursor;
7231
7309
  if (pagination?.hasMore === true && typeof next === "string" && next !== "") {
@@ -7292,7 +7370,9 @@ ${STREAM_HELP}` : op.method === "GET" ? "" : isDestructive(op) ? "\nIt deletes,
7292
7370
  // The same text helpNotes measures, so the pointer shows only when something was left out.
7293
7371
  cut || normalizedNotes(op).length > HELP_NOTES_MAX ? `Full notes: kenso describe ${op.resource} ${op.action}.` : ""
7294
7372
  ].filter(Boolean);
7295
- const footer = [...op.stream === "sse" ? [] : [rows], ...more.length ? [more.join(" ")] : []];
7373
+ const compact = COMPACT_FIELDS[op.id];
7374
+ const fields = compact ? `Each row holds ${compact.join(", ")}: --full prints every field, --fields <a,b> picks your own.` : "";
7375
+ const footer = [...fields ? [fields] : [], ...op.stream === "sse" ? [] : [rows], ...more.length ? [more.join(" ")] : []];
7296
7376
  return {
7297
7377
  resource: op.resource,
7298
7378
  action: op.action,
@@ -7314,7 +7394,7 @@ ${api}` : api,
7314
7394
  run: (ctx, args) => runOperation(ctx, op, args.flags)
7315
7395
  };
7316
7396
  }
7317
- 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;
7397
+ var STREAM_HELP, DATA_KEY, IDEMPOTENCY_KEY, IDEMPOTENCY_KEY_FLAG, SCALAR_TYPES, FLAG_ALIASES, OUT_FLAG, CONTACT_FIELDS, COMPACT_FIELDS, FULL_FLAG, LIST_PARAM_TEXT, HELP_NOTES_MAX, HELP_FLAG_MAX, FOOTER_FLAGS;
7318
7398
  var init_execute = __esm({
7319
7399
  "src/generated/execute.ts"() {
7320
7400
  "use strict";
@@ -7340,6 +7420,32 @@ var init_execute = __esm({
7340
7420
  ["q", "search"]
7341
7421
  ];
7342
7422
  OUT_FLAG = "out";
7423
+ CONTACT_FIELDS = ["id", "firstName", "lastName", "email", "title", "companyName", "emailValidity", "campaignId", "companyDomain", "linkedInUrl", "segmentId", "qualityScore", "doNotContact", "sequenceStopReason", "updatedAt"];
7424
+ COMPACT_FIELDS = {
7425
+ "threads.list": [
7426
+ "id",
7427
+ "personName",
7428
+ "channel",
7429
+ "fromName",
7430
+ "subject",
7431
+ "interest",
7432
+ "isRead",
7433
+ "lastMessageAt",
7434
+ "preview",
7435
+ "direction",
7436
+ "fromEmailAddress",
7437
+ "hasDraft",
7438
+ "campaignId",
7439
+ "contactId",
7440
+ "inboxId",
7441
+ "waitingSince",
7442
+ "personKey",
7443
+ "waitingCount"
7444
+ ],
7445
+ "contacts.list": CONTACT_FIELDS,
7446
+ "contacts.search": CONTACT_FIELDS
7447
+ };
7448
+ FULL_FLAG = "full";
7343
7449
  LIST_PARAM_TEXT = {
7344
7450
  limit: "Page size.",
7345
7451
  cursor: "Start at this cursor (the next: hint of a previous page)."
@@ -7368,8 +7474,8 @@ async function featuresFromEnv(env, flags = {}, overrides = {}) {
7368
7474
  }
7369
7475
  }
7370
7476
  async function listGenerated(opts = {}) {
7371
- const { loadManifest: loadManifest2 } = await Promise.resolve().then(() => (init_manifest(), manifest_exports));
7372
- const operations = loadManifest2().operations;
7477
+ const { listOperations: listOperations2 } = await Promise.resolve().then(() => (init_manifest(), manifest_exports));
7478
+ const operations = listOperations2();
7373
7479
  let features = [];
7374
7480
  if (operations.some((op) => op.featureGates)) {
7375
7481
  const source = opts.features;
@@ -8296,7 +8402,7 @@ var init_merge = __esm({
8296
8402
 
8297
8403
  // src/commands/work/common.ts
8298
8404
  import { randomUUID } from "node:crypto";
8299
- import { join as join7 } from "node:path";
8405
+ import { join as join8 } from "node:path";
8300
8406
  import { setTimeout as delay4 } from "node:timers/promises";
8301
8407
  function unavailable(err) {
8302
8408
  return err instanceof KensoError && (err.code === "network_error" || err.httpStatus === 502 || err.httpStatus === 503 || err.httpStatus === 504);
@@ -8370,8 +8476,8 @@ function leaseMinutes(flags) {
8370
8476
  function shellQuote5(value) {
8371
8477
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8372
8478
  }
8373
- function submitCommand(dir) {
8374
- return `kenso work submit ${shellQuote5(join7(dir, "/"))}*.answers.json`;
8479
+ function submitCommand(dir2) {
8480
+ return `kenso work submit ${shellQuote5(join8(dir2, "/"))}*.answers.json`;
8375
8481
  }
8376
8482
  function explainNotFound(err) {
8377
8483
  if (!(err instanceof KensoError) || err.httpStatus !== 404 || err.hint !== void 0) return err;
@@ -8671,7 +8777,7 @@ var init_connect = __esm({
8671
8777
  var crm_default;
8672
8778
  var init_crm = __esm({
8673
8779
  "docs/crm.md"() {
8674
- crm_default = '# CRM (beta)\n\nThe CRM commands work on Kenso\'s Accounts lane: accounts (companies), the people on them, and opportunities. They are beta: they need the `accounts` feature flag on your workspace (opportunities need `opportunities`, CRM sync needs `ingestion`). Help and `kenso describe` hide them until your workspace has the flag; `--all-commands` shows them.\n\n| Command | What it does |\n|---|---|\n| `accounts import` | Create accounts from a CSV or JSONL file. Research is charged per created account |\n| `people import` | Create or match people from a file, optionally onto accounts |\n| `import accounts <file.csv>`, `import people <file.csv>`, `import deals <file.csv>` | Import a CSV export of another CRM, up to 50,000 rows: Kenso proposes the mapping, you approve once, it runs in the background and can be undone for 30 days |\n| `accounts update --each`, `people update --each`, `opportunities update --each` | Edit many records from a file, one call per row |\n| `accounts bulk-update`, `people bulk-update`, `opportunities bulk-update` | Set the same fields on many records at once, by ids or by a filter, with a preview first. Needs `bulk_edit` too |\n| `accounts bulk-delete`, `people bulk-delete`, `opportunities bulk-delete` | Delete many records at once, by ids or by a filter, with a preview first. Not undone. Needs `bulk_edit` too |\n| `changes list`, `get`, `rows`, `apply`, `cancel`, `undo` | Follow a bulk change, read what each record got, stop it, or put the old values back for 30 days |\n| `accounts write-research`, `people write-research` | Store research you gathered as a record\'s latest research, free. `--each` writes many |\n| `opportunities move <id> [--stage <key>] [--pipeline <pipelineId>] [--reason <key>]` | Move a deal to a stage or another pipeline, with its won or lost reason; a field the stage asks for never stops it |\n| `opportunities stage-history <id>` | A deal\'s stage history: each stage, when, who moved it and how long it sat there |\n| `notes list`, `notes add`, `notes edit`, `notes delete` | Notes and comments on accounts, people and deals (needs `record_notes`) |\n| `deleted-accounts list`, `accounts restore <id>` | The accounts deleted in the last 30 days, and bringing one back |\n| `accounts duplicates`, `accounts merge <id> --into <id>`, `accounts merges list` | The pairs that look like one company, merging a pair, and the log of merges |\n| `export <accounts\\|people\\|deals>` | The list as CSV: everything, a saved Accounts view, or what the filters match |\n| `capture status` | Your captured mailbox, its backfill progress and what teammates see of a captured email. Needs the `crm_capture` flag |\n| `capture connect` | Turn capture on for your own mailbox. `--private` starts it hidden from teammates; `--provider google` prints a sign-in link when no account is connected yet |\n| `capture private on\\|off` | Hide your captured email from teammates, or show it again. Email only: meetings stay visible. `--thread <id>` sets the switch for one thread |\n| `capture thread <threadId>` | One captured email thread: subject, people, time, Ken\'s summary, the members whose mailboxes hold it, and each body you may open. The id is `capturedThread.id` on a timeline row |\n| `views pin <viewId>`, `views unpin <viewId>` | Pin a saved view to your own sidebar, or take it off. Needs the `shared_views` flag |\n| `capture sync` | Read your captured mailbox now, instead of waiting for the next two-minute poll. Prints what the pass read, logged and created |\n| `capture disconnect` | Turn capture off and delete your stored email bodies. Asks first; `--yes` skips the question |\n| `capture teammates-see summary\\|full_email` | Workspace admin: what teammates see of captured email |\n| `pipelines stage-rules` | List or set the fields a deal should have in each stage |\n| `opportunity-reasons get`, `opportunity-reasons replace` | List or edit why deals are lost and won |\n| `layouts show\\|set\\|reset <object>` | How every account, person or deal page in the workspace lays out its fields: header, rail sections and hidden fields (needs `record_layout`) |\n| `crm-connections`, `crm-imports`, `crm-sync-issues` | Read and run CRM sync. Connecting a CRM stays in the app |\n| `tasks add`, `tasks done`, `tasks assign`, `tasks queue` | Add a to-do for a member on an account, person or deal, complete it, hand it on, or read your open work (needs `tasks`) |\n\nImport accounts first, then people: `people import` never creates an account.\n\n## Import accounts\n\n```bash\nkenso accounts import --file accounts.csv\nkenso accounts import --file accounts.csv --yes\n```\n\n```csv\nname,domain,industry,employeeCount\nAcme,acme.io,Software,120\nGlobex,globex.com,Manufacturing,"1,200"\n```\n\n- **Columns** map by name, ignoring case, spaces and dashes: `name` (or `company`, `companyName`, `accountName`), `domains` (several, split on `,` or `;`) or one `domain` (or `website`, `companyDomain`), `industry`, `employeeCount`, `hqLocation`, `linkedinUrl`, `stage`, `angle`, `whyNow`, `fitScore`, `fundingRound`, `cadenceDays`, `ownerMemberId`, `kenCompanyId`, `sendsFromInboxId`, `sendsFromLinkedInAccountId` and `source`.\n- **A domain is required.** A file with no domain column is a usage error, and a row without a domain is `invalid` (`domain_required`).\n- **The dry run prices the research.** It asks for a credit estimate per 1,000 accounts and puts the sum in the plan: `kind`, `accountCount`, `totalMillicredits`, `availableMillicredits` and `sufficient`.\n- **Rows go 100 per call** to `POST /v1/accounts/bulk-create`.\n\nEach row comes back `created` (`id` is the new account; its research is queued, `researchQueued`, or waits for credits, `researchWaitingCredits`), `skipped` with reason `domain_taken` (already an account; `id` is that account) or `failed` (`reason` is the API\'s code, `error` names the field; an item Kenso failed to save is sent once more first). Rerunning the same file is safe: accounts that exist come back `domain_taken`.\n\n## Import people\n\n```bash\nkenso people import --file people.csv\nkenso people import --file people.csv --find-emails --yes\nkenso people import --file people.jsonl --dry-run\n```\n\n```csv\nfullName,email,title,accountDomain,role\nAnn Lee,ann@acme.io,VP Sales,acme.io,champion\nBob Ray,,CTO,acme.io,\n```\n\n- **Columns** map by name, ignoring case, spaces and dashes: `email`, `fullName` (or `name`), `firstName`, `lastName`, `title`, `linkedinUrl` (or `linkedin`, `profileUrl`), `accountDomain` (or `domain`, `website`, `companyDomain`), `accountId`, `role` and `priority`. Other columns are ignored with one warning.\n- **A person needs a name:** `fullName`, or `firstName`, `lastName` or both (the CLI joins them). A row with none of them is `invalid` (`name_required`).\n- **To put a person on an account,** give `accountDomain` or `accountId`. A row with both sends only `accountId`.\n- **`--find-emails`** queues an email find (charged in credits) for each person without an email.\n- **Rows go 200 per call** to `POST /v1/people/batch`.\n\nPeople already in the workspace are matched by email, then LinkedIn URL, so running the same file again creates nobody twice. A row comes back `created` (a new person), `updated` (an existing person added to the account), `skipped` with reason `already_on_account`, `matched` (no account asked) or `previously_removed`, or `failed`: `account_not_found` saves the person without an account (import the account, then rerun to place them), any other reason is the API\'s. The summary adds `matched`, `addedToAccounts` and `emailFindsQueued`.\n\n## List and search accounts\n\n`accounts list` and `accounts search` sort and page on the server, so they reach every account in the workspace, however many there are.\n\n```bash\nkenso accounts list --sort score:desc --limit 100 # one page; the output\'s next: line is the following one\nkenso accounts list --sort score:desc --limit 100 --all # every page, to the end\nkenso accounts search --search hiring --sort latestSignalAt:desc --data \'{"qFields": ["name", "latestSignal"]}\'\nkenso accounts search --limit 1 --data \'{"countBy": ["stage"]}\' # how many accounts sit in each stage\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "tier", "operator": "is", "values": ["1"]}]}, "sort": "tier,-pipelineAmount"}\' --all\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "hqLocation", "operator": "contains", "values": ["Germany"]}]}}\' --all\n# my accounts with a meeting this quarter: me is whoever runs it, so a saved view with it lists each member\'s own\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "owner", "operator": "is", "values": ["me"]}, {"field": "lastMeeting", "operator": "in_period", "values": ["this_quarter"]}]}}\' --all\n# tier 1 accounts with no meeting in 30 days: none since then, or none ever\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "tier", "operator": "is", "values": ["1"]}, {"match": "any", "conditions": [{"field": "lastMeeting", "operator": "older_than_days", "values": ["30"]}, {"field": "lastMeeting", "operator": "is_empty"}]}]}}\' --all\n```\n\n- **`--sort`** takes up to 3 comma-separated keys, each `field` (ascending), `field:asc` or `field:desc`. The API\'s `-field` form needs the equals sign here, `--sort=-score`, because a value that starts with a dash reads as a flag. Fields: `createdAt`, `name`, `score`, `tier` (ascending is tier 1 first), `latestSignalAt`, `committee`, `pipelineAmount`, `nextTouchAt`, `lastTouchAt`. An account with no value for a key comes last in both directions. The default is `-createdAt`.\n- **`--limit`** is 1 to 1000 (default 50). `--cursor` takes the previous page\'s `nextCursor` with the same filters and sort; `--all` follows the cursors for you.\n- **`--search`** (also `--q`) matches the name or a domain.\n- **Lists and objects go in `--data`** on `search`, as the API takes them (`kenso describe accounts search`); a flag beside it sets or replaces one key:\n - `qFields` picks where the search text looks: `name`, `domain`, `latestSignal` (the latest signal\'s title).\n - `countBy` (`stage`, `stageGroup`) adds `counts` to the output: every value with the number of matching accounts that hold it, whatever the page. The output is then one object: `data`, `pagination` and `counts`.\n - `filters` and `where` narrow the accounts.\n\nAn account\'s timeline pages the same way. `kenso accounts activity 812` returns the newest 100 earlier rows and, when older ones exist, `data.nextCursor`. Pass it back as `--cursor` (with the same `--category`) for the rows before them, until a page comes without one.\n\n## Edit accounts, people and opportunities\n\nTo set the same fields on many records, use `bulk-update` (below; it needs the `bulk_edit` flag). When every row gets its own values, or the workspace has no `bulk_edit`, run the generated `update` command once per row with `--each`. Columns are the command\'s flags by API name or flag name, and the id column fills the route:\n\n```bash\nkenso accounts update --each accounts-edit.csv --dry-run # then the same with --yes\nkenso people update --each people-edit.csv --dry-run\nkenso opportunities update --each deals.csv --dry-run\n```\n\n```csv\naccountId,stage,ownerMemberId,overwritePinned\n501,engaged,42,true\n502,customer,42,true\n```\n\nA row that changes a field someone pinned in the app fails as a whole (`409 conflict`, `pinned_by_user`: nothing on that record changes, the other fields of the row included), unless the row sets `overwritePinned` to `true` (or you pass `--overwrite-pinned`, only with the person\'s OK). Every flag of an update command: `kenso accounts update --help`.\n\n## Change many accounts at once\n\n```bash\nkenso accounts bulk-update --filter \'{"filters":[{"field":"stage","operator":"is","values":["new"]}]}\' --set owner=42 --dry-run\nkenso changes apply --change-id 31\nkenso accounts bulk-update --ids 812,813 --set stage=engaged --set tier=2 --yes\nkenso changes get --change-id 31\n```\n\n`accounts bulk-update` sets the same fields on every account you name: `--ids` (1,000 at most), everything a `--filter` matches (the body `kenso accounts search --data` takes: `filters`, `where`, `q`; up to 50,000), or `--all`. A filter that holds only options and no condition (`--filter \'{"includeImportOnly":true}\'`) takes `--all` beside it. `--exclude-ids` leaves some of a filter\'s accounts out. `--set field=value` takes `ownerMemberId` (or `owner`), `stage`, `tierOverride` (or `tier`), `industry`, `fundingRound`, `employeeCount`, `hqLocation` and `cadenceDays`, and a custom field as `custom.<key>` (`--set custom.region=EMEA`; `kenso api GET \'/v1/fields?object=account\'` gives the keys); a value of `null` clears the field. `--add-tag 12,14` and `--remove-tag 13` put tags on every account or take them off (`kenso tags list` gives the ids); each tag is one row per account from `false` to `true` or back, so `kenso changes undo` takes off only the tags the change put on. People take them too; deals have no tags. A text field\'s value is sent as you type it (`--set hqLocation=10001` is the text "10001"); a custom field\'s type is not known to the CLI, so quote its text when it reads as a number or as true or false: `--set \'custom.code="10001"\'`. Use `accounts update --each` when every row gets its own values.\n\nIt makes a change set: the accounts it names and, for each, the field, its value before and its value after. Without `--yes` (or with `--dry-run`) it previews: it prints `count` and a `sample`, writes nothing, and `next` is the `kenso changes apply` command that writes exactly those accounts. With `--yes` it writes in the background and waits (`--timeout`, default 10m), then prints the change with its `counts`: `applied`, `unchanged` (already had the value), `conflict` (the account changed after the preview, so it was left alone) and `failed` (for example `pinned`: a person set the field by hand; `--overwrite-pinned` replaces it). Exit 5 when some accounts failed or conflicted. It needs the `bulk_edit` flag as well as `accounts`.\n\n`kenso accounts bulk-update` used to be the generated command for the route\'s older one-field body, which sets one `accountType` on up to 500 accounts and needs only `accounts`. The route still takes that body, but this command no longer sends it: use `kenso accounts update --each` with an `accountType` column, or `kenso api POST /v1/accounts/bulk-update --data \'{"accountIds":[812,813],"accountType":"lost"}\'`.\n\n`people bulk-update` and `opportunities bulk-update` work the same way. People take `--set` for `ownerMemberId` (or `owner`), `leadStatus`, `title`, `seniority`, `department` and `location`, and a `--filter` of `kenso people search --data` fields (`leadStatus`, `roles`, `tagIds`, `q` and the rest). Deals take `stage` (a live stage key), `ownerMemberId` (or `owner`), `closeDate` (or `close`), `amount`, `dealType` and `nextStep`, and a `--filter` of `kenso opportunities search --data` fields (`filters`, `accountId`, `q`):\n\n```bash\nkenso opportunities bulk-update --filter \'{"filters":[{"field":"stageCategory","operator":"is","values":["open"]}]}\' --set stage=proposal --dry-run\nkenso people bulk-update --ids 501,502 --set owner=42 --yes\n```\n\n### Delete many records at once\n\n```bash\nkenso people bulk-delete --filter \'{"onAccount":"none","leadStatus":["disqualified"]}\' --dry-run\nkenso changes apply --change-id 32\nkenso opportunities bulk-delete --ids 71,72,73 --yes\n```\n\n`accounts bulk-delete`, `people bulk-delete` and `opportunities bulk-delete` name their records the way `bulk-update` does (`--ids`, `--filter`, `--all`, `--exclude-ids`) and take no `--set`. Without `--yes` they preview: `count`, a `sample`, and `next` is the `kenso changes apply` command that deletes exactly those records. The API itself previews a delete whose body leaves `dryRun` out, so `--yes` sends `dryRun: false`. Each record is deleted as its own `delete` command deletes it, so one that cannot be deleted (a person still on an account) is counted as `failed` and the rest go on. A delete is not undone with `kenso changes undo`.\n\n### Follow, stop and undo a change\n\n```bash\nkenso changes list --object accounts\nkenso changes rows --change-id 31 --status conflict,failed\nkenso changes cancel --change-id 31\nkenso changes undo --change-id 31\n```\n\n`changes list` shows the workspace\'s bulk changes, newest first, whoever made them. `changes rows` lists a change\'s records with the value before (`from`) and after (`to`) and a `status`; `--status conflict,failed` reads what a change missed. `changes cancel` drops a preview or stops a change that is still writing; what it already wrote stays. `changes undo` puts the old value back on every record that still holds the value the change wrote, for 30 days after it was applied (`undoUntil`). A record someone changed again since keeps its newer value: `counts.undone` is how many went back, `counts.applied` how many still hold the change. Undo answers `409 invalid_state` with `undo_expired`, `still_running`, `nothing_applied` or `not_undoable` when there is nothing it can put back.\n\n## Search opportunities\n\n`kenso opportunities search` works as `accounts search` does: it takes `--search`, `--sort`, `--limit`, `--cursor`, `--all`, and its lists in `--data`.\n\n```bash\nkenso opportunities search --data \'{"filters": [{"field": "stageCategory", "operator": "is", "values": ["open"]}]}\' --all\nkenso opportunities search --data \'{"filters": [{"field": "ownerMemberId", "operator": "is", "values": ["none"]}, {"field": "closeDate", "operator": "is", "values": ["past_due", "next_30_days"]}]}\'\nkenso opportunities search --limit 1 --data \'{"countBy": ["stage", "ownerMemberId"]}\' # how many opportunities hold each value\n```\n\n- **`filters`** is a list of `{field, operator, values}`, all of which must hold. Fields: `stage` (a stage key), `stageCategory` (`open`, `won`, `lost`), `ownerMemberId` (member ids, or `me` for whoever runs it), `closeDate` (`past_due`, `next_30_days`, `later`, `none`, or a period such as `this_week` or `next_quarter`), `sourceCampaignId`, `closedAt` and `createdAt` (periods). `operator` is `is` or `is_not`; the values of one condition are OR. `none` in `values` matches an opportunity with no owner, no source campaign or no close date.\n- **`countBy`** takes the same field names and adds `counts` to the output: per field, every value with the number of matching opportunities that hold it.\n- `--account-id` keeps the search to one account. `closeDate` counts days in the member\'s app time zone.\n\nOne person\'s deals, meetings and campaign contacts, as their person page lists them:\n\n```bash\nkenso opportunities list --person-id 9001 # the deals they are on, or are the primary person of\nkenso meetings list --person-id 9001 # the meetings they attend, among the ones you can see\nkenso contacts list --person-id 9001 # their contact in each campaign they are in\n```\n\n## Write research you gathered\n\n`accounts write-research` and `people write-research` store research you gathered outside Kenso as the record\'s latest research (`PUT /v1/accounts/{accountId}/research`, `PUT /v1/people/{personId}/research`). The Research tab shows it like a Ken run, with `trigger: agent` and `researchedAt` now. Nothing is charged, and no account or person field changes: set an account\'s own `fitScore`, `whyNow` or `angle` with `accounts update`. They need the `accounts_research` flag and accounts edit.\n\nThe body is the research block `accounts get --expand research` (or `people get-research`) returns, without its read-only fields: leave out `id`, `status`, `trigger`, `errorCode`, `researchedAt`, `isStale` and `appliedPrompt` (for a person also `mode`, `requestedAt`, `researchedMode`, `firecrawlCredits` and `webNote`), or the write fails with `unknown_field`. Pass it with `--data @file`:\n\n```bash\nkenso accounts write-research --account-id 501 --data @acme-dossier.json\nkenso people write-research --person-id 9001 --data @jane.json\n```\n\n```json\n{\n "tagline": { "text": "Payroll for EU contractors", "sourceUrls": ["https://acme.example"] },\n "description": { "text": "Acme runs payroll and compliance for companies hiring contractors in 30 EU countries.", "sourceUrls": ["https://acme.example"] },\n "links": { "website": "https://acme.example" },\n "whyNow": { "text": "Raised a $40M Series B in October", "sourceUrls": ["https://news.example/acme-b"], "date": "2026-10" },\n "fitScore": 82,\n "angle": "Lead with contractor onboarding time."\n}\n```\n\nMany records: one JSONL line per record, with the id next to the block\'s fields. Nested objects are sent as written. Use JSONL, not CSV: the block\'s fields are objects and lists, which a CSV cell cannot carry.\n\n```bash\nkenso accounts write-research --each dossiers.jsonl --dry-run # then the same with --yes\nkenso people write-research --each people-research.jsonl --yes --concurrency 8\n```\n\n```jsonl\n{"accountId": 501, "tagline": {"text": "Payroll for EU contractors"}, "links": {"website": "https://acme.example"}}\n{"accountId": 502, "description": {"text": "Cloud cost tooling for retailers."}, "links": {"website": "https://beta.example"}}\n```\n\nA row fails as a whole with the API\'s code: `validation_failed` (an unknown field is `unknown_field`, and `error.details` names every bad field), `research_in_progress` (`409`: Ken is researching that record now, write it again once the run ends; an account run waiting for credits counts too: it runs once the workspace has credits, and the write stays refused until that run ends) or `not_found`. Rerunning a file is safe: each write replaces the record\'s research shown.\n\n## CRM sync\n\nCRM sync has generated commands only: read connections, preview, start an import, and work through sync issues. Connect the CRM itself in the app.\n\n```bash\nkenso crm-connections list\nkenso crm-connections get --connection-id 7\nkenso crm-imports create --connection-id 7 --dry-run\nkenso crm-sync-issues list --connection-id 7 --all\n```\n\nRun `kenso crm-connections --help` (or add `--all-commands` when the actions are hidden) to see every action.\n\n## Pipelines\n\nA workspace with the `pipelines` flag on can run several deal pipelines, each with its own stages. These are generated commands (beta):\n\n```bash\nkenso pipelines list\nkenso pipelines list --query "[].{id: id, name: name, default: isDefault, stages: stages[].key}"\nkenso pipelines get --pipeline-id 5\n```\n\n`list` prints every pipeline in display order, archived ones included: `id`, `name`, `routingRule` (the one sentence Ken reads to decide whether a new deal belongs there), `isDefault`, `isArchived`, `position`, `opportunityCount`, `amountTotal` and `stages`, each stage as `kenso opportunity-stages list` prints it. A stage key is unique in the workspace, across pipelines, so a deal\'s `stage` names its pipeline and its `pipelineId` repeats it. The first read turns the workspace\'s stage list into its default pipeline, named Sales, with every deal in it. The same rows as the MCP\'s `pipelines(operation="list")`.\n\nShaping them needs the `workspace_settings` permission:\n\n```bash\nkenso pipelines create --name Renewals --routing-rule "The account is already a customer" --data \'{"stages": [{"label": "Up for renewal", "category": "open"}, {"label": "Won", "category": "won"}, {"label": "Lost", "category": "lost"}]}\'\nkenso pipelines update --pipeline-id 6 --name Expansion --position 0\nkenso pipelines update --pipeline-id 6 --data @stages.json\nkenso pipelines archive --pipeline-id 6\nkenso pipelines restore --pipeline-id 6\nkenso pipelines propose --description "upsells and renewals for customers"\n```\n\n- **`create`** takes a unique `name`, the pipeline\'s `stages` in display order (at least one `open`, one `won` and one `lost`) and an optional `routingRule`: one sentence that says which deals belong there, which Ken reads to route a new deal that names no pipeline. Each stage gets a key from its label; a key another pipeline already uses gets the pipeline\'s name in front (`renewals_won`). A workspace has at most 10 pipelines.\n- **`update`** changes what you send. `stages` is the pipeline\'s whole stage list: read it with `pipelines get`, keep each stage\'s `key`, and add a new stage without one. A stage with live deals in it cannot be left out; archive it with `"isArchived": true` instead.\n- **`propose`** asks Ken to draft a pipeline from one sentence: a `name`, a `routingRule` and `stages`, in the shape `create` takes. It saves nothing. Read it, change what you want, and send it to `create`.\n- **`archive`** stops new deals from entering a pipeline and keeps the deals in it. The default pipeline cannot be archived, and nothing is deleted: `restore` brings a pipeline back.\n\n## Deals in a pipeline\n\nA deal\'s stage names its pipeline, and the deal\'s `pipelineId` repeats it. To work one pipeline\'s deals, or move a deal between pipelines:\n\n```bash\nkenso opportunities list --pipeline-id 6\nkenso opportunities search --pipeline-id 6 --data \'{"countBy": ["stage"]}\'\nkenso opportunities create --account-id 501 --pipeline-id 6\nkenso opportunities move 77 --pipeline 6\nkenso opportunities move 77 --pipeline 6 --stage negotiating\n```\n\n- **`create --pipeline-id`** opens the deal in that pipeline\'s first live open stage. Without it, and without a `stage`, Ken reads each pipeline\'s `routingRule` and opens the deal in the pipeline whose rule clearly fits the account, else in the default pipeline. A pipeline you name always wins.\n- **`move --pipeline`** alone keeps the deal\'s category (`open`, `won` or `lost`): it lands in that pipeline\'s live stage of the category with the same label as its stage now, else in the category\'s first live stage. The printed deal says where it landed. With `--stage`, the stage must be that pipeline\'s; the error lists the pipeline\'s stage keys otherwise.\n- An archived pipeline takes no deal from another pipeline (`pipeline_archived`). The deals already in it still move between its stages.\n- A move is a stage change: it writes the same history, and a stage a person set is refused with `pinned_by_user` unless you pass `--overwrite-pinned`.\n\n## Restore a deleted account\n\n```bash\nkenso deleted-accounts list\nkenso accounts restore 812\n```\n\nA deleted account can be restored for 30 days. `deleted-accounts list` shows each one with who deleted it, `expiresAt` (restore works until then) and what comes back: `personCount`, `opportunityCount` and `touchCount`. `accounts restore <id>` brings the account back with its domains, its people, its deals and its planned touches, which wait for approval again. A domain another account took since stays with that account and is listed in `domainsTaken`. A merged account is not listed and cannot be restored: a merge has no undo. Both commands are behind the `crm_import_export` feature flag (`404` while it is off).\n\n## Import a CSV export of another CRM\n\n```bash\nkenso import accounts companies.csv\nkenso import accounts companies.csv --map "Company=name" --map "Notes=" --yes\nkenso import accounts --id 42 --yes\nkenso record-import-rows list --import-id 42 --outcome skipped\nkenso record-imports undo --import-id 42\n```\n\n`kenso import accounts <file.csv>` uploads the file (a header row, at most 50,000 rows) and prints Kenso\'s plan: which field each column fills, which columns it skips, how owner and stage values are read (`valueMaps`) and what it could not settle (`questions`). Headers of Kenso, Twenty, HubSpot, Attio and Salesforce exports are recognized. Nothing is written to your accounts yet. `--map "Header=field"` changes a column and `--map "Header="` skips it. A column fills a custom field with `--map "Header=custom.<key>"` (`kenso fields list --object account` has the keys; people are `person`, deals `opportunity`), and `--map "Header=new"` adds the custom field Kenso proposes for a column no field matches (`new:text` picks the type), and a column whose header is a custom field\'s label is mapped to it already; owner and stage values change with `kenso record-imports update --import-id <id>`.\n\nWith `--yes` the import starts and the command waits for it (`--timeout`, default 30m; the import keeps running on the server either way), then prints how many rows were created, updated, restored, left unchanged and skipped. Without `--yes` it stops at the plan and prints the command that starts that import (`--id <importId> --yes`), so the file is uploaded once. `--dry-run` sends nothing: with a file it prints the upload it would make, since the plan needs the upload, and with `--id` it reads the planned import and prints what `--map`, `--source` and `--research` would change on it. `--source twenty` names the system the file\'s record ids come from: pass the same one for every file of an export, so the people and deals files find the accounts by their old ids. `kenso record-imports delete --import-id <id>` discards an import that was planned and never started; one left planned for 30 days is discarded by itself.\n\nPer row: a domain no account has creates an account; a domain that is already an account fills only that account\'s empty fields, so nothing you entered is overwritten; an account deleted in the last 30 days is restored; a row with no usable domain is skipped, and `kenso record-import-rows list --import-id <id> --outcome skipped` says why. Research of new accounts is off unless you pass `--research`, which is charged per account. It needs the `accounts` and `crm_import_export` flags. This is a different command from `accounts import`, which creates accounts row by row from the machine running the CLI.\n\n`kenso record-imports undo --import-id <id>` takes a finished import back in the background (`kenso record-imports get --import-id <id>` reads `undoing`, then `undone`): an account the import created is deleted, and can be restored for 30 days, unless someone changed it since, it holds a deal, a person was added to it since, or it was merged; a field the import filled is emptied while it still holds the imported value. `kenso record-import-rows list --import-id <id>` shows each row\'s `undoOutcome`.\n\n`kenso import people <file.csv>` works the same way for people. Import the accounts file first: a people row\'s company id (Twenty\'s `Company Id`, HubSpot\'s associated company id) places the person on the account that kept that id, and without one the person goes on the account that holds their email\'s or company\'s domain. A people import never creates an account; a person whose company is no account comes in without one and the row says so. A row matches a person by email, then LinkedIn URL, then name on the company, as every other way into People does; a matched person gets only their empty fields filled (a phone only when they have none). A row with none of the three is skipped, and a row with only a name needs a company that is an account with a domain. `kenso record-imports undo --import-id <id>` takes a people import back too: a person it created leaves the accounts the row placed them on and is deleted, unless someone changed them since, they were contacted or have a touch planned, or they are on an open deal; a field it filled is emptied while it still holds the imported value. `kenso people import` stays the JSONL and enrichment path (`--find-emails`); `kenso import people` is the CRM file with a plan, a row report and one approval.\n\n`kenso import deals <file.csv>` works the same way for deals, after the accounts file and the people file. A row opens a deal on the account that kept its company id (Twenty\'s `Company Id`, HubSpot\'s associated company id), else on the account that holds its company domain; a row whose account Kenso does not know is skipped and says so. Its contact is the person a people import kept the row\'s contact id for (Twenty\'s `Point of Contact Id`). The plan maps each stage in the file to one of the workspace\'s deal stages (`valueMaps`, field `stage`): a stage\'s key or label matches by itself, Closed Won and Closed Lost go to the first won and lost stage, and a value with no match opens in the first open stage until you pick one with `kenso record-imports update`. Amounts stay in the workspace currency: an amount in another currency is left out with a warning, never converted. A row whose deal id an earlier import kept is that deal and only gets its empty fields filled; a file with no id column opens every deal again each time it is imported, and the plan says so (`no_source_id`). `kenso record-imports undo --import-id <id>` takes a deals import back: a deal it opened is deleted unless someone changed it since, and a field it filled is emptied while it still holds the imported value. Undo in the reverse order of the imports (deals, then people, then accounts): an account that holds a deal is kept.\n\n## Export accounts, people or deals\n\n```bash\nkenso export accounts --out accounts.csv\nkenso export accounts --view 12 --out tier-1.csv\nkenso export deals --filters \'[{"field":"stageCategory","operator":"is","values":["open"]}]\' > open-deals.csv\n```\n\nIt writes the CSV that `POST /v1/accounts/export`, `/v1/people/export` or `/v1/opportunities/export` returns, to stdout or to `--out` (then it prints the file and its row count). With no filter it exports every record. More than 50,000 rows is refused: narrow the filters. `--view <id>` exports a saved Accounts view (`kenso account-views list` shows the ids). `--filters`, `--where` (accounts), `--q` and `--sort` are the search operation\'s own fields, so a deals or people view exports with its filters and sort. The accounts and deals files start with `id` and import back as they are. Each export writes an audit-log entry and needs the export permission. Accounts and deals also need the `crm_import_export` flag while it is in beta.\n\n## Duplicates and merges\n\n```bash\nkenso accounts duplicates --scan\nkenso accounts merge 812 --into 77 --dry-run\nkenso accounts merge 812 --into 77 --yes\nkenso accounts merges list --merged-by system\nkenso accounts merges 41\n```\n\nThese need the `crm_import_export` flag beside `accounts`. `accounts duplicates` lists the pairs of accounts that look like one company: both accounts, why they were paired (`reasons`: `domain`, `linkedin`, `name`) and `isCertain`, true when the two share the name and the domain apart from its ending (acme.com and acme.co). `--scan` compares every account first; a scan also runs after each accounts import. `--status dismissed` or `merged` shows the answered pairs. `kenso account-duplicates dismiss --duplicate-id <duplicateId>` answers that a pair is not a duplicate, for good.\n\n`accounts merge <accountId> --into <id>` merges the first account into the second, the one you keep. A merge cannot be undone, so look first: `--dry-run` prints `mergeSummary` (each field that changes with its value before and after, and how many people, deals, touches and domains move) and writes nothing. The merge itself needs `--yes` when no person is at the terminal. It answers the kept account with the same summary and a `mergeId`.\n\n`accounts merges list` is the log, newest first, and `accounts merges <mergeId>` opens one merge with `mergedValues`: the merged-away account as it was. `--merged-by system` shows the merges Ken made itself. Where automatic merging is on for the workspace, Ken merges only certain pairs, keeps the customer, then the owned, then the last touched account, and leaves a pair for you when both are customers, the two have different owners, or one is being worked and the other is set aside (`heldReason` on the pair says which). That job is off unless it was turned on for the workspace.\n\n## A deal\'s stage history\n\n```bash\nkenso opportunities stage-history 77\nkenso opportunities stage-history 77 --query "entries[].{to: stageLabel, at: enteredAt, by: changedBy}"\n```\n\nIt prints `GET /v1/opportunities/{id}/stage-history` as it is, the same rows as the deal page and the MCP\'s `opportunities(operation="get-stage-history")`: the stage now, `isComplete` and `entries`, oldest first, each with `fromStage`, `stage`, `stageLabel`, `enteredAt`, `leftAt`, `durationSeconds`, `actorKind`, `actorMemberId` and Ken\'s `reason` on a move its stage judge made. With the `deal_stage_rules` flag on, each entry also has `changedBy` (`member`, `agent`, `api_key`, `workflow`, `stage_judge`, `crm_sync` or `ken_automation`), `crmProvider` on a CRM sync, and on a move `fromStageLabel` and `fromStageDurationSeconds`, how long the deal sat in the stage it left. `isComplete` false means Kenso has no record of part of the history.\n\n## Notes on accounts, people and deals\n\nWith the `record_notes` feature on, everyone who can see a record reads its notes. Name the record with exactly one of `--account`, `--person` and `--deal`:\n\n```bash\nkenso notes list --account 5\nkenso notes add --account 5 --body \'Budget approved, @[Jane Doe](41) please send the DPA\'\nkenso notes add --parent 900 --body \'Sent it this morning\' # a comment under note 900\ncat call-notes.md | kenso notes add --deal 77 --body - # the body from stdin\nkenso notes edit 900 --body \'Budget approved for Q1\' # the author only\nkenso notes edit 900 --pin\nkenso notes delete 900 --yes # kenso notes restore 900 brings it back\n```\n\nThe body is markdown, up to 20,000 characters. Mention a teammate as `@[Name](memberId)`: they get a notification that opens the note. A note shows on the record\'s Notes tab and its Activity timeline, and Ken\'s account brief quotes the account\'s notes. The MCP\'s `notes` tool does the same. A note on an account needs the accounts plan feature; people and deals work on every plan.\n\n## Required fields per stage\n\n```bash\nkenso pipelines stage-rules\nkenso pipelines stage-rules proposal --require amount,closeDate,custom.tier\nkenso pipelines stage-rules proposal --none\nkenso pipelines stage-rules lost --default\n```\n\nWith the `deal_stage_rules` flag on, each stage can name the fields a deal should have in it. Without a stage the command prints every stage\'s `key`, `label`, `category`, `isArchived`, `requiredFields` and `isDefault`, plus `requirableFields`: `amount`, `closeDate`, `ownerMemberId`, `primaryPersonId`, `nextStep`, `lostReasonKey`, `wonReasonKey` and `custom.<key>` for each custom deal field. `--require` sets the stage\'s whole list, in order, at most 10. `--none` requires nothing, and `--default` goes back to the default: a lost stage asks for `lostReasonKey`, any other stage nothing. Setting a rule needs the `workspace_settings` permission. The same as the MCP\'s `opportunities(operation="stages-set-required-fields")`.\n\nA missing field never stops a move. The deal moves, and it is flagged Missing on the board, the list and the deal page until the field is filled. A rule also applies to deals already in the stage.\n\n```bash\nkenso opportunities update --opportunity-id 4401 --stage proposal\nkenso opportunities list --missing-fields\n```\n\nEvery deal then carries `missingFields` (`[{field, label}]`). A create, or an update that sends a stage, answers `warnings` beside the deal for each field the stage asks for that the deal leaves empty: each prints on stderr as `warning: <message>`, stdout stays the deal and the exit code stays 0. `--missing-fields` keeps only the deals flagged Missing (also `missingFields: true` on `kenso opportunities search`).\n\n## Won and lost reasons\n\n```bash\nkenso opportunity-reasons get\nkenso opportunity-reasons replace --kind lost --data \'{"reasons":[{"key":"no_budget","label":"No budget"},{"label":"Built it in-house"}]}\'\nkenso opportunities move 4401 --stage lost --reason built_it_in_house\n```\n\n`kenso opportunities move <id> --stage <key> [--reason <key>]` sends the reason as `lostReasonKey` for a lost stage or `wonReasonKey` for a won stage; an open stage takes none. Each field the new stage asks for that the deal leaves empty prints a warning on stderr, and the move still goes through.\n\nWith the `deal_stage_rules` flag on, each workspace edits why its deals are lost and won. `get` prints `lost` and `won`, each `{isDefault, reasons: [{key, label, isArchived}]}`. `replace` takes a kind\'s whole list in order, as `get` prints it: keep a reason by its `key`, leave `key` out for a new one, and set `isArchived` to archive a reason or bring one back. A reason left out is archived too: deals keep it, and no write can pick it again. At least one reason stays live and at most 30, and labels stay unique, archived ones included. A deal takes a live key in `lostReasonKey` (a lost stage) or `wonReasonKey` (a won stage). A move to Lost without a reason still goes through, with a warning and "Missing: Lost reason" on the deal. Editing the lists needs the `workspace_settings` permission. The same as the MCP\'s `pipelines(operation="reasons-get")` and `reasons-replace`.\n\n## Record page layouts\n\n```bash\nkenso layouts show account\nkenso layouts set account --header tier,ownerMemberId,score,custom.arr\nkenso layouts show account > layout.json && kenso layouts set account --data @layout.json\nkenso layouts reset account\n```\n\nWith the `record_layout` flag on, a workspace lays out each record page once, for every member: `account`, `person` or `opportunity` (a deal). `show` prints `GET /v1/record-layouts/{object}`: `isDefault`, `version`, `headerFields` (up to 6, pinned under the record\'s name), `railSections` (`{name, fields}`), `hiddenFields` (under the rail\'s More), `sections` (`{key, label, placement, locked, hidden}`, in page order) and `availableFields`. Field keys are the field catalog\'s (`ownerMemberId`, `closeDate`, `primaryDomain`); a custom field is `custom.<field_key>`, and a new one joins the last rail section.\n\n`set --header` pins up to 6 fields and keeps the rest of the saved layout; the fields it unpins go to the top of the first rail section. `set --data` saves a whole layout, so group the rail into sections or hide a section that way, starting from `show`. A save made after someone else\'s answers a conflict: show it again. `reset` puts the page back to Kenso\'s default. Saving needs the `workspace_settings` permission, and the account page also needs the `accounts` plan. The same as the MCP\'s `account_views` operations `record-layouts-get`, `record-layouts-replace` and `record-layouts-reset`.\n\n## Pin a saved view\n\n```bash\nkenso views pin 118\nkenso views unpin 118\n```\n\nWith the `shared_views` flag on, `views pin` adds a saved view to your own sidebar, nested under its list (an account view under Accounts, a person view under People, a deal view under Deals). It is `kenso pins add --kind view --view-id <viewId>` under the name you would try: it prints the pin, and a view already pinned answers the pin it has. Pins are yours alone: pinning a shared view does not pin it for a teammate. `views unpin` finds your pin of the view and removes it, and prints `{"viewId": ..., "removed": true}`; a view you had not pinned prints `removed: false` and changes nothing. The view itself stays either way. `kenso pins list` shows every pin you have.\n\n## Tasks\n\nTasks are to-dos a member owes: a title, an optional due day or time, an assignee and at most one account, person or deal. They need the `tasks` flag. The app calls deals "Deals"; the CLI keeps `--deal` for an opportunity id.\n\n```bash\nkenso tasks add "Send the deck" --due tomorrow --account 812\nkenso tasks add "Call Ada back" --due friday --at 16:00 --person 501 --assignee ada@acme.com\nkenso tasks list --assignee me --due overdue,today\nkenso tasks queue --scope mine\nkenso tasks assign 7 me\nkenso tasks done 7 8 9\nkenso tasks done 7 --undo\n```\n\n- `tasks add` sends `POST /v1/tasks`. `--due` takes `today`, `tomorrow`, a weekday (the next one: `friday` or `fri`), a day (`2026-11-20`) or an ISO 8601 time; `--at HH:MM` puts a time on that day (today without `--due`). Day words and `--at` read this computer\'s clock and time zone (`TZ`); a time\'s day is read in the assignee\'s app time zone. `--assignee` takes `me`, a member id or an email; without it the task is yours.\n- `tasks done` completes each task it names, in order (`PATCH /v1/tasks/{id}` with `status: done`); `--undo` reopens them. `tasks assign` gives a task to `me`, a member id or a member\'s email; that member gets a `task_assigned` notification.\n- `tasks queue` is `task-queue list` under the name you would try: the Tasks screen\'s open work by due day, with `--scope mine|assigned_by_me|everyone`. It lists tasks, manual touches, call tasks, inbox threads with a reminder due (when you can view the Inbox) and Ken\'s follow-ups to you, each with the app path in `href` (null for a task, which opens in its panel).\n- `tasks list`, `get`, `update`, `delete`, `restore` and `task-queue list` are generated from the API: `kenso tasks --help` lists them.\n';
8780
+ crm_default = '# CRM (beta)\n\nThe CRM commands work on Kenso\'s Accounts lane: accounts (companies), the people on them, and opportunities. They are beta: they need the `accounts` feature flag on your workspace (opportunities need `opportunities`, CRM sync needs `ingestion`). Help and `kenso describe` hide them until your workspace has the flag; `--all-commands` shows them.\n\n| Command | What it does |\n|---|---|\n| `accounts import` | Create accounts from a CSV or JSONL file. Research is charged per created account |\n| `people import` | Create or match people from a file, optionally onto accounts |\n| `import accounts <file.csv>`, `import people <file.csv>`, `import deals <file.csv>` | Import a CSV export of another CRM, up to 50,000 rows: Kenso proposes the mapping, you approve once, it runs in the background and can be undone for 30 days |\n| `accounts update --each`, `people update --each`, `opportunities update --each` | Edit many records from a file, one call per row |\n| `accounts bulk-update`, `people bulk-update`, `opportunities bulk-update` | Set the same fields on many records at once, by ids or by a filter, with a preview first. Needs `bulk_edit` too |\n| `accounts bulk-delete`, `people bulk-delete`, `opportunities bulk-delete` | Delete many records at once, by ids or by a filter, with a preview first. Not undone. Needs `bulk_edit` too |\n| `changes list`, `get`, `rows`, `apply`, `cancel`, `undo` | Follow a bulk change, read what each record got, stop it, or put the old values back for 30 days |\n| `accounts write-research`, `people write-research` | Store research you gathered as a record\'s latest research, free. `--each` writes many |\n| `opportunities move <id> [--stage <key>] [--pipeline <pipelineId>] [--reason <key>]` | Move a deal to a stage or another pipeline, with its won or lost reason; a field the stage asks for never stops it |\n| `opportunities stage-history <id>` | A deal\'s stage history: each stage, when, who moved it and how long it sat there |\n| `notes list`, `notes add`, `notes edit`, `notes delete` | Notes and comments on accounts, people and deals (needs `record_notes`) |\n| `deleted-accounts list`, `accounts restore <id>` | The accounts deleted in the last 30 days, and bringing one back |\n| `accounts duplicates`, `accounts merge <id> --into <id>`, `accounts merges list` | The pairs that look like one company, merging a pair, and the log of merges |\n| `export <accounts\\|people\\|deals>` | The list as CSV: everything, a saved Accounts view, or what the filters match |\n| `capture status` | Your captured mailbox, its backfill progress and what teammates see of a captured email. Needs the `crm_capture` flag |\n| `capture connect` | Turn capture on for your own mailbox. `--private` starts it hidden from teammates; `--provider google` prints a sign-in link when no account is connected yet |\n| `capture private on\\|off` | Hide your captured email from teammates, or show it again. Email only: meetings stay visible. `--thread <id>` sets the switch for one thread |\n| `capture thread <threadId>` | One captured email thread: subject, people, time, Ken\'s summary, the members whose mailboxes hold it, and each body you may open. The id is `capturedThread.id` on a timeline row |\n| `views pin <viewId>`, `views unpin <viewId>` | Pin a saved view to your own sidebar, or take it off. Needs the `shared_views` flag |\n| `capture sync` | Read your captured mailbox now, instead of waiting for the next two-minute poll. Prints what the pass read, logged and created |\n| `capture disconnect` | Turn capture off and delete your stored email bodies. Asks first; `--yes` skips the question |\n| `capture teammates-see summary\\|full_email` | Workspace admin: what teammates see of captured email |\n| `pipelines stage-rules` | List or set the fields a deal should have in each stage |\n| `opportunity-reasons get`, `opportunity-reasons replace` | List or edit why deals are lost and won |\n| `layouts show\\|set\\|reset <object>` | How every account, person or deal page in the workspace lays out its fields: header, rail sections and hidden fields (needs `record_layout`) |\n| `crm-connections`, `crm-imports`, `crm-sync-issues` | Read and run CRM sync. Connecting a CRM stays in the app |\n| `tasks add`, `tasks done`, `tasks assign`, `tasks queue` | Add a to-do for a member on an account, person or deal, complete it, hand it on, or read your open work (needs `tasks`) |\n\nImport accounts first, then people: `people import` never creates an account.\n\n## Import accounts\n\n```bash\nkenso accounts import --file accounts.csv\nkenso accounts import --file accounts.csv --yes\n```\n\n```csv\nname,domain,industry,employeeCount\nAcme,acme.io,Software,120\nGlobex,globex.com,Manufacturing,"1,200"\n```\n\n- **Columns** map by name, ignoring case, spaces and dashes: `name` (or `company`, `companyName`, `accountName`), `domains` (several, split on `,` or `;`) or one `domain` (or `website`, `companyDomain`), `industry`, `employeeCount`, `hqLocation`, `linkedinUrl`, `stage`, `angle`, `whyNow`, `fitScore`, `fundingRound`, `cadenceDays`, `ownerMemberId`, `kenCompanyId`, `sendsFromInboxId`, `sendsFromLinkedInAccountId` and `source`.\n- **A domain is required.** A file with no domain column is a usage error, and a row without a domain is `invalid` (`domain_required`).\n- **The dry run prices the research.** It asks for a credit estimate per 1,000 accounts and puts the sum in the plan: `kind`, `accountCount`, `totalMillicredits`, `availableMillicredits` and `sufficient`.\n- **Rows go 100 per call** to `POST /v1/accounts/bulk-create`.\n\nEach row comes back `created` (`id` is the new account; its research is queued, `researchQueued`, or waits for credits, `researchWaitingCredits`), `skipped` with reason `domain_taken` (already an account; `id` is that account) or `failed` (`reason` is the API\'s code, `error` names the field; an item Kenso failed to save is sent once more first). Rerunning the same file is safe: accounts that exist come back `domain_taken`.\n\n## Import people\n\n```bash\nkenso people import --file people.csv\nkenso people import --file people.csv --find-emails --yes\nkenso people import --file people.jsonl --dry-run\n```\n\n```csv\nfullName,email,title,accountDomain,role\nAnn Lee,ann@acme.io,VP Sales,acme.io,champion\nBob Ray,,CTO,acme.io,\n```\n\n- **Columns** map by name, ignoring case, spaces and dashes: `email`, `fullName` (or `name`), `firstName`, `lastName`, `title`, `linkedinUrl` (or `linkedin`, `profileUrl`), `accountDomain` (or `domain`, `website`, `companyDomain`), `accountId`, `role` and `priority`. Other columns are ignored with one warning.\n- **A person needs a name:** `fullName`, or `firstName`, `lastName` or both (the CLI joins them). A row with none of them is `invalid` (`name_required`).\n- **To put a person on an account,** give `accountDomain` or `accountId`. A row with both sends only `accountId`.\n- **`--find-emails`** queues an email find (charged in credits) for each person without an email.\n- **Rows go 200 per call** to `POST /v1/people/batch`.\n\nPeople already in the workspace are matched by email, then LinkedIn URL, so running the same file again creates nobody twice. A row comes back `created` (a new person), `updated` (an existing person added to the account), `skipped` with reason `already_on_account`, `matched` (no account asked) or `previously_removed`, or `failed`: `account_not_found` saves the person without an account (import the account, then rerun to place them), any other reason is the API\'s. The summary adds `matched`, `addedToAccounts` and `emailFindsQueued`.\n\n## List and search accounts\n\n`accounts list` and `accounts search` sort and page on the server, so they reach every account in the workspace, however many there are.\n\n```bash\nkenso accounts list --sort score:desc --limit 100 # one page; the output\'s next: line is the following one\nkenso accounts list --sort score:desc --limit 100 --all # every page, to the end\nkenso accounts search --search hiring --sort latestSignalAt:desc --data \'{"qFields": ["name", "latestSignal"]}\'\nkenso accounts search --limit 1 --data \'{"countBy": ["stage"]}\' # how many accounts sit in each stage\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "tier", "operator": "is", "values": ["1"]}]}, "sort": "tier,-pipelineAmount"}\' --all\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "hqLocation", "operator": "contains", "values": ["Germany"]}]}}\' --all\n# my accounts with a meeting this quarter: me is whoever runs it, so a saved view with it lists each member\'s own\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "owner", "operator": "is", "values": ["me"]}, {"field": "lastMeeting", "operator": "in_period", "values": ["this_quarter"]}]}}\' --all\n# tier 1 accounts with no meeting in 30 days: none since then, or none ever\nkenso accounts search --data \'{"where": {"match": "all", "conditions": [{"field": "tier", "operator": "is", "values": ["1"]}, {"match": "any", "conditions": [{"field": "lastMeeting", "operator": "older_than_days", "values": ["30"]}, {"field": "lastMeeting", "operator": "is_empty"}]}]}}\' --all\n```\n\n- **`--sort`** takes up to 3 comma-separated keys, each `field` (ascending), `field:asc` or `field:desc`. The API\'s `-field` form needs the equals sign here, `--sort=-score`, because a value that starts with a dash reads as a flag. Fields: `createdAt`, `name`, `score`, `tier` (ascending is tier 1 first), `latestSignalAt`, `committee`, `pipelineAmount`, `nextTouchAt`, `lastTouchAt`. An account with no value for a key comes last in both directions. The default is `-createdAt`.\n- **`--limit`** is 1 to 1000 (default 50). `--cursor` takes the previous page\'s `nextCursor` with the same filters and sort; `--all` follows the cursors for you.\n- **`--search`** (also `--q`) matches the name or a domain.\n- **Lists and objects go in `--data`** on `search`, as the API takes them (`kenso describe accounts search`); a flag beside it sets or replaces one key:\n - `qFields` picks where the search text looks: `name`, `domain`, `latestSignal` (the latest signal\'s title).\n - `countBy` (`stage`, `stageGroup`) adds `counts` to the output: every value with the number of matching accounts that hold it, whatever the page. The output is then one object: `data`, `pagination` and `counts`.\n - `filters` and `where` narrow the accounts.\n\nAn account\'s timeline pages the same way. `kenso accounts activity 812` returns the newest 100 earlier rows and, when older ones exist, `data.nextCursor`. Pass it back as `--cursor` (with the same `--category`) for the rows before them, until a page comes without one.\n\n## Edit accounts, people and opportunities\n\nTo set the same fields on many records, use `bulk-update` (below; it needs the `bulk_edit` flag). When every row gets its own values, or the workspace has no `bulk_edit`, run the generated `update` command once per row with `--each`. Columns are the command\'s flags by API name or flag name, and the id column fills the route:\n\n```bash\nkenso accounts update --each accounts-edit.csv --dry-run # then the same with --yes\nkenso people update --each people-edit.csv --dry-run\nkenso opportunities update --each deals.csv --dry-run\n```\n\n```csv\naccountId,stage,ownerMemberId,overwritePinned\n501,engaged,42,true\n502,customer,42,true\n```\n\nA row that changes a field someone pinned in the app fails as a whole (`409 conflict`, `pinned_by_user`: nothing on that record changes, the other fields of the row included), unless the row sets `overwritePinned` to `true` (or you pass `--overwrite-pinned`, only with the person\'s OK). Every flag of an update command: `kenso accounts update --help`.\n\n## Change many accounts at once\n\n```bash\nkenso accounts bulk-update --filter \'{"filters":[{"field":"stage","operator":"is","values":["new"]}]}\' --set owner=42 --dry-run\nkenso changes apply --change-id 31\nkenso accounts bulk-update --ids 812,813 --set stage=engaged --set tier=2 --yes\nkenso changes get --change-id 31\n```\n\n`accounts bulk-update` sets the same fields on every account you name: `--ids` (1,000 at most), everything a `--filter` matches (the body `kenso accounts search --data` takes: `filters`, `where`, `q`; up to 50,000), or `--all`. A filter that holds only options and no condition (`--filter \'{"includeImportOnly":true}\'`) takes `--all` beside it. `--exclude-ids` leaves some of a filter\'s accounts out. `--set field=value` takes `ownerMemberId` (or `owner`), `stage`, `tierOverride` (or `tier`), `industry`, `fundingRound`, `employeeCount`, `hqLocation` and `cadenceDays`, and a custom field as `custom.<key>` (`--set custom.region=EMEA`; `kenso api GET \'/v1/fields?object=account\'` gives the keys); a value of `null` clears the field. `--add-tag 12,14` and `--remove-tag 13` put tags on every account or take them off (`kenso tags list` gives the ids); each tag is one row per account from `false` to `true` or back, so `kenso changes undo` takes off only the tags the change put on. People take them too; deals have no tags. A text field\'s value is sent as you type it (`--set hqLocation=10001` is the text "10001"); a custom field\'s type is not known to the CLI, so quote its text when it reads as a number or as true or false: `--set \'custom.code="10001"\'`. Use `accounts update --each` when every row gets its own values.\n\nIt makes a change set: the accounts it names and, for each, the field, its value before and its value after. Without `--yes` (or with `--dry-run`) it previews: it prints `count` and a `sample`, writes nothing, and `next` is the `kenso changes apply` command that writes exactly those accounts. With `--yes` it writes in the background and waits (`--timeout`, default 10m), then prints the change with its `counts`: `applied`, `unchanged` (already had the value), `conflict` (the account changed after the preview, so it was left alone) and `failed` (for example `pinned`: a person set the field by hand; `--overwrite-pinned` replaces it). Exit 5 when some accounts failed or conflicted. It needs the `bulk_edit` flag as well as `accounts`.\n\n`kenso accounts bulk-update` used to be the generated command for the route\'s older one-field body, which sets one `accountType` on up to 500 accounts and needs only `accounts`. The route still takes that body, but this command no longer sends it: use `kenso accounts update --each` with an `accountType` column, or `kenso api POST /v1/accounts/bulk-update --data \'{"accountIds":[812,813],"accountType":"lost"}\'`.\n\n`people bulk-update` and `opportunities bulk-update` work the same way. People take `--set` for `ownerMemberId` (or `owner`), `leadStatus`, `title`, `seniority`, `department` and `location`, and a `--filter` of `kenso people search --data` fields (`leadStatus`, `roles`, `tagIds`, `q` and the rest). Deals take `stage` (a live stage key), `ownerMemberId` (or `owner`), `closeDate` (or `close`), `amount`, `dealType` and `nextStep`, and a `--filter` of `kenso opportunities search --data` fields (`filters`, `accountId`, `q`):\n\n```bash\nkenso opportunities bulk-update --filter \'{"filters":[{"field":"stageCategory","operator":"is","values":["open"]}]}\' --set stage=proposal --dry-run\nkenso people bulk-update --ids 501,502 --set owner=42 --yes\n```\n\n### Delete many records at once\n\n```bash\nkenso people bulk-delete --filter \'{"onAccount":"none","leadStatus":["disqualified"]}\' --dry-run\nkenso changes apply --change-id 32\nkenso opportunities bulk-delete --ids 71,72,73 --yes\n```\n\n`accounts bulk-delete`, `people bulk-delete` and `opportunities bulk-delete` name their records the way `bulk-update` does (`--ids`, `--filter`, `--all`, `--exclude-ids`) and take no `--set`. Without `--yes` they preview: `count`, a `sample`, and `next` is the `kenso changes apply` command that deletes exactly those records. The API itself previews a delete whose body leaves `dryRun` out, so `--yes` sends `dryRun: false`. Each record is deleted as its own `delete` command deletes it, so one that cannot be deleted (a person still on an account) is counted as `failed` and the rest go on. A delete is not undone with `kenso changes undo`.\n\n### Follow, stop and undo a change\n\n```bash\nkenso changes list --object accounts\nkenso changes rows --change-id 31 --status conflict,failed\nkenso changes cancel --change-id 31\nkenso changes undo --change-id 31\n```\n\n`changes list` shows the workspace\'s bulk changes, newest first, whoever made them. `changes rows` lists a change\'s records with the value before (`from`) and after (`to`) and a `status`; `--status conflict,failed` reads what a change missed. `changes cancel` drops a preview or stops a change that is still writing; what it already wrote stays. `changes undo` puts the old value back on every record that still holds the value the change wrote, for 30 days after it was applied (`undoUntil`). A record someone changed again since keeps its newer value: `counts.undone` is how many went back, `counts.applied` how many still hold the change. Undo answers `409 invalid_state` with `undo_expired`, `still_running`, `nothing_applied` or `not_undoable` when there is nothing it can put back.\n\n## Search opportunities\n\n`kenso opportunities search` works as `accounts search` does: it takes `--search`, `--sort`, `--limit`, `--cursor`, `--all`, and its lists in `--data`.\n\n```bash\nkenso opportunities search --data \'{"filters": [{"field": "stageCategory", "operator": "is", "values": ["open"]}]}\' --all\nkenso opportunities search --data \'{"filters": [{"field": "ownerMemberId", "operator": "is", "values": ["none"]}, {"field": "closeDate", "operator": "is", "values": ["past_due", "next_30_days"]}]}\'\nkenso opportunities search --limit 1 --data \'{"countBy": ["stage", "ownerMemberId"]}\' # how many opportunities hold each value\n```\n\n- **`filters`** is a list of `{field, operator, values}`, all of which must hold. Fields: `stage` (a stage key), `stageCategory` (`open`, `won`, `lost`), `ownerMemberId` (member ids, or `me` for whoever runs it), `closeDate` (`past_due`, `next_30_days`, `later`, `none`, or a period such as `this_week` or `next_quarter`), `sourceCampaignId`, `closedAt` and `createdAt` (periods). `operator` is `is` or `is_not`; the values of one condition are OR. `none` in `values` matches an opportunity with no owner, no source campaign or no close date.\n- **`countBy`** takes the same field names and adds `counts` to the output: per field, every value with the number of matching opportunities that hold it.\n- `--account-id` keeps the search to one account. `closeDate` counts days in the member\'s app time zone.\n\nOne person\'s deals, meetings and campaign contacts, as their person page lists them:\n\n```bash\nkenso opportunities list --person-id 9001 # the deals they are on, or are the primary person of\nkenso meetings list --person-id 9001 # the meetings they attend, among the ones you can see\nkenso contacts list --person-id 9001 # their contact in each campaign they are in\n```\n\n## Write research you gathered\n\n`accounts write-research` and `people write-research` store research you gathered outside Kenso as the record\'s latest research (`PUT /v1/accounts/{accountId}/research`, `PUT /v1/people/{personId}/research`). The Research tab shows it like a Ken run, with `trigger: agent` and `researchedAt` now. Nothing is charged, and no account or person field changes: set an account\'s own `fitScore`, `whyNow` or `angle` with `accounts update`. They need the `accounts_research` flag and accounts edit.\n\nThe body is the research block `accounts get --expand research` (or `people get-research`) returns, without its read-only fields: leave out `id`, `status`, `trigger`, `errorCode`, `researchedAt`, `isStale` and `appliedPrompt` (for a person also `mode`, `requestedAt`, `researchedMode`, `firecrawlCredits` and `webNote`), or the write fails with `unknown_field`. Pass it with `--data @file`:\n\n```bash\nkenso accounts write-research --account-id 501 --data @acme-dossier.json\nkenso people write-research --person-id 9001 --data @jane.json\n```\n\n```json\n{\n "tagline": { "text": "Payroll for EU contractors", "sourceUrls": ["https://acme.example"] },\n "description": { "text": "Acme runs payroll and compliance for companies hiring contractors in 30 EU countries.", "sourceUrls": ["https://acme.example"] },\n "links": { "website": "https://acme.example" },\n "whyNow": { "text": "Raised a $40M Series B in October", "sourceUrls": ["https://news.example/acme-b"], "date": "2026-10" },\n "fitScore": 82,\n "angle": "Lead with contractor onboarding time."\n}\n```\n\nMany records: one JSONL line per record, with the id next to the block\'s fields. Nested objects are sent as written. Use JSONL, not CSV: the block\'s fields are objects and lists, which a CSV cell cannot carry.\n\n```bash\nkenso accounts write-research --each dossiers.jsonl --dry-run # then the same with --yes\nkenso people write-research --each people-research.jsonl --yes --concurrency 8\n```\n\n```jsonl\n{"accountId": 501, "tagline": {"text": "Payroll for EU contractors"}, "links": {"website": "https://acme.example"}}\n{"accountId": 502, "description": {"text": "Cloud cost tooling for retailers."}, "links": {"website": "https://beta.example"}}\n```\n\nA row fails as a whole with the API\'s code: `validation_failed` (an unknown field is `unknown_field`, and `error.details` names every bad field), `research_in_progress` (`409`: Ken is researching that record now, write it again once the run ends; an account run waiting for credits counts too: it runs once the workspace has credits, and the write stays refused until that run ends) or `not_found`. Rerunning a file is safe: each write replaces the record\'s research shown.\n\n## CRM sync\n\nCRM sync has generated commands only: read connections, preview, start an import, and work through sync issues. Connect the CRM itself in the app.\n\n```bash\nkenso crm-connections list\nkenso crm-connections get --connection-id 7\nkenso crm-imports create --connection-id 7 --dry-run\nkenso crm-sync-issues list --connection-id 7 --all\n```\n\nRun `kenso crm-connections --help` (or add `--all-commands` when the actions are hidden) to see every action.\n\n## Pipelines\n\nA workspace with the `pipelines` flag on can run several deal pipelines, each with its own stages. These are generated commands (beta):\n\n```bash\nkenso pipelines list\nkenso pipelines list --query "[].{id: id, name: name, default: isDefault, stages: stages[].key}"\nkenso pipelines get --pipeline-id 5\n```\n\n`list` prints every pipeline in display order, archived ones included: `id`, `name`, `routingRule` (the one sentence Ken reads to decide whether a new deal belongs there), `isDefault`, `isArchived`, `position`, `opportunityCount`, `amountTotal` and `stages`, each stage as `kenso opportunity-stages list` prints it. A stage key is unique in the workspace, across pipelines, so a deal\'s `stage` names its pipeline and its `pipelineId` repeats it. The first read turns the workspace\'s stage list into its default pipeline, named Sales, with every deal in it. The same rows as the MCP\'s `pipelines(operation="list")`.\n\nShaping them needs the `workspace_settings` permission:\n\n```bash\nkenso pipelines create --name Renewals --routing-rule "The account is already a customer" --data \'{"stages": [{"label": "Up for renewal", "category": "open"}, {"label": "Won", "category": "won"}, {"label": "Lost", "category": "lost"}]}\'\nkenso pipelines update --pipeline-id 6 --name Expansion --position 0\nkenso pipelines update --pipeline-id 6 --data @stages.json\nkenso pipelines archive --pipeline-id 6\nkenso pipelines restore --pipeline-id 6\nkenso pipelines propose --description "upsells and renewals for customers"\n```\n\n- **`create`** takes a unique `name`, the pipeline\'s `stages` in display order (at least one `open`, one `won` and one `lost`) and an optional `routingRule`: one sentence that says which deals belong there, which Ken reads to route a new deal that names no pipeline. Each stage gets a key from its label; a key another pipeline already uses gets the pipeline\'s name in front (`renewals_won`). A workspace has at most 10 pipelines.\n- **`update`** changes what you send. `stages` is the pipeline\'s whole stage list: read it with `pipelines get`, keep each stage\'s `key`, and add a new stage without one. A stage with live deals in it cannot be left out; archive it with `"isArchived": true` instead.\n- **`propose`** asks Ken to draft a pipeline from one sentence: a `name`, a `routingRule` and `stages`, in the shape `create` takes. It saves nothing. Read it, change what you want, and send it to `create`.\n- **`archive`** stops new deals from entering a pipeline and keeps the deals in it. The default pipeline cannot be archived, and nothing is deleted: `restore` brings a pipeline back.\n\n## Deals in a pipeline\n\nA deal\'s stage names its pipeline, and the deal\'s `pipelineId` repeats it. To work one pipeline\'s deals, or move a deal between pipelines:\n\n```bash\nkenso opportunities list --pipeline-id 6\nkenso opportunities search --pipeline-id 6 --data \'{"countBy": ["stage"]}\'\nkenso opportunities create --account-id 501 --pipeline-id 6\nkenso opportunities move 77 --pipeline 6\nkenso opportunities move 77 --pipeline 6 --stage negotiating\n```\n\n- **`create --pipeline-id`** opens the deal in that pipeline\'s first live open stage. Without it, and without a `stage`, Ken reads each pipeline\'s `routingRule` and opens the deal in the pipeline whose rule clearly fits the account, else in the default pipeline. A pipeline you name always wins.\n- **`move --pipeline`** alone keeps the deal\'s category (`open`, `won` or `lost`): it lands in that pipeline\'s live stage of the category with the same label as its stage now, else in the category\'s first live stage. The printed deal says where it landed. With `--stage`, the stage must be that pipeline\'s; the error lists the pipeline\'s stage keys otherwise.\n- An archived pipeline takes no deal from another pipeline (`pipeline_archived`). The deals already in it still move between its stages.\n- A move is a stage change: it writes the same history, and a stage a person set is refused with `pinned_by_user` unless you pass `--overwrite-pinned`.\n\n## Restore a deleted account\n\n```bash\nkenso deleted-accounts list\nkenso accounts restore 812\n```\n\nA deleted account can be restored for 30 days. `deleted-accounts list` shows each one with who deleted it, `expiresAt` (restore works until then) and what comes back: `personCount`, `opportunityCount` and `touchCount`. `accounts restore <id>` brings the account back with its domains, its people, its deals and its planned touches, which wait for approval again. A domain another account took since stays with that account and is listed in `domainsTaken`. A merged account is not listed and cannot be restored: a merge has no undo. Both commands are behind the `crm_import_export` feature flag (`404` while it is off).\n\n## Import a CSV export of another CRM\n\n```bash\nkenso import accounts companies.csv\nkenso import accounts companies.csv --map "Company=name" --map "Notes=" --yes\nkenso import accounts --id 42 --yes\nkenso record-import-rows list --import-id 42 --outcome skipped\nkenso record-imports undo --import-id 42\n```\n\n`kenso import accounts <file.csv>` uploads the file (a header row, at most 50,000 rows) and prints Kenso\'s plan: which field each column fills, which columns it skips, how owner and stage values are read (`valueMaps`) and what it could not settle (`questions`). Headers of Kenso, Twenty, HubSpot, Attio and Salesforce exports are recognized. Nothing is written to your accounts yet. `--map "Header=field"` changes a column and `--map "Header="` skips it. A column fills a custom field with `--map "Header=custom.<key>"` (`kenso fields list --object account` has the keys; people are `person`, deals `opportunity`), and `--map "Header=new"` adds the custom field Kenso proposes for a column no field matches (`new:text` picks the type), and a column whose header is a custom field\'s label is mapped to it already; owner and stage values change with `kenso record-imports update --import-id <id>`.\n\nWith `--yes` the import starts and the command waits for it (`--timeout`, default 30m; the import keeps running on the server either way), then prints how many rows were created, updated, restored, left unchanged and skipped. Without `--yes` it stops at the plan and prints the command that starts that import (`--id <importId> --yes`), so the file is uploaded once. `--dry-run` sends nothing: with a file it prints the upload it would make, since the plan needs the upload, and with `--id` it reads the planned import and prints what `--map`, `--source` and `--research` would change on it. `--source twenty` names the system the file\'s record ids come from: pass the same one for every file of an export, so the people and deals files find the accounts by their old ids. `kenso record-imports delete --import-id <id>` discards an import that was planned and never started; one left planned for 30 days is discarded by itself.\n\nPer row: a domain no account has creates an account; a domain that is already an account fills only that account\'s empty fields, so nothing you entered is overwritten; an account deleted in the last 30 days is restored; a row with no usable domain is skipped, and `kenso record-import-rows list --import-id <id> --outcome skipped` says why. Research of new accounts is off unless you pass `--research`, which is charged per account. It needs the `accounts` and `crm_import_export` flags. This is a different command from `accounts import`, which creates accounts row by row from the machine running the CLI.\n\n`kenso record-imports undo --import-id <id>` takes a finished import back in the background (`kenso record-imports get --import-id <id>` reads `undoing`, then `undone`): an account the import created is deleted, and can be restored for 30 days, unless someone changed it since, it holds a deal, a person was added to it since, or it was merged; a field the import filled is emptied while it still holds the imported value. `kenso record-import-rows list --import-id <id>` shows each row\'s `undoOutcome`.\n\n`kenso import people <file.csv>` works the same way for people. Import the accounts file first: a people row\'s company id (Twenty\'s `Company Id`, HubSpot\'s associated company id) places the person on the account that kept that id, and without one the person goes on the account that holds their email\'s or company\'s domain. A people import never creates an account; a person whose company is no account comes in without one and the row says so. A row matches a person by email, then LinkedIn URL, then name on the company, as every other way into People does; a matched person gets only their empty fields filled (a phone only when they have none). A row with none of the three is skipped, and a row with only a name needs a company that is an account with a domain. `kenso record-imports undo --import-id <id>` takes a people import back too: a person it created leaves the accounts the row placed them on and is deleted, unless someone changed them since, they were contacted or have a touch planned, or they are on an open deal; a field it filled is emptied while it still holds the imported value. `kenso people import` stays the JSONL and enrichment path (`--find-emails`); `kenso import people` is the CRM file with a plan, a row report and one approval.\n\n`kenso import deals <file.csv>` works the same way for deals, after the accounts file and the people file. A row opens a deal on the account that kept its company id (Twenty\'s `Company Id`, HubSpot\'s associated company id), else on the account that holds its company domain; a row whose account Kenso does not know is skipped and says so. Its contact is the person a people import kept the row\'s contact id for (Twenty\'s `Point of Contact Id`). The plan maps each stage in the file to one of the workspace\'s deal stages (`valueMaps`, field `stage`): a stage\'s key or label matches by itself, Closed Won and Closed Lost go to the first won and lost stage, and a value with no match opens in the first open stage until you pick one with `kenso record-imports update`. Amounts stay in the workspace currency: an amount in another currency is left out with a warning, never converted. A row whose deal id an earlier import kept is that deal and only gets its empty fields filled; a file with no id column opens every deal again each time it is imported, and the plan says so (`no_source_id`). `kenso record-imports undo --import-id <id>` takes a deals import back: a deal it opened is deleted unless someone changed it since, and a field it filled is emptied while it still holds the imported value. Undo in the reverse order of the imports (deals, then people, then accounts): an account that holds a deal is kept.\n\n## Export accounts, people or deals\n\n```bash\nkenso export accounts --out accounts.csv\nkenso export accounts --view 12 --out tier-1.csv\nkenso export deals --filters \'[{"field":"stageCategory","operator":"is","values":["open"]}]\' > open-deals.csv\n```\n\nIt writes the CSV that `POST /v1/accounts/export`, `/v1/people/export` or `/v1/opportunities/export` returns, to stdout or to `--out` (then it prints the file and its row count). With no filter it exports every record. More than 50,000 rows is refused: narrow the filters. `--view <id>` exports a saved Accounts view (`kenso account-views list` shows the ids). `--filters`, `--where` (accounts), `--q` and `--sort` are the search operation\'s own fields, so a deals or people view exports with its filters and sort. The accounts and deals files start with `id` and import back as they are. Each export writes an audit-log entry and needs the export permission. Accounts and deals also need the `crm_import_export` flag while it is in beta.\n\n## Duplicates and merges\n\n```bash\nkenso accounts duplicates --scan\nkenso accounts merge 812 --into 77 --dry-run\nkenso accounts merge 812 --into 77 --yes\nkenso accounts merges list --merged-by system\nkenso accounts merges 41\n```\n\nThese need the `crm_import_export` flag beside `accounts`. `accounts duplicates` lists the pairs of accounts that look like one company: both accounts, why they were paired (`reasons`: `domain`, `linkedin`, `name`) and `isCertain`, true when the two share the name and the domain apart from its ending (acme.com and acme.co). `--scan` compares every account first; a scan also runs after each accounts import. `--status dismissed` or `merged` shows the answered pairs. `kenso account-duplicates dismiss --duplicate-id <duplicateId>` answers that a pair is not a duplicate, for good.\n\n`accounts merge <accountId> --into <id>` merges the first account into the second, the one you keep. A merge cannot be undone, so look first: `--dry-run` prints `mergeSummary` (each field that changes with its value before and after, and how many people, deals, touches and domains move) and writes nothing. The merge itself needs `--yes` when no person is at the terminal. It answers the kept account with the same summary and a `mergeId`.\n\n`accounts merges list` is the log, newest first, and `accounts merges <mergeId>` opens one merge with `mergedValues`: the merged-away account as it was. `--merged-by system` shows the merges Ken made itself. Where automatic merging is on for the workspace, Ken merges only certain pairs, keeps the customer, then the owned, then the last touched account, and leaves a pair for you when both are customers, the two have different owners, or one is being worked and the other is set aside (`heldReason` on the pair says which). That job is off unless it was turned on for the workspace.\n\n## A deal\'s stage history\n\n```bash\nkenso opportunities stage-history 77\nkenso opportunities stage-history 77 --query "entries[].{to: stageLabel, at: enteredAt, by: changedBy}"\n```\n\nIt prints `GET /v1/opportunities/{id}/stage-history` as it is, the same rows as the deal page and the MCP\'s `opportunities(operation="get-stage-history")`: the stage now, `isComplete` and `entries`, oldest first, each with `fromStage`, `stage`, `stageLabel`, `enteredAt`, `leftAt`, `durationSeconds`, `actorKind`, `actorMemberId` and Ken\'s `reason` on a move its stage judge made. With the `deal_stage_rules` flag on, each entry also has `changedBy` (`member`, `agent`, `api_key`, `workflow`, `stage_judge`, `crm_sync` or `ken_automation`), `crmProvider` on a CRM sync, and on a move `fromStageLabel` and `fromStageDurationSeconds`, how long the deal sat in the stage it left. `isComplete` false means Kenso has no record of part of the history.\n\n## Notes on accounts, people and deals\n\nWith the `record_notes` feature on, everyone who can see a record reads its notes. Name the record with exactly one of `--account`, `--person` and `--deal`:\n\n```bash\nkenso notes list --account 5\nkenso notes add --account 5 --body \'Budget approved, @[Jane Doe](41) please send the DPA\'\nkenso notes add --parent 900 --body \'Sent it this morning\' # a comment under note 900\ncat call-notes.md | kenso notes add --deal 77 --body - # the body from stdin\nkenso notes edit 900 --body \'Budget approved for Q1\' # the author only\nkenso notes edit 900 --pin\nkenso notes delete 900 --yes # kenso notes restore 900 brings it back\n```\n\nThe body is markdown, up to 20,000 characters. Mention a teammate as `@[Name](memberId)`: they get a notification that opens the note. A note shows on the record\'s Notes tab and its Activity timeline, and Ken\'s account brief quotes the account\'s notes. The MCP\'s `notes` tool does the same. A note on an account needs the accounts plan feature; people and deals work on every plan.\n\n## Required fields per stage\n\n```bash\nkenso pipelines stage-rules\nkenso pipelines stage-rules proposal --require amount,closeDate,custom.tier\nkenso pipelines stage-rules proposal --none\nkenso pipelines stage-rules lost --default\n```\n\nWith the `deal_stage_rules` flag on, each stage can name the fields a deal should have in it. Without a stage the command prints every stage\'s `key`, `label`, `category`, `isArchived`, `requiredFields` and `isDefault`, plus `requirableFields`: `amount`, `closeDate`, `ownerMemberId`, `primaryPersonId`, `nextStep`, `lostReasonKey`, `wonReasonKey` and `custom.<key>` for each custom deal field. `--require` sets the stage\'s whole list, in order, at most 10. `--none` requires nothing, and `--default` goes back to the default: a lost stage asks for `lostReasonKey`, any other stage nothing. Setting a rule needs the `workspace_settings` permission. The same as the MCP\'s `opportunities(operation="stages-set-required-fields")`.\n\nA missing field never stops a move. The deal moves, and it is flagged Missing on the board, the list and the deal page until the field is filled. A rule also applies to deals already in the stage.\n\n```bash\nkenso opportunities update --opportunity-id 4401 --stage proposal\nkenso opportunities list --missing-fields\n```\n\nEvery deal then carries `missingFields` (`[{field, label}]`). A create, or an update that sends a stage, answers `warnings` beside the deal for each field the stage asks for that the deal leaves empty: each prints on stderr as `warning: <message>`, stdout stays the deal and the exit code stays 0. `--missing-fields` keeps only the deals flagged Missing (also `missingFields: true` on `kenso opportunities search`).\n\n## Won and lost reasons\n\n```bash\nkenso opportunity-reasons get\nkenso opportunity-reasons replace --kind lost --data \'{"reasons":[{"key":"no_budget","label":"No budget"},{"label":"Built it in-house"}]}\'\nkenso opportunities move 4401 --stage lost --reason built_it_in_house\n```\n\n`kenso opportunities move <id> --stage <key> [--reason <key>]` sends the reason as `lostReasonKey` for a lost stage or `wonReasonKey` for a won stage; an open stage takes none. Each field the new stage asks for that the deal leaves empty prints a warning on stderr, and the move still goes through.\n\nWith the `deal_stage_rules` flag on, each workspace edits why its deals are lost and won. `get` prints `lost` and `won`, each `{isDefault, reasons: [{key, label, isArchived}]}`. `replace` takes a kind\'s whole list in order, as `get` prints it: keep a reason by its `key`, leave `key` out for a new one, and set `isArchived` to archive a reason or bring one back. A reason left out is archived too: deals keep it, and no write can pick it again. At least one reason stays live and at most 30, and labels stay unique, archived ones included. A deal takes a live key in `lostReasonKey` (a lost stage) or `wonReasonKey` (a won stage). A move to Lost without a reason still goes through, with a warning and "Missing: Lost reason" on the deal. Editing the lists needs the `workspace_settings` permission. The same as the MCP\'s `pipelines(operation="reasons-get")` and `reasons-replace`.\n\n## Record page layouts\n\n```bash\nkenso layouts show account\nkenso layouts set account --header tier,ownerMemberId,score,custom.arr\nkenso layouts show account > layout.json && kenso layouts set account --data @layout.json\nkenso layouts reset account\n```\n\nWith the `record_layout` flag on, a workspace lays out each record page once, for every member: `account`, `person` or `opportunity` (a deal). `show` prints `GET /v1/record-layouts/{object}`: `isDefault`, `version`, `headerFields` (up to 6, pinned under the record\'s name), `railSections` (`{name, fields}`), `hiddenFields` (under the rail\'s More), `sections` (`{key, label, placement, locked, hidden}`, in page order) and `availableFields`. Field keys are the field catalog\'s (`ownerMemberId`, `closeDate`, `primaryDomain`); a custom field is `custom.<field_key>`, and a new one joins the last rail section.\n\n`set --header` pins up to 6 fields and keeps the rest of the saved layout; the fields it unpins go to the top of the first rail section. `set --data` saves a whole layout, so group the rail into sections or hide a section that way, starting from `show`. A save made after someone else\'s answers a conflict: show it again. `reset` puts the page back to Kenso\'s default. Saving needs the `workspace_settings` permission, and the account page also needs the `accounts` plan. The same as the MCP\'s `account_views` operations `record-layouts-get`, `record-layouts-replace` and `record-layouts-reset`.\n\n## Pin a saved view\n\n```bash\nkenso views pin 118\nkenso views unpin 118\n```\n\nWith the `shared_views` flag on, `views pin` adds a saved view to your own sidebar, nested under its list (an account view under Accounts, a person view under People, a deal view under Deals). It is `kenso pins add --kind view --view-id <viewId>` under the name you would try: it prints the pin, and a view already pinned answers the pin it has. Pins are yours alone: pinning a shared view does not pin it for a teammate. `views unpin` finds your pin of the view and removes it, and prints `{"viewId": ..., "removed": true}`; a view you had not pinned prints `removed: false` and changes nothing. The view itself stays either way. `kenso pins list` shows every pin you have.\n\n## Tasks\n\nTasks are to-dos a member owes: a title, an optional due day or time, an assignee and at most one account, person or deal. They need the `tasks` flag. The app calls deals "Deals"; the CLI keeps `--deal` for an opportunity id.\n\n```bash\nkenso tasks add "Send the deck" --due tomorrow --account 812\nkenso tasks add "Call Ada back" --due friday --at 16:00 --person 501 --assignee ada@acme.com\nkenso tasks list --assignee me --due overdue,today\nkenso tasks queue --scope mine\nkenso tasks assign 7 me\nkenso tasks done 7 8 9\nkenso tasks done 7 --undo\n```\n\n- `tasks add` sends `POST /v1/tasks`. `--due` takes `today`, `tomorrow`, a weekday (the next one: `friday` or `fri`), a day (`2026-11-20`) or an ISO 8601 time with its offset (`2026-11-20T15:00:00Z`); `--at HH:MM` puts a time on that day (today without `--due`). Day words and `--at` read this computer\'s clock and time zone (`TZ`); a time\'s day is read in the assignee\'s app time zone. `--assignee` takes `me`, a member id or an email; without it the task is yours.\n- `tasks done` completes each task it names, in order (`PATCH /v1/tasks/{id}` with `status: done`); `--undo` reopens them. When one fails, its error names the tasks before it, which are already changed. `tasks assign` gives a task to `me`, a member id or a member\'s email; that member gets a `task_assigned` notification.\n- `tasks queue` is `task-queue list` under the name you would try: the Tasks screen\'s open work by due day, with `--scope mine|assigned_by_me|everyone`. It lists tasks, manual touches, call tasks, inbox threads with a reminder due (when you can view the Inbox) and Ken\'s follow-ups to you, each with the app path in `href` (null for a task, which opens in its panel).\n- `tasks list`, `get`, `update`, `delete`, `restore` and `task-queue list` are generated from the API: `kenso tasks --help` lists them.\n';
8675
8781
  }
8676
8782
  });
8677
8783
 
@@ -8687,7 +8793,7 @@ var init_leads = __esm({
8687
8793
  var output_and_errors_default;
8688
8794
  var init_output_and_errors = __esm({
8689
8795
  "docs/output-and-errors.md"() {
8690
- 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';
8796
+ 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- `threads list`, `contacts list` and `contacts search` print a short set of fields per row, in every format: a thread\'s id, channel, sender, subject, interest, read state, newest message time and preview, a contact\'s id, name, email, title, company and email validity, and a few more (the command\'s `--help` names them all). `--full` prints every field (`--full -o json` for a script that reads them all), `--fields` picks your own, and `--query` sees every field.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\nkenso threads list --folder inbox --full\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';
8691
8797
  }
8692
8798
  });
8693
8799
 
@@ -9004,28 +9110,28 @@ var init_client = __esm({
9004
9110
 
9005
9111
  // src/commands/skill/clients.ts
9006
9112
  import { homedir as homedir2 } from "node:os";
9007
- import { join as join8 } from "node:path";
9113
+ import { join as join9 } from "node:path";
9008
9114
  function home(env) {
9009
9115
  return env.HOME?.trim() || env.USERPROFILE?.trim() || homedir2();
9010
9116
  }
9011
9117
  function claudeDir(env) {
9012
- return env.CLAUDE_CONFIG_DIR?.trim() || join8(home(env), ".claude");
9118
+ return env.CLAUDE_CONFIG_DIR?.trim() || join9(home(env), ".claude");
9013
9119
  }
9014
9120
  function xdgConfigDir(env) {
9015
- return env.XDG_CONFIG_HOME?.trim() || join8(home(env), ".config");
9121
+ return env.XDG_CONFIG_HOME?.trim() || join9(home(env), ".config");
9016
9122
  }
9017
9123
  function skillsFolder(client, env) {
9018
9124
  switch (client) {
9019
9125
  case "claude-code":
9020
- return join8(claudeDir(env), "skills");
9126
+ return join9(claudeDir(env), "skills");
9021
9127
  case "codex":
9022
- return join8(home(env), ".agents", "skills");
9128
+ return join9(home(env), ".agents", "skills");
9023
9129
  case "cursor":
9024
- return join8(home(env), ".cursor", "skills");
9130
+ return join9(home(env), ".cursor", "skills");
9025
9131
  case "gemini":
9026
- return join8(home(env), ".gemini", "skills");
9132
+ return join9(home(env), ".gemini", "skills");
9027
9133
  case "opencode":
9028
- return join8(xdgConfigDir(env), "opencode", "skills");
9134
+ return join9(xdgConfigDir(env), "opencode", "skills");
9029
9135
  }
9030
9136
  }
9031
9137
  var CLIENTS, CLIENT_CHOICES, CLIENT_NAMES, AGENT_CLIENTS;
@@ -9056,7 +9162,7 @@ __export(install_exports, {
9056
9162
  write: () => write
9057
9163
  });
9058
9164
  import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync7, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
9059
- import { basename as basename2, dirname, join as join9, resolve as resolve6 } from "node:path";
9165
+ import { basename as basename2, dirname, join as join10, resolve as resolve6 } from "node:path";
9060
9166
  function quote(value) {
9061
9167
  return /^[A-Za-z0-9_\-.,:/@=+%~]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
9062
9168
  }
@@ -9080,10 +9186,10 @@ function write(path, text4) {
9080
9186
  throw new KensoError({ code: "file_unwritable", message: `Cannot write ${path}${code ? ` (${code})` : ""}.`, exitCode: ExitCode.Error });
9081
9187
  }
9082
9188
  }
9083
- function folders(ctx, client, dir) {
9084
- if (dir !== void 0) return [{ client, folder: resolve6(dir) }];
9189
+ function folders(ctx, client, dir2) {
9190
+ if (dir2 !== void 0) return [{ client, folder: resolve6(dir2) }];
9085
9191
  const clients = client === "all" ? CLIENTS : [client];
9086
- return clients.map((c) => ({ client: c, folder: join9(skillsFolder(c, ctx.env), SKILL_NAME) }));
9192
+ return clients.map((c) => ({ client: c, folder: join10(skillsFolder(c, ctx.env), SKILL_NAME) }));
9087
9193
  }
9088
9194
  function installCommand(opts) {
9089
9195
  const parts2 = ["kenso skill install"];
@@ -9117,21 +9223,21 @@ var init_install = __esm({
9117
9223
  dryRun: true,
9118
9224
  async run(ctx, { flags }) {
9119
9225
  const clientFlag = typeof flags.client === "string" ? flags.client.trim() : void 0;
9120
- const dir = typeof flags.dir === "string" && flags.dir.trim() !== "" ? flags.dir : void 0;
9226
+ const dir2 = typeof flags.dir === "string" && flags.dir.trim() !== "" ? flags.dir : void 0;
9121
9227
  if (clientFlag !== void 0 && !CLIENT_CHOICES.includes(clientFlag)) {
9122
9228
  throw usageError(`--client must be one of ${CLIENT_CHOICES.join(", ")} (got "${clientFlag}").`, { field: "client", next: "kenso skill install --help" });
9123
9229
  }
9124
9230
  const client = clientFlag ?? (ctx.agent ? AGENT_CLIENTS2[ctx.agent.name] : void 0) ?? "all";
9125
9231
  const text4 = await skillText();
9126
- const targets = folders(ctx, client, dir).map(({ client: c, folder }) => {
9127
- const path = join9(folder, "SKILL.md");
9232
+ const targets = folders(ctx, client, dir2).map(({ client: c, folder }) => {
9233
+ const path = join10(folder, "SKILL.md");
9128
9234
  const existing = readExisting(path);
9129
9235
  const status = existing === void 0 ? "created" : existing === text4 ? "unchanged" : "replaced";
9130
9236
  return { client: c, path, status };
9131
9237
  });
9132
9238
  const conflicts = targets.filter((t) => t.status === "replaced");
9133
9239
  const needsForce = conflicts.length > 0 || flags.force === true;
9134
- const next = installCommand({ client: dir === void 0 ? client : clientFlag, dir, force: needsForce });
9240
+ const next = installCommand({ client: dir2 === void 0 ? client : clientFlag, dir: dir2, force: needsForce });
9135
9241
  if (ctx.flags.dryRun) {
9136
9242
  ctx.output.object({ dryRun: true, installed: targets, next });
9137
9243
  return ExitCode.Ok;
@@ -9149,8 +9255,8 @@ var init_install = __esm({
9149
9255
  for (const target2 of targets) {
9150
9256
  if (target2.status !== "unchanged") write(target2.path, text4);
9151
9257
  }
9152
- if (dir !== void 0 && basename2(resolve6(dir)) !== SKILL_NAME) {
9153
- ctx.output.warn(`Agents expect the skill's folder to be named ${SKILL_NAME}, like the skill: ${resolve6(dir)} is not.`);
9258
+ if (dir2 !== void 0 && basename2(resolve6(dir2)) !== SKILL_NAME) {
9259
+ ctx.output.warn(`Agents expect the skill's folder to be named ${SKILL_NAME}, like the skill: ${resolve6(dir2)} is not.`);
9154
9260
  }
9155
9261
  ctx.output.object({ installed: targets });
9156
9262
  return ExitCode.Ok;
@@ -9163,7 +9269,7 @@ var init_install = __esm({
9163
9269
  // src/commands/agent/mcp-config.ts
9164
9270
  import { spawnSync } from "node:child_process";
9165
9271
  import { existsSync as existsSync5, readFileSync as readFileSync8 } from "node:fs";
9166
- import { delimiter, join as join10 } from "node:path";
9272
+ import { delimiter, join as join11 } from "node:path";
9167
9273
  function parse2(text4) {
9168
9274
  try {
9169
9275
  const doc = JSON.parse(text4);
@@ -9220,9 +9326,9 @@ function tomlServers(text4) {
9220
9326
  return entries2;
9221
9327
  }
9222
9328
  function opencodeFile(env) {
9223
- const dir = join10(xdgConfigDir(env), "opencode");
9224
- const existing = ["opencode.jsonc", "opencode.json", "config.json"].map((f) => join10(dir, f)).find((f) => existsSync5(f));
9225
- return existing ?? join10(dir, "opencode.json");
9329
+ const dir2 = join11(xdgConfigDir(env), "opencode");
9330
+ const existing = ["opencode.jsonc", "opencode.json", "config.json"].map((f) => join11(dir2, f)).find((f) => existsSync5(f));
9331
+ return existing ?? join11(dir2, "opencode.json");
9226
9332
  }
9227
9333
  function canonical(url) {
9228
9334
  try {
@@ -9234,13 +9340,13 @@ function canonical(url) {
9234
9340
  }
9235
9341
  function onPath(bin, env) {
9236
9342
  const names = process.platform === "win32" ? [`${bin}.cmd`, `${bin}.exe`, bin] : [bin];
9237
- return (env.PATH ?? env.Path ?? "").split(delimiter).some((dir) => dir !== "" && names.some((n) => existsSync5(join10(dir, n))));
9343
+ return (env.PATH ?? env.Path ?? "").split(delimiter).some((dir2) => dir2 !== "" && names.some((n) => existsSync5(join11(dir2, n))));
9238
9344
  }
9239
9345
  function isPresent(client, env) {
9240
9346
  const t = TARGETS[client];
9241
9347
  return t.bins.some((b) => onPath(b, env)) || existsSync5(t.folder(env));
9242
9348
  }
9243
- function readText(path) {
9349
+ function readText2(path) {
9244
9350
  try {
9245
9351
  return readFileSync8(path, "utf8");
9246
9352
  } catch {
@@ -9257,7 +9363,7 @@ function manualStep(client, env, url) {
9257
9363
  function mcpState(client, env, url) {
9258
9364
  const t = TARGETS[client];
9259
9365
  const file = t.file(env);
9260
- const text4 = readText(file);
9366
+ const text4 = readText2(file);
9261
9367
  if (text4 === void 0) return { status: "missing", file };
9262
9368
  const entries2 = t.entries(text4);
9263
9369
  if (entries2 === void 0) return { status: "unknown", file, detail: `${file} could not be read as JSON` };
@@ -9286,7 +9392,7 @@ function addMcp(client, env, url) {
9286
9392
  const after = mcpState(client, env, url);
9287
9393
  return after.status === "registered" ? { ...after, status: "added" } : { ...state, status: "failed", detail: `${bin} answered OK but ${t.file(env)} does not list kenso`, next };
9288
9394
  }
9289
- const text4 = readText(state.file);
9395
+ const text4 = readText2(state.file);
9290
9396
  const doc = text4 === void 0 || text4.trim() === "" ? {} : parse2(text4);
9291
9397
  if (doc === void 0) return { ...state, status: "skipped", detail: `${state.file} is not plain JSON, so it was left as it is`, next };
9292
9398
  if (text4 === void 0 && client === "opencode") doc.$schema = "https://opencode.ai/config.json";
@@ -9311,7 +9417,7 @@ var init_mcp_config = __esm({
9311
9417
  "claude-code": {
9312
9418
  bins: ["claude"],
9313
9419
  folder: claudeDir,
9314
- file: (env) => env.CLAUDE_CONFIG_DIR?.trim() ? join10(env.CLAUDE_CONFIG_DIR.trim(), ".claude.json") : join10(home(env), ".claude.json"),
9420
+ file: (env) => env.CLAUDE_CONFIG_DIR?.trim() ? join11(env.CLAUDE_CONFIG_DIR.trim(), ".claude.json") : join11(home(env), ".claude.json"),
9315
9421
  // User scope only: that is where setup adds it, and it reaches every project.
9316
9422
  entries: (text4) => mcpServersOf(text4),
9317
9423
  command: (url) => ["claude", "mcp", "add", "--scope", "user", "--transport", "http", SERVER_NAME, url],
@@ -9319,16 +9425,16 @@ var init_mcp_config = __esm({
9319
9425
  },
9320
9426
  codex: {
9321
9427
  bins: ["codex"],
9322
- folder: (env) => env.CODEX_HOME?.trim() || join10(home(env), ".codex"),
9323
- file: (env) => join10(env.CODEX_HOME?.trim() || join10(home(env), ".codex"), "config.toml"),
9428
+ folder: (env) => env.CODEX_HOME?.trim() || join11(home(env), ".codex"),
9429
+ file: (env) => join11(env.CODEX_HOME?.trim() || join11(home(env), ".codex"), "config.toml"),
9324
9430
  entries: tomlServers,
9325
9431
  command: (url) => ["codex", "mcp", "add", SERVER_NAME, "--url", url],
9326
9432
  signIn: "Run codex mcp login kenso."
9327
9433
  },
9328
9434
  cursor: {
9329
9435
  bins: ["cursor", "cursor-agent"],
9330
- folder: (env) => join10(home(env), ".cursor"),
9331
- file: (env) => join10(home(env), ".cursor", "mcp.json"),
9436
+ folder: (env) => join11(home(env), ".cursor"),
9437
+ file: (env) => join11(home(env), ".cursor", "mcp.json"),
9332
9438
  entries: (text4) => mcpServersOf(text4),
9333
9439
  merge: (doc, url) => {
9334
9440
  const all = isDoc(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
@@ -9338,8 +9444,8 @@ var init_mcp_config = __esm({
9338
9444
  },
9339
9445
  gemini: {
9340
9446
  bins: ["gemini"],
9341
- folder: (env) => join10(home(env), ".gemini"),
9342
- file: (env) => join10(home(env), ".gemini", "settings.json"),
9447
+ folder: (env) => join11(home(env), ".gemini"),
9448
+ file: (env) => join11(home(env), ".gemini", "settings.json"),
9343
9449
  // httpUrl is Gemini CLI's Streamable HTTP key; url is SSE.
9344
9450
  entries: (text4) => mcpServersOf(text4, ["httpUrl", "url"]),
9345
9451
  command: (url) => ["gemini", "mcp", "add", "--scope", "user", "--transport", "http", SERVER_NAME, url],
@@ -9347,7 +9453,7 @@ var init_mcp_config = __esm({
9347
9453
  },
9348
9454
  opencode: {
9349
9455
  bins: ["opencode"],
9350
- folder: (env) => join10(xdgConfigDir(env), "opencode"),
9456
+ folder: (env) => join11(xdgConfigDir(env), "opencode"),
9351
9457
  file: opencodeFile,
9352
9458
  // OpenCode 1.x lists servers under mcp; newer configs nest them under mcp.servers.
9353
9459
  entries: (text4) => {
@@ -9371,7 +9477,7 @@ var setup_exports = {};
9371
9477
  __export(setup_exports, {
9372
9478
  default: () => setup_default
9373
9479
  });
9374
- import { join as join11 } from "node:path";
9480
+ import { join as join12 } from "node:path";
9375
9481
  function quote2(value) {
9376
9482
  return /^[A-Za-z0-9_\-.,:/@=+%~]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
9377
9483
  }
@@ -9431,7 +9537,7 @@ var init_setup = __esm({
9431
9537
  const clients = pickClients(ctx, clientFlag, status);
9432
9538
  const text4 = await skillText();
9433
9539
  const rows = clients.map((client) => {
9434
- const path = join11(skillsFolder(client, ctx.env), SKILL_NAME, "SKILL.md");
9540
+ const path = join12(skillsFolder(client, ctx.env), SKILL_NAME, "SKILL.md");
9435
9541
  const existing = readExisting(path);
9436
9542
  const skill = existing === void 0 ? "missing" : existing === text4 ? "installed" : "different";
9437
9543
  return { client, present: isPresent(client, ctx.env), skill: { path, status: skill }, mcp: mcpState(client, ctx.env, url) };
@@ -11417,13 +11523,13 @@ function rowValues(row, mapping, mode) {
11417
11523
  }
11418
11524
  return out;
11419
11525
  }
11420
- var CONTACT_FIELDS, NOT_UPDATABLE, ALIAS_GROUPS, ALIASES2, CUSTOM_PREFIX, CUSTOM_HEADER, FIELD_LIST;
11526
+ var CONTACT_FIELDS2, NOT_UPDATABLE, ALIAS_GROUPS, ALIASES2, CUSTOM_PREFIX, CUSTOM_HEADER, FIELD_LIST;
11421
11527
  var init_mapping = __esm({
11422
11528
  "src/commands/contacts/mapping.ts"() {
11423
11529
  "use strict";
11424
11530
  init_errors();
11425
11531
  init_normalize();
11426
- CONTACT_FIELDS = ["email", "firstName", "lastName", "title", "linkedInUrl", "companyName", "companyDomain"];
11532
+ CONTACT_FIELDS2 = ["email", "firstName", "lastName", "title", "linkedInUrl", "companyName", "companyDomain"];
11427
11533
  NOT_UPDATABLE = /* @__PURE__ */ new Set(["companyName", "companyDomain"]);
11428
11534
  ALIAS_GROUPS = [
11429
11535
  ["email", ["email", "emailaddress", "mail", "workemail"]],
@@ -11438,7 +11544,7 @@ var init_mapping = __esm({
11438
11544
  ALIASES2 = new Map(ALIAS_GROUPS.flatMap(([field, names]) => names.map((name) => [name, field])));
11439
11545
  CUSTOM_PREFIX = "customVariables.";
11440
11546
  CUSTOM_HEADER = /^customVariables\.(.+)$/i;
11441
- FIELD_LIST = `${CONTACT_FIELDS.join(", ")}, id (update only)`;
11547
+ FIELD_LIST = `${CONTACT_FIELDS2.join(", ")}, id (update only)`;
11442
11548
  }
11443
11549
  });
11444
11550
 
@@ -11469,7 +11575,7 @@ function rowProblem(contact, linkedInOnly) {
11469
11575
  function toContact(row, mapping) {
11470
11576
  const values = rowValues(row, mapping, "import");
11471
11577
  const contact = {};
11472
- for (const field of CONTACT_FIELDS) {
11578
+ for (const field of CONTACT_FIELDS2) {
11473
11579
  const value = values.fields[field];
11474
11580
  if (typeof value === "string") contact[field] = value;
11475
11581
  }
@@ -11577,8 +11683,8 @@ function mapCreateAnswer(chunk, body2) {
11577
11683
  const error = isRecord4(entry.error) ? entry.error : entry;
11578
11684
  failed.set(entry.index, { code: text3(error.code) ?? "failed", message: text3(error.message) });
11579
11685
  }
11580
- chunk.forEach((item, index) => {
11581
- const failure = failed.get(index);
11686
+ chunk.forEach((item, index2) => {
11687
+ const failure = failed.get(index2);
11582
11688
  if (!failure) {
11583
11689
  results.push({ row: item.row, status: "ok", ...email(item) });
11584
11690
  return;
@@ -11823,7 +11929,7 @@ var init_import2 = __esm({
11823
11929
  COMMAND2 = "kenso contacts import";
11824
11930
  CHUNK_SIZE2 = 1e3;
11825
11931
  LINKEDIN_ONLY_CHANNELS = /* @__PURE__ */ new Set(["linkedin", "linkedin_only"]);
11826
- TEMPLATE_HEADER = `${CONTACT_FIELDS.join(",")},<your custom columns>`;
11932
+ TEMPLATE_HEADER = `${CONTACT_FIELDS2.join(",")},<your custom columns>`;
11827
11933
  command20 = {
11828
11934
  resource: "contacts",
11829
11935
  action: "import",
@@ -11925,7 +12031,7 @@ __export(update_exports, {
11925
12031
  planUpdate: () => planUpdate
11926
12032
  });
11927
12033
  async function emailIndex(ctx, campaignId) {
11928
- const index = /* @__PURE__ */ new Map();
12034
+ const index2 = /* @__PURE__ */ new Map();
11929
12035
  let read2 = 0;
11930
12036
  for await (const contact of ctx.client.paginate({ method: "GET", path: "/v1/contacts", query: { campaignId } }, { pageSize: PAGE_SIZE })) {
11931
12037
  read2++;
@@ -11933,9 +12039,9 @@ async function emailIndex(ctx, campaignId) {
11933
12039
  if (!isRecord4(contact)) continue;
11934
12040
  const email = typeof contact.email === "string" ? contact.email.trim().toLowerCase() : "";
11935
12041
  const id = typeof contact.id === "number" ? contact.id : typeof contact.id === "string" ? positiveId(contact.id) : void 0;
11936
- if (email !== "" && id !== void 0 && !index.has(email)) index.set(email, id);
12042
+ if (email !== "" && id !== void 0 && !index2.has(email)) index2.set(email, id);
11937
12043
  }
11938
- return index;
12044
+ return index2;
11939
12045
  }
11940
12046
  function planUpdate(rows, mapping, match, emails) {
11941
12047
  const items = [];
@@ -12109,25 +12215,25 @@ var init_update = __esm({
12109
12215
  // src/commands/contacts/bulk-store.ts
12110
12216
  import { existsSync as existsSync6 } from "node:fs";
12111
12217
  import { appendFile as appendFile2, readFile as readFile8, writeFile as writeFile3 } from "node:fs/promises";
12112
- import { join as join12 } from "node:path";
12218
+ import { join as join13 } from "node:path";
12113
12219
  function whereDir(env) {
12114
- return join12(runsRoot(env), WHERE_DIR);
12220
+ return join13(runsRoot(env), WHERE_DIR);
12115
12221
  }
12116
12222
  async function unfinishedWhereIds(ctx, command69, args) {
12117
- const dir = whereDir(ctx.env);
12223
+ const dir2 = whereDir(ctx.env);
12118
12224
  const identity = argsIdentity(args);
12119
12225
  const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
12120
12226
  for (const run of await listRuns(ctx.env)) {
12121
12227
  if (run.command !== command69 || run.status === "done" || run.status === "planned") continue;
12122
12228
  if ((run.workspaceId || void 0) !== (workspaceId || void 0) || argsIdentity(run.args) !== identity) continue;
12123
- if (run.inputPath?.startsWith(`${dir}/`) && existsSync6(run.inputPath)) return run.inputPath;
12229
+ if (run.inputPath?.startsWith(`${dir2}/`) && existsSync6(run.inputPath)) return run.inputPath;
12124
12230
  }
12125
12231
  return void 0;
12126
12232
  }
12127
12233
  async function saveWhereIds(ctx, kind, ids2) {
12128
- const dir = whereDir(ctx.env);
12129
- ensurePrivateDir2(dir);
12130
- const path = join12(dir, `${kind}-${Date.now()}-${newRunId().slice(2)}.txt`);
12234
+ const dir2 = whereDir(ctx.env);
12235
+ ensurePrivateDir2(dir2);
12236
+ const path = join13(dir2, `${kind}-${Date.now()}-${newRunId().slice(2)}.txt`);
12131
12237
  await writeFile3(path, ids2.map((id) => `${id}
12132
12238
  `).join(""), { mode: 384 });
12133
12239
  return path;
@@ -12136,7 +12242,7 @@ function chunkAttempts(env) {
12136
12242
  let earlier;
12137
12243
  return async (runId, chunkIndex) => {
12138
12244
  earlier ??= (async () => {
12139
- const path2 = join12(runsRoot(env), runId, ATTEMPTS_FILE);
12245
+ const path2 = join13(runsRoot(env), runId, ATTEMPTS_FILE);
12140
12246
  const text4 = await readFile8(path2, "utf8").catch(() => "");
12141
12247
  const indexes3 = new Set(
12142
12248
  text4.split("\n").filter((line) => line.trim() !== "").map(Number)
@@ -13478,7 +13584,7 @@ var init_jobs2 = __esm({
13478
13584
  // src/commands/layouts/layouts.ts
13479
13585
  var layouts_exports = {};
13480
13586
  __export(layouts_exports, {
13481
- reset: () => reset,
13587
+ reset: () => reset2,
13482
13588
  set: () => set,
13483
13589
  show: () => show,
13484
13590
  withHeader: () => withHeader
@@ -13512,15 +13618,15 @@ function withHeader(layout, header) {
13512
13618
  return bodyOf({
13513
13619
  version: layout.version,
13514
13620
  headerFields: header,
13515
- railSections: (layout.railSections ?? []).map((s, index) => ({
13621
+ railSections: (layout.railSections ?? []).map((s, index2) => ({
13516
13622
  name: s.name,
13517
- fields: [...index === 0 ? unpinned : [], ...s.fields.filter((f) => !pinned.has(f.toLowerCase()))]
13623
+ fields: [...index2 === 0 ? unpinned : [], ...s.fields.filter((f) => !pinned.has(f.toLowerCase()))]
13518
13624
  })),
13519
13625
  hiddenFields: (layout.hiddenFields ?? []).filter((f) => !pinned.has(f.toLowerCase())),
13520
13626
  sections: layout.sections ?? []
13521
13627
  });
13522
13628
  }
13523
- var OBJECTS3, BETA2, OBJECT_ARG, show, set, reset;
13629
+ var OBJECTS3, BETA2, OBJECT_ARG, show, set, reset2;
13524
13630
  var init_layouts = __esm({
13525
13631
  "src/commands/layouts/layouts.ts"() {
13526
13632
  "use strict";
@@ -13584,7 +13690,7 @@ var init_layouts = __esm({
13584
13690
  return ExitCode.Ok;
13585
13691
  }
13586
13692
  };
13587
- reset = {
13693
+ reset2 = {
13588
13694
  resource: "layouts",
13589
13695
  action: "reset",
13590
13696
  summary: "Put the account, person or deal page back to Kenso's default layout",
@@ -14895,7 +15001,7 @@ __export(show_exports2, {
14895
15001
  default: () => show_default2
14896
15002
  });
14897
15003
  import { existsSync as existsSync7, readFileSync as readFileSync9 } from "node:fs";
14898
- import { join as join13 } from "node:path";
15004
+ import { join as join14 } from "node:path";
14899
15005
  var FILES, command43, show_default2;
14900
15006
  var init_show2 = __esm({
14901
15007
  "src/commands/runs/show.ts"() {
@@ -14920,10 +15026,10 @@ var init_show2 = __esm({
14920
15026
  examples: ["kenso runs show r_ab3dxk2q"],
14921
15027
  async run(ctx, { positionals }) {
14922
15028
  const run = await loadRun(positionals[0] ?? "", ctx.env);
14923
- const { dir, ...record3 } = run;
14924
- const files = { dir };
15029
+ const { dir: dir2, ...record3 } = run;
15030
+ const files = { dir: dir2 };
14925
15031
  for (const [key, name] of FILES) {
14926
- const path = join13(dir, name);
15032
+ const path = join14(dir2, name);
14927
15033
  if (existsSync7(path)) files[key] = path;
14928
15034
  }
14929
15035
  let summary;
@@ -15423,7 +15529,7 @@ var init_common3 = __esm({
15423
15529
 
15424
15530
  // src/commands/studio/folder.ts
15425
15531
  import { readdir as readdir2, readFile as readFile11, stat as stat2 } from "node:fs/promises";
15426
- import { extname as extname6, isAbsolute, join as join14, relative, resolve as resolve11, sep } from "node:path";
15532
+ import { extname as extname6, isAbsolute, join as join15, relative, resolve as resolve11, sep } from "node:path";
15427
15533
  function textOf2(bytes) {
15428
15534
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
15429
15535
  try {
@@ -15432,20 +15538,20 @@ function textOf2(bytes) {
15432
15538
  return void 0;
15433
15539
  }
15434
15540
  }
15435
- async function existingDir(dir) {
15436
- const abs = resolve11(dir);
15541
+ async function existingDir(dir2) {
15542
+ const abs = resolve11(dir2);
15437
15543
  const info = await stat2(abs).catch(() => void 0);
15438
- if (!info?.isDirectory()) throw usageError(`${dir} is not a directory.`, { field: "dir" });
15544
+ if (!info?.isDirectory()) throw usageError(`${dir2} is not a directory.`, { field: "dir" });
15439
15545
  return abs;
15440
15546
  }
15441
- async function readFolder(dir) {
15442
- const root2 = await existingDir(dir);
15547
+ async function readFolder(dir2) {
15548
+ const root2 = await existingDir(dir2);
15443
15549
  const files = [];
15444
15550
  const walk = async (folder) => {
15445
15551
  const entries2 = await readdir2(folder, { withFileTypes: true });
15446
15552
  for (const entry of entries2) {
15447
15553
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
15448
- const abs = join14(folder, entry.name);
15554
+ const abs = join15(folder, entry.name);
15449
15555
  if (entry.isDirectory()) await walk(abs);
15450
15556
  else if (entry.isFile()) {
15451
15557
  const bytes = await readFile11(abs);
@@ -15479,9 +15585,9 @@ async function mapLimit(items, limit, fn) {
15479
15585
  let failed = false;
15480
15586
  const worker = async () => {
15481
15587
  while (!failed && next < items.length) {
15482
- const index = next++;
15588
+ const index2 = next++;
15483
15589
  try {
15484
- out[index] = await fn(items[index], index);
15590
+ out[index2] = await fn(items[index2], index2);
15485
15591
  } catch (err) {
15486
15592
  failed = true;
15487
15593
  throw err;
@@ -15652,7 +15758,7 @@ var init_pull = __esm({
15652
15758
  if (version !== void 0 && !/^(draft|latest|\d+)$/.test(version)) {
15653
15759
  throw usageError(`--template-version must be draft, latest or a version id (got "${version}").`, { field: "template-version" });
15654
15760
  }
15655
- const dir = resolve12(String(flags.dir));
15761
+ const dir2 = resolve12(String(flags.dir));
15656
15762
  const res = await ctx.client.request({
15657
15763
  method: "GET",
15658
15764
  path: `/v1/asset-templates/${templateId}/pull`,
@@ -15660,22 +15766,22 @@ var init_pull = __esm({
15660
15766
  signal: ctx.signal
15661
15767
  });
15662
15768
  const pulled = unwrap(res.body) ?? {};
15663
- const files = Object.entries(pulled.files ?? {}).map(([path, file]) => ({ path, file, target: safeJoin(dir, path) }));
15769
+ const files = Object.entries(pulled.files ?? {}).map(([path, file]) => ({ path, file, target: safeJoin(dir2, path) }));
15664
15770
  const missing2 = files.find(({ file }) => typeof file.text !== "string" && !file.downloadUrl);
15665
15771
  if (missing2) {
15666
15772
  throw new KensoError({ code: "pull_incomplete", message: `${missing2.path} came back with neither text nor a download link.`, exitCode: ExitCode.Server });
15667
15773
  }
15668
15774
  if (ctx.flags.dryRun) {
15669
- ctx.output.object({ dryRun: true, templateId, versionId: pulled.versionId, dir, files: files.map(({ path }) => path) });
15775
+ ctx.output.object({ dryRun: true, templateId, versionId: pulled.versionId, dir: dir2, files: files.map(({ path }) => path) });
15670
15776
  return ExitCode.Ok;
15671
15777
  }
15672
- await mkdir(dir, { recursive: true });
15778
+ await mkdir(dir2, { recursive: true });
15673
15779
  await mapLimit(files, PARALLEL_TRANSFERS, async ({ path, file, target: target2 }) => {
15674
15780
  const content = typeof file.text === "string" ? file.text : await download2(file.downloadUrl, path, file.sha256, ctx.signal);
15675
15781
  await mkdir(dirname2(target2), { recursive: true });
15676
15782
  await writeFile4(target2, content);
15677
15783
  });
15678
- ctx.output.object({ templateId, versionId: pulled.versionId, files: files.length, dir });
15784
+ ctx.output.object({ templateId, versionId: pulled.versionId, files: files.length, dir: dir2 });
15679
15785
  return ExitCode.Ok;
15680
15786
  }
15681
15787
  };
@@ -15684,19 +15790,19 @@ var init_pull = __esm({
15684
15790
  });
15685
15791
 
15686
15792
  // src/commands/studio/read.ts
15687
- async function readLocalTemplate(templateId, dir) {
15688
- const files = await readFolder(dir);
15793
+ async function readLocalTemplate(templateId, dir2) {
15794
+ const files = await readFolder(dir2);
15689
15795
  if (files.length === 0) {
15690
- throw usageError(`${dir} has no template files (dotfiles and node_modules are skipped).`, {
15796
+ throw usageError(`${dir2} has no template files (dotfiles and node_modules are skipped).`, {
15691
15797
  field: "dir",
15692
- next: `kenso studio pull ${templateId} --dir ${dir}`
15798
+ next: `kenso studio pull ${templateId} --dir ${dir2}`
15693
15799
  });
15694
15800
  }
15695
15801
  refuseOversize(files);
15696
15802
  return files;
15697
15803
  }
15698
- async function readTemplateFolder(ctx, templateId, dir) {
15699
- return bundleFiles(ctx, templateId, await readLocalTemplate(templateId, dir));
15804
+ async function readTemplateFolder(ctx, templateId, dir2) {
15805
+ return bundleFiles(ctx, templateId, await readLocalTemplate(templateId, dir2));
15700
15806
  }
15701
15807
  var init_read = __esm({
15702
15808
  "src/commands/studio/read.ts"() {
@@ -15876,8 +15982,8 @@ import { createHash as createHash7 } from "node:crypto";
15876
15982
  function list(paths) {
15877
15983
  return paths.length > SHOWN ? `${paths.slice(0, SHOWN).join(", ")} and ${paths.length - SHOWN} more` : paths.join(", ");
15878
15984
  }
15879
- async function warnIfFolderDiffers(ctx, templateId, dir, versionId, push) {
15880
- const local = await readFolder(dir);
15985
+ async function warnIfFolderDiffers(ctx, templateId, dir2, versionId, push) {
15986
+ const local = await readFolder(dir2);
15881
15987
  const res = await ctx.client.request({
15882
15988
  method: "GET",
15883
15989
  path: `/v1/asset-templates/${templateId}/pull`,
@@ -15950,10 +16056,10 @@ var init_preview = __esm({
15950
16056
  const ids2 = accountIds(stringFlag(flags["account-ids"]));
15951
16057
  const interact = flags.interact !== void 0 ? await readDataArg(String(flags.interact), ctx.stdin) : void 0;
15952
16058
  if (interact !== void 0 && !Array.isArray(interact)) throw usageError("--interact must be a JSON array of steps.", { field: "interact" });
15953
- const dir = stringFlag(flags.dir);
15954
- if (dir !== void 0) {
15955
- const push = commandLine2(ctx, "studio push", { flags: { dir }, positionals: [String(templateId)] });
15956
- await warnIfFolderDiffers(ctx, templateId, dir, versionId, push);
16059
+ const dir2 = stringFlag(flags.dir);
16060
+ if (dir2 !== void 0) {
16061
+ const push = commandLine2(ctx, "studio push", { flags: { dir: dir2 }, positionals: [String(templateId)] });
16062
+ await warnIfFolderDiffers(ctx, templateId, dir2, versionId, push);
15957
16063
  }
15958
16064
  const mode = stringFlag(flags.mode);
15959
16065
  const sample = stringFlag(flags.sample);
@@ -16082,7 +16188,7 @@ __export(fill_exports, {
16082
16188
  });
16083
16189
  import { createHash as createHash8 } from "node:crypto";
16084
16190
  import { readFile as readFile12 } from "node:fs/promises";
16085
- import { join as join15, resolve as resolve13 } from "node:path";
16191
+ import { join as join16, resolve as resolve13 } from "node:path";
16086
16192
  async function readTarget(ctx, flags) {
16087
16193
  const accounts = stringFlag(flags.accounts);
16088
16194
  const campaign = stringFlag(flags.campaign);
@@ -16133,7 +16239,7 @@ async function refuseRefill(ctx, args, target2) {
16133
16239
  code: "already_filled",
16134
16240
  exitCode: ExitCode.Conflict,
16135
16241
  message: unfinished ? `Run ${earlier.runId} is already filling these ${ids2} (${earlier.status}).` : `Run ${earlier.runId} already filled these ${ids2}.`,
16136
- hint: unfinished ? "Continue that run instead: a new fill would create every fill run again." : succeeded ? "Every page was filled. Filling again rebuilds and charges every page that is not building or live; to do that anyway, use kenso asset-runs create." : `Filling again rebuilds and charges every page that is not building or live. To retry only the failed ones, put the ${target2.key} values of the failed rows in ${join15(earlier.dir, "results.csv")} in a file and fill that file.`,
16242
+ hint: unfinished ? "Continue that run instead: a new fill would create every fill run again." : succeeded ? "Every page was filled. Filling again rebuilds and charges every page that is not building or live; to do that anyway, use kenso asset-runs create." : `Filling again rebuilds and charges every page that is not building or live. To retry only the failed ones, put the ${target2.key} values of the failed rows in ${join16(earlier.dir, "results.csv")} in a file and fill that file.`,
16137
16243
  next: unfinished ? `kenso runs resume ${earlier.runId}` : `kenso runs show ${earlier.runId}`
16138
16244
  });
16139
16245
  }
@@ -16280,6 +16386,11 @@ function due(dueText, atText, now = /* @__PURE__ */ new Date()) {
16280
16386
  const text4 = (dueText ?? "").trim();
16281
16387
  if (/^\d{4}-\d{2}-\d{2}T/.test(text4)) {
16282
16388
  if (atText !== void 0) throw usageError("--at puts a time on a day: give --due a day, not a time.", { field: "at", next: DUE_NEXT });
16389
+ if (!/(Z|[+-]\d{2}:?\d{2})$/i.test(text4))
16390
+ throw usageError(`--due as a time needs its offset, such as ${text4}Z or ${text4}+02:00 (got "${text4}"); or use --at for local time.`, {
16391
+ field: "due",
16392
+ next: DUE_NEXT
16393
+ });
16283
16394
  if (Number.isNaN(Date.parse(text4))) throw badDue(text4);
16284
16395
  return { dueAt: text4 };
16285
16396
  }
@@ -16365,9 +16476,9 @@ var init_add2 = __esm({
16365
16476
  resource: "tasks",
16366
16477
  action: "add",
16367
16478
  summary: "Add a task: a title, an optional due day and time, assignee and the account, person or deal it is about",
16368
- description: "Sends POST /v1/tasks and prints the task. The words after add are the title (1-500 characters). --due takes today, tomorrow, a weekday (the next one: friday or fri), a day (2026-11-20) or an ISO 8601 time; --at HH:MM puts a time on that day (today without --due). Day words and --at read this computer's clock and time zone (TZ); a time's day is read in the assignee's app time zone. --assignee takes me, a member id or an email; without it the task is yours. Link at most one of --account, --person, --deal: a person's task also shows on their first account, a deal's on its account and primary person. Linking an account on a plan without Accounts is plan_required.",
16479
+ description: "Sends POST /v1/tasks and prints the task. The words after add are the title (1-500 characters). --due takes today, tomorrow, a weekday (the next one: friday or fri), a day (2026-11-20) or an ISO 8601 time with its offset; --at HH:MM puts a time on that day (today without --due). Day words and --at read this computer's clock and time zone (TZ); a time's day is read in the assignee's app time zone. --assignee takes me, a member id or an email; without it the task is yours. Link at most one of --account, --person, --deal: a person's task also shows on their first account, a deal's on its account and primary person. Linking an account on a plan without Accounts is plan_required.",
16369
16480
  flags: {
16370
- due: { type: "string", description: "Due day: today, tomorrow, a weekday, YYYY-MM-DD, or an ISO 8601 time" },
16481
+ due: { type: "string", description: "Due day: today, tomorrow, a weekday, YYYY-MM-DD, or an ISO 8601 time with an offset" },
16371
16482
  at: { type: "string", description: "Due time on that day, HH:MM (today without --due)" },
16372
16483
  assignee: { type: "string", description: "The member it is for: me, a member id or an email; default you" },
16373
16484
  notes: { type: "string", description: "Notes (markdown)" },
@@ -16387,10 +16498,10 @@ var init_add2 = __esm({
16387
16498
  const body2 = { title };
16388
16499
  if (typeof flags.notes === "string") body2.notes = flags.notes;
16389
16500
  Object.assign(body2, due(typeof flags.due === "string" ? flags.due : void 0, typeof flags.at === "string" ? flags.at : void 0));
16390
- if (typeof flags.assignee === "string") body2.assigneeMemberId = await memberId(ctx, flags.assignee, "assignee", NEXT);
16391
16501
  if (typeof flags.account === "string") body2.accountId = positiveId4(flags.account, "account", NEXT);
16392
16502
  if (typeof flags.person === "string") body2.personId = positiveId4(flags.person, "person", NEXT);
16393
16503
  if (typeof flags.deal === "string") body2.opportunityId = positiveId4(flags.deal, "deal", NEXT);
16504
+ if (typeof flags.assignee === "string") body2.assigneeMemberId = await memberId(ctx, flags.assignee, "assignee", NEXT);
16394
16505
  const res = await ctx.client.request({ method: "POST", path: "/v1/tasks", body: body2, signal: ctx.signal });
16395
16506
  ctx.output.object(unwrap(res.body));
16396
16507
  return ExitCode.Ok;
@@ -16411,10 +16522,28 @@ async function patchTask(ctx, taskId, change) {
16411
16522
  try {
16412
16523
  return unwrap((await send2()).body);
16413
16524
  } catch (error) {
16414
- if (!(error instanceof KensoError) || error.httpStatus !== 409) throw error;
16525
+ if (!(error instanceof KensoError) || error.httpStatus !== 409 || !taskChanged(error.details)) throw error;
16415
16526
  return unwrap((await send2()).body);
16416
16527
  }
16417
16528
  }
16529
+ function taskChanged(body2) {
16530
+ const details = body2?.error?.details;
16531
+ return Array.isArray(details) && details.some((detail) => detail?.code === "task_changed");
16532
+ }
16533
+ function stoppedAt(error, id, finished, status) {
16534
+ const done2 = status === "open" ? "reopened" : "done";
16535
+ return new KensoError({
16536
+ code: error.code,
16537
+ message: `Task ${id}: ${error.message} Tasks ${finished.join(", ")} are ${done2}; ${id} and the ones after it are not.`,
16538
+ exitCode: error.exitCode,
16539
+ httpStatus: error.httpStatus,
16540
+ field: error.field,
16541
+ hint: error.hint,
16542
+ next: error.next,
16543
+ requestId: error.requestId,
16544
+ details: error.details
16545
+ });
16546
+ }
16418
16547
  var command56, done_default;
16419
16548
  var init_done = __esm({
16420
16549
  "src/commands/tasks/done.ts"() {
@@ -16427,7 +16556,7 @@ var init_done = __esm({
16427
16556
  resource: "tasks",
16428
16557
  action: "done",
16429
16558
  summary: "Complete one or more tasks (--undo reopens them)",
16430
- description: "Sends PATCH /v1/tasks/{taskId} with status done for each id, in order, and prints the task (one line per task for several): completedAt and completedByMemberId set, and task.completed written on the record's timeline. --undo sends status open, which reopens it. An error stops at that id; the ones before it are done.",
16559
+ description: "Sends PATCH /v1/tasks/{taskId} with status done for each id, in order, and prints the task (one line per task for several): completedAt and completedByMemberId set, and task.completed written on the record's timeline. --undo sends status open, which reopens it. An error stops at that id; its message names the ids before it, which are done.",
16431
16560
  flags: { undo: { type: "boolean", description: "Reopen the task instead" } },
16432
16561
  positionals: [{ name: "taskId", required: true, variadic: true, description: "One or more task ids" }],
16433
16562
  examples: ["kenso tasks done 7", "kenso tasks done 7 8 9", "kenso tasks done 7 --undo"],
@@ -16440,7 +16569,15 @@ var init_done = __esm({
16440
16569
  else
16441
16570
  await ctx.output.list(
16442
16571
  (async function* () {
16443
- for (const id of ids2) yield await patchTask(ctx, id, change);
16572
+ const finished = [];
16573
+ for (const id of ids2) {
16574
+ try {
16575
+ yield await patchTask(ctx, id, change);
16576
+ } catch (error) {
16577
+ throw finished.length === 0 || !(error instanceof KensoError) ? error : stoppedAt(error, id, finished, change.status);
16578
+ }
16579
+ finished.push(id);
16580
+ }
16444
16581
  })()
16445
16582
  );
16446
16583
  return ExitCode.Ok;
@@ -16618,14 +16755,14 @@ var init_views = __esm({
16618
16755
  // src/commands/webhooks/local.ts
16619
16756
  import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
16620
16757
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
16621
- import { join as join16 } from "node:path";
16758
+ import { join as join17 } from "node:path";
16622
16759
  function webhooksDir(env) {
16623
- const dir = join16(configDir(env), "webhooks");
16624
- mkdirSync4(dir, { recursive: true, mode: 448 });
16625
- return dir;
16760
+ const dir2 = join17(configDir(env), "webhooks");
16761
+ mkdirSync4(dir2, { recursive: true, mode: 448 });
16762
+ return dir2;
16626
16763
  }
16627
16764
  function signingSecretPath(env) {
16628
- return join16(webhooksDir(env), "signing-secret");
16765
+ return join17(webhooksDir(env), "signing-secret");
16629
16766
  }
16630
16767
  function signingSecret(env) {
16631
16768
  const file = signingSecretPath(env);
@@ -16676,7 +16813,7 @@ async function forward(url, event, secret, signal) {
16676
16813
  }
16677
16814
  }
16678
16815
  function statePath(env, workspaceId) {
16679
- return join16(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
16816
+ return join17(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
16680
16817
  }
16681
16818
  function writeListenerState(env, workspaceId, state) {
16682
16819
  writeFileSync4(statePath(env, workspaceId), `${JSON.stringify(state)}
@@ -17016,8 +17153,8 @@ var init_status3 = __esm({
17016
17153
  });
17017
17154
 
17018
17155
  // src/work/files.ts
17019
- import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
17020
- import { join as join17 } from "node:path";
17156
+ import { closeSync as closeSync2, constants, fchmodSync, fstatSync, lstatSync, openSync as openSync2, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
17157
+ import { join as join18 } from "node:path";
17021
17158
  function agentName(value) {
17022
17159
  if (typeof value !== "string") return void 0;
17023
17160
  const name = value.trim().slice(0, MAX_AGENT_NAME);
@@ -17033,30 +17170,30 @@ function workFileName(claimId) {
17033
17170
  if (!isPlainFileName(claimId)) throw new Error("claimId is not a plain file name");
17034
17171
  return `${claimId}.work.json`;
17035
17172
  }
17036
- function writeWorkFile(dir, work, mode = 384) {
17173
+ function writeWorkFile(dir2, work, mode = 384) {
17037
17174
  const name = workFileName(work.claimId);
17038
17175
  if (!isPlainFileName(work.answersFile)) throw new Error("answersFile is not a plain file name");
17039
- const path = join17(dir, name);
17040
- const fd = openSync(path, "wx", mode);
17176
+ const path = join18(dir2, name);
17177
+ const fd = openSync2(path, "wx", mode);
17041
17178
  try {
17042
17179
  writeFileSync5(fd, JSON.stringify(work, null, 2) + "\n", "utf8");
17043
17180
  fchmodSync(fd, mode);
17044
17181
  } finally {
17045
- closeSync(fd);
17182
+ closeSync2(fd);
17046
17183
  }
17047
17184
  return path;
17048
17185
  }
17049
17186
  function readRegularFile(path, what) {
17050
17187
  const notPlain = { ok: false, error: `the ${what} is not a plain file` };
17051
17188
  if (!lstatSync(path).isFile()) return notPlain;
17052
- const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
17189
+ const fd = openSync2(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
17053
17190
  try {
17054
17191
  const stat3 = fstatSync(fd);
17055
17192
  if (!stat3.isFile()) return notPlain;
17056
17193
  if (stat3.size > MAX_ANSWERS_FILE_BYTES) return { ok: false, error: `the ${what} is too large` };
17057
17194
  return readFileSync11(fd, "utf8");
17058
17195
  } finally {
17059
- closeSync(fd);
17196
+ closeSync2(fd);
17060
17197
  }
17061
17198
  }
17062
17199
  function isObject2(value) {
@@ -17086,25 +17223,25 @@ function readAnswersFile(path, work) {
17086
17223
  const answers = [];
17087
17224
  const dropped = [];
17088
17225
  const answered = /* @__PURE__ */ new Set();
17089
- doc.answers.forEach((entry, index) => {
17226
+ doc.answers.forEach((entry, index2) => {
17090
17227
  if (!isObject2(entry)) {
17091
- dropped.push({ index, reason: "not_an_object" });
17228
+ dropped.push({ index: index2, reason: "not_an_object" });
17092
17229
  return;
17093
17230
  }
17094
17231
  const itemId = entry.itemId;
17095
17232
  const format = typeof itemId === "string" ? formats.get(itemId) : void 0;
17096
17233
  if (typeof itemId !== "string" || format === void 0) {
17097
- dropped.push({ index, itemId: typeof itemId === "string" ? itemId : void 0, reason: "unknown_item" });
17234
+ dropped.push({ index: index2, itemId: typeof itemId === "string" ? itemId : void 0, reason: "unknown_item" });
17098
17235
  return;
17099
17236
  }
17100
17237
  if (answered.has(itemId)) {
17101
- dropped.push({ index, itemId, reason: "duplicate" });
17238
+ dropped.push({ index: index2, itemId, reason: "duplicate" });
17102
17239
  return;
17103
17240
  }
17104
17241
  const output = entry.output;
17105
17242
  const fits = format === "json" ? isObject2(output) : typeof output === "string";
17106
17243
  if (!fits) {
17107
- dropped.push({ index, itemId, reason: "wrong_output_type" });
17244
+ dropped.push({ index: index2, itemId, reason: "wrong_output_type" });
17108
17245
  return;
17109
17246
  }
17110
17247
  answered.add(itemId);
@@ -17260,7 +17397,7 @@ var init_agent_user = __esm({
17260
17397
  // src/commands/work/folder.ts
17261
17398
  import { existsSync as existsSync9 } from "node:fs";
17262
17399
  import { appendFile as appendFile3, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
17263
- import { dirname as dirname3, join as join18, resolve as resolve14 } from "node:path";
17400
+ import { dirname as dirname3, join as join19, resolve as resolve14 } from "node:path";
17264
17401
  var WorkRunFolder;
17265
17402
  var init_folder2 = __esm({
17266
17403
  "src/commands/work/folder.ts"() {
@@ -17300,32 +17437,32 @@ var init_folder2 = __esm({
17300
17437
  async make() {
17301
17438
  const root2 = runsRoot(this.ctx.env);
17302
17439
  const makeDir = (path) => this.shared ? ensureDir(path, SHARED_DIR_MODE) : ensurePrivateDir2(path);
17303
- let dir;
17440
+ let dir2;
17304
17441
  if (this.outDir === void 0) {
17305
- dir = join18(root2, this.runId);
17442
+ dir2 = join19(root2, this.runId);
17306
17443
  if (!this.shared) ensurePrivateDir2(root2);
17307
- makeDir(dir);
17444
+ makeDir(dir2);
17308
17445
  } else {
17309
- dir = resolve14(this.outDir);
17310
- const existing = existsSync9(join18(dir, "run.json")) ? await readRunDir(dir) : null;
17446
+ dir2 = resolve14(this.outDir);
17447
+ const existing = existsSync9(join19(dir2, "run.json")) ? await readRunDir(dir2) : null;
17311
17448
  if (existing && !existing.command.startsWith("work ")) {
17312
- throw usageError(`${dir} already holds run ${existing.runId} (${existing.command}).`, {
17449
+ throw usageError(`${dir2} already holds run ${existing.runId} (${existing.command}).`, {
17313
17450
  field: "out",
17314
17451
  hint: "Pick another --out directory, or leave --out off to keep the work under the runs directory."
17315
17452
  });
17316
17453
  }
17317
- makeDir(dir);
17318
- for (const name of ["results.ndjson", "summary.json"]) await unlink3(join18(dir, name)).catch(() => void 0);
17454
+ makeDir(dir2);
17455
+ for (const name of ["results.ndjson", "summary.json"]) await unlink3(join19(dir2, name)).catch(() => void 0);
17319
17456
  try {
17320
17457
  if (!this.shared) ensurePrivateDir2(root2);
17321
- await symlink2(dir, join18(root2, this.runId), "junction");
17458
+ await symlink2(dir2, join19(root2, this.runId), "junction");
17322
17459
  } catch (err) {
17323
- this.ctx.output.warn(`Could not link ${dir} into ${root2} (${err.message}): kenso runs will not list this run.`);
17460
+ this.ctx.output.warn(`Could not link ${dir2} into ${root2} (${err.message}): kenso runs will not list this run.`);
17324
17461
  }
17325
17462
  }
17326
- this.dir = dir;
17463
+ this.dir = dir2;
17327
17464
  if (this.shared) {
17328
- this.tmpDir = join18(dir, "tmp");
17465
+ this.tmpDir = join19(dir2, "tmp");
17329
17466
  ensureDir(this.tmpDir, JOB_DIR_MODE);
17330
17467
  }
17331
17468
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -17338,28 +17475,28 @@ var init_folder2 = __esm({
17338
17475
  status: "running",
17339
17476
  chunkCount: 0,
17340
17477
  chunksDone: [],
17341
- dir,
17478
+ dir: dir2,
17342
17479
  rows: 0,
17343
17480
  cwd: process.cwd(),
17344
17481
  pid: process.pid,
17345
17482
  updatedAt: now
17346
17483
  };
17347
17484
  await writeRunRecord(this.record);
17348
- return dir;
17485
+ return dir2;
17349
17486
  }
17350
17487
  /**
17351
17488
  * A job's folder, jobs/<claimId> (a plain file name): private, or with --agent-user one the agent user's group
17352
17489
  * writes (3770) under a jobs folder it can only pass through (2750).
17353
17490
  */
17354
17491
  async jobDir(claimId) {
17355
- const dir = join18(await this.ensure(), "jobs", claimId);
17492
+ const dir2 = join19(await this.ensure(), "jobs", claimId);
17356
17493
  if (this.shared) {
17357
- ensureDir(dirname3(dir), SHARED_DIR_MODE);
17358
- ensureDir(dir, JOB_DIR_MODE);
17494
+ ensureDir(dirname3(dir2), SHARED_DIR_MODE);
17495
+ ensureDir(dir2, JOB_DIR_MODE);
17359
17496
  } else {
17360
- ensurePrivateDir2(dir);
17497
+ ensurePrivateDir2(dir2);
17361
17498
  }
17362
- return dir;
17499
+ return dir2;
17363
17500
  }
17364
17501
  /**
17365
17502
  * One line of results.ndjson, each string redacted: a failed job's detail is the agent's own stderr, which can hold
@@ -17368,13 +17505,13 @@ var init_folder2 = __esm({
17368
17505
  async append(line) {
17369
17506
  if (!this.dir) return;
17370
17507
  const json = JSON.stringify(line, (_key, value) => typeof value === "string" ? redact(value) : value);
17371
- await appendFile3(join18(this.dir, "results.ndjson"), `${json}
17508
+ await appendFile3(join19(this.dir, "results.ndjson"), `${json}
17372
17509
  `, { mode: 384 });
17373
17510
  }
17374
17511
  /** summary.json, and run.json with the final status, the claims (chunkCount) and the items (rows). */
17375
17512
  async finish(status, claims, items, summary) {
17376
17513
  if (!this.dir || !this.record) return;
17377
- await writeJsonAtomic(join18(this.dir, "summary.json"), summary);
17514
+ await writeJsonAtomic(join19(this.dir, "summary.json"), summary);
17378
17515
  this.record = { ...this.record, status, chunkCount: claims, rows: items, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
17379
17516
  await writeRunRecord(this.record);
17380
17517
  }
@@ -17481,7 +17618,7 @@ var init_pull2 = __esm({
17481
17618
  // src/commands/work/answers.ts
17482
17619
  import { randomUUID as randomUUID3 } from "node:crypto";
17483
17620
  import { existsSync as existsSync10 } from "node:fs";
17484
- import { basename as basename5, dirname as dirname4, join as join19 } from "node:path";
17621
+ import { basename as basename5, dirname as dirname4, join as join20 } from "node:path";
17485
17622
  function zeroTotals() {
17486
17623
  return { accepted: 0, rejected: 0, expired: 0, duplicate: 0, dropped: 0 };
17487
17624
  }
@@ -17553,7 +17690,7 @@ function droppedResult(d) {
17553
17690
  return { itemId: d.itemId ?? null, status: "dropped", reason: d.reason, message: `Answer ${d.index + 1} of the file was not sent: ${d.reason.replace(/_/g, " ")}.` };
17554
17691
  }
17555
17692
  async function writeResults(answersPath, claimId, results, totals) {
17556
- const path = join19(dirname4(answersPath), `${claimId}.results.json`);
17693
+ const path = join20(dirname4(answersPath), `${claimId}.results.json`);
17557
17694
  await writeJsonAtomic(path, { version: 1, claimId, submittedAt: (/* @__PURE__ */ new Date()).toISOString(), ...totals, results });
17558
17695
  return path;
17559
17696
  }
@@ -17582,7 +17719,7 @@ function workFileNextTo(answersPath) {
17582
17719
  hint: "Write the answers to <claimId>.answers.json next to its <claimId>.work.json, as the work file's rules say."
17583
17720
  });
17584
17721
  }
17585
- const workPath = join19(dirname4(answersPath), `${claimId}.work.json`);
17722
+ const workPath = join20(dirname4(answersPath), `${claimId}.work.json`);
17586
17723
  if (!existsSync10(workPath)) {
17587
17724
  throw usageError(`${workPath} is missing: kenso work submit reads it next to the answers file.`, { field: "answers-file" });
17588
17725
  }
@@ -17714,7 +17851,7 @@ var init_release = __esm({
17714
17851
  import { spawn as nodeSpawn3 } from "node:child_process";
17715
17852
  import { rmSync as rmSync3, statSync as statSync2 } from "node:fs";
17716
17853
  import { access, constants as constants2 } from "node:fs/promises";
17717
- import { delimiter as delimiter2, join as join20 } from "node:path";
17854
+ import { delimiter as delimiter2, join as join21 } from "node:path";
17718
17855
  import { setTimeout as delay12 } from "node:timers/promises";
17719
17856
  function childEnv(parent, adapter, extra) {
17720
17857
  const scrub = new Set(adapter.scrubEnv.map((name) => name.toUpperCase()));
@@ -17739,7 +17876,7 @@ async function isExecutableFile(path) {
17739
17876
  function pathDirs(env) {
17740
17877
  const key = Object.keys(env).find((name) => name.toUpperCase() === "PATH");
17741
17878
  const value = key ? env[key] : void 0;
17742
- return (value ?? "").split(delimiter2).filter((dir) => dir !== "");
17879
+ return (value ?? "").split(delimiter2).filter((dir2) => dir2 !== "");
17743
17880
  }
17744
17881
  async function resolveBinary(adapter, env, override2) {
17745
17882
  const names = override2 !== void 0 && override2 !== "" ? [override2] : adapter.binaries;
@@ -17749,9 +17886,9 @@ async function resolveBinary(adapter, env, override2) {
17749
17886
  if (await isExecutableFile(name)) return name;
17750
17887
  continue;
17751
17888
  }
17752
- for (const dir of pathDirs(env)) {
17889
+ for (const dir2 of pathDirs(env)) {
17753
17890
  for (const ext of extensions) {
17754
- const candidate = join20(dir, name + ext);
17891
+ const candidate = join21(dir2, name + ext);
17755
17892
  if (await isExecutableFile(candidate)) return candidate;
17756
17893
  }
17757
17894
  }
@@ -17917,11 +18054,11 @@ async function runAgentJob(adapter, job, deps) {
17917
18054
  }
17918
18055
  let work;
17919
18056
  try {
17920
- work = readWorkFile(join20(job.cwd, job.workFile));
18057
+ work = readWorkFile(join21(job.cwd, job.workFile));
17921
18058
  } catch (err) {
17922
18059
  return result("fatal", null, `the work file could not be read: ${err.message}`);
17923
18060
  }
17924
- const answersPath = join20(job.cwd, job.answersFile);
18061
+ const answersPath = join21(job.cwd, job.answersFile);
17925
18062
  try {
17926
18063
  rmSync3(answersPath, { force: true });
17927
18064
  } catch (err) {
@@ -18331,7 +18468,7 @@ ${out.stderr}`;
18331
18468
  });
18332
18469
 
18333
18470
  // src/work/adapters/opencode.ts
18334
- import { basename as basename6, join as join21 } from "node:path";
18471
+ import { basename as basename6, join as join22 } from "node:path";
18335
18472
  var opencode;
18336
18473
  var init_opencode = __esm({
18337
18474
  "src/work/adapters/opencode.ts"() {
@@ -18375,7 +18512,7 @@ ${out.stderr}`);
18375
18512
  if (job.model) args.push("--model", job.model);
18376
18513
  args.push(job.instruction);
18377
18514
  const env = { OPENCODE_CONFIG_CONTENT: JSON.stringify(config) };
18378
- if (job.tmpDir !== void 0) env.OPENCODE_DB = join21(job.tmpDir, `opencode-${basename6(job.cwd)}.db`);
18515
+ if (job.tmpDir !== void 0) env.OPENCODE_DB = join22(job.tmpDir, `opencode-${basename6(job.cwd)}.db`);
18379
18516
  return { args, env };
18380
18517
  },
18381
18518
  classify: classifyByExit
@@ -18462,7 +18599,7 @@ function decodings(text4) {
18462
18599
  }
18463
18600
  return out;
18464
18601
  }
18465
- function scanFields(fields, index) {
18602
+ function scanFields(fields, index2) {
18466
18603
  const readings = [];
18467
18604
  for (const field of fields) {
18468
18605
  readings.push({ text: field, foldedOnly: false, entropy: true });
@@ -18476,7 +18613,7 @@ function scanFields(fields, index) {
18476
18613
  for (const decoded of decodings(foldedJoined)) readings.push({ text: decoded, foldedOnly: false, entropy: false });
18477
18614
  const reasons = /* @__PURE__ */ new Set();
18478
18615
  for (const reading of readings) {
18479
- if (index.hit(reading.text, reading.foldedOnly)) reasons.add("credential_file_content");
18616
+ if (index2.hit(reading.text, reading.foldedOnly)) reasons.add("credential_file_content");
18480
18617
  if (SHAPES.some((shape) => shape.test(reading.text))) reasons.add("credential_shape");
18481
18618
  if (reading.entropy && hasHighEntropyRun(reading.text)) reasons.add("high_entropy_run");
18482
18619
  }
@@ -18580,7 +18717,7 @@ var init_scan = __esm({
18580
18717
 
18581
18718
  // src/work/credentials.ts
18582
18719
  import { createHash as createHash9 } from "node:crypto";
18583
- import { join as join22 } from "node:path";
18720
+ import { join as join23 } from "node:path";
18584
18721
  function unreadable(why) {
18585
18722
  return new KensoError({
18586
18723
  code: "credentials_unreadable",
@@ -18668,7 +18805,7 @@ var init_credentials = __esm({
18668
18805
  }
18669
18806
  }
18670
18807
  async read(rel) {
18671
- const r = await sudoExec(this.user, CAT, [join22(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
18808
+ const r = await sudoExec(this.user, CAT, [join23(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
18672
18809
  if (r.exitCode !== 0) return /No such file or directory/.test(r.stderr) ? "missing" : "unreadable";
18673
18810
  const digest = createHash9("sha256").update(r.stdout).digest("hex");
18674
18811
  if (this.seen.get(rel) !== digest) {
@@ -18682,21 +18819,21 @@ var init_credentials = __esm({
18682
18819
  });
18683
18820
 
18684
18821
  // src/work/guide.ts
18685
- import { closeSync as closeSync2, fchmodSync as fchmodSync2, openSync as openSync2, writeFileSync as writeFileSync6 } from "node:fs";
18686
- import { join as join23 } from "node:path";
18822
+ import { closeSync as closeSync3, fchmodSync as fchmodSync2, openSync as openSync3, writeFileSync as writeFileSync6 } from "node:fs";
18823
+ import { join as join24 } from "node:path";
18687
18824
  function agentGuide(opts) {
18688
18825
  const browser = opts.browser ?? findOperation("browser-runs", "create") !== void 0;
18689
18826
  const parts2 = opts.kensoKey ? [JOB, KENSO, ...browser ? [BROWSER] : [], NEVER] : [JOB, NO_KENSO, NEVER];
18690
18827
  return parts2.join("\n");
18691
18828
  }
18692
- function writeAgentGuide(dir, text4, mode = WORK_FILE_MODE) {
18829
+ function writeAgentGuide(dir2, text4, mode = WORK_FILE_MODE) {
18693
18830
  for (const name of GUIDE_FILES) {
18694
- const fd = openSync2(join23(dir, name), "wx", mode);
18831
+ const fd = openSync3(join24(dir2, name), "wx", mode);
18695
18832
  try {
18696
18833
  writeFileSync6(fd, text4, "utf8");
18697
18834
  fchmodSync2(fd, mode);
18698
18835
  } finally {
18699
- closeSync2(fd);
18836
+ closeSync3(fd);
18700
18837
  }
18701
18838
  }
18702
18839
  }
@@ -19321,11 +19458,11 @@ var init_run3 = __esm({
19321
19458
  }
19322
19459
  try {
19323
19460
  workFileName(claim.id);
19324
- const dir = await folder.jobDir(claim.id);
19461
+ const dir2 = await folder.jobDir(claim.id);
19325
19462
  const work = workFileOf(claim);
19326
- writeWorkFile(dir, work, runAs ? WORK_FILE_MODE : void 0);
19327
- if (tools) writeAgentGuide(dir, tools.guide);
19328
- return { claim, work, dir };
19463
+ writeWorkFile(dir2, work, runAs ? WORK_FILE_MODE : void 0);
19464
+ if (tools) writeAgentGuide(dir2, tools.guide);
19465
+ return { claim, work, dir: dir2 };
19329
19466
  } catch (err) {
19330
19467
  await releaseOnce(claim.id);
19331
19468
  error = err instanceof KensoError ? err : new KensoError({ code: "work_file_failed", message: `Could not write the work file: ${err.message}`, exitCode: ExitCode.Error });
@@ -20191,12 +20328,12 @@ var init_flag_names = __esm({
20191
20328
 
20192
20329
  // src/core/invoked.ts
20193
20330
  import { realpathSync } from "node:fs";
20194
- import { pathToFileURL } from "node:url";
20331
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
20195
20332
  function invokedDirectly(moduleUrl) {
20196
20333
  const script = process.argv[1];
20197
20334
  if (!script) return false;
20198
20335
  try {
20199
- return moduleUrl === pathToFileURL(realpathSync(script)).href;
20336
+ return moduleUrl === pathToFileURL2(realpathSync(script)).href;
20200
20337
  } catch {
20201
20338
  return false;
20202
20339
  }
@@ -20209,13 +20346,13 @@ var init_invoked = __esm({
20209
20346
 
20210
20347
  // src/core/update-notice.ts
20211
20348
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync13, realpathSync as realpathSync2, renameSync as renameSync4, writeFileSync as writeFileSync7 } from "node:fs";
20212
- import { dirname as dirname5, join as join24, sep as sep3 } from "node:path";
20349
+ import { dirname as dirname5, join as join25, sep as sep3 } from "node:path";
20213
20350
  function installKind(script = process.argv[1], execPath = process.execPath, platform = process.platform) {
20214
20351
  try {
20215
20352
  if (!script) return "npm";
20216
20353
  const bundle = realpathSync2(script);
20217
20354
  const lib = dirname5(dirname5(dirname5(bundle)));
20218
- if (execPath !== join24(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
20355
+ if (execPath !== join25(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
20219
20356
  return bundle.includes(`${sep3}Cellar${sep3}kenso${sep3}`) ? "homebrew" : "standalone";
20220
20357
  } catch {
20221
20358
  return "npm";
@@ -20275,7 +20412,7 @@ function startUpdateNotice(argv, opts = {}) {
20275
20412
  const stderr = opts.stderr ?? process.stderr;
20276
20413
  const wanted = (opts.stderrIsTTY ?? process.stderr.isTTY === true) && detectAgent(env) === null && env.CI === void 0 && !env.KENSO_NO_UPDATE_NOTIFIER && RELEASE.test(version) && !argv.some((word) => QUIET_COMMANDS.has(word));
20277
20414
  if (!wanted) return done;
20278
- const file = join24(configDir(env), UPDATE_CHECK_FILE);
20415
+ const file = join25(configDir(env), UPDATE_CHECK_FILE);
20279
20416
  const now = (opts.now ?? Date.now)();
20280
20417
  const cached = readCheck(file);
20281
20418
  const checkedAt = Date.parse(cached?.checkedAt ?? "");
@@ -20335,11 +20472,11 @@ __export(complete_exports, {
20335
20472
  });
20336
20473
  function resources() {
20337
20474
  const names = Object.entries(handWritten).filter(([, area]) => Object.keys(area).length > 0).map(([resource]) => resource);
20338
- return sorted([...names, ...Object.keys(resourceAliases), ...loadManifest().operations.map((op) => op.resource)]);
20475
+ return sorted([...names, ...Object.keys(resourceAliases), ...listOperations().map((op) => op.resource)]);
20339
20476
  }
20340
20477
  function actions33(resource) {
20341
20478
  const own = Object.keys(handWritten[resource] ?? {}).filter((action) => action !== "");
20342
- return sorted([...own, ...loadManifest().operations.filter((op) => op.resource === resource).map((op) => op.action)]);
20479
+ return sorted([...own, ...listOperations().filter((op) => op.resource === resource).map((op) => op.action)]);
20343
20480
  }
20344
20481
  function flagName(word, spec, globals) {
20345
20482
  if (word.startsWith("--")) return word.slice(2).split("=")[0];