kenso 0.1.157 → 0.1.159

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
@@ -240,8 +240,9 @@ var init_api_key = __esm({
240
240
  });
241
241
 
242
242
  // src/core/folder.ts
243
- import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
244
- import { dirname, join, resolve } from "node:path";
243
+ import { existsSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
244
+ import { homedir } from "node:os";
245
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
245
246
  function invalid(path, message, field) {
246
247
  return new KensoError({
247
248
  code: "folder_file_invalid",
@@ -298,18 +299,48 @@ function readFolderFile(path) {
298
299
  }
299
300
  return file;
300
301
  }
301
- function findFolderFile(start) {
302
+ function untrustedReason(path) {
303
+ const uid = process.getuid?.();
304
+ if (uid === void 0) return void 0;
305
+ try {
306
+ const file = statSync(path);
307
+ const dir3 = statSync(dirname(path));
308
+ if (file.uid !== uid) return `another user (uid ${file.uid}) owns it`;
309
+ if ((file.mode & 2) !== 0) return `anyone can write it (mode ${(file.mode & 511).toString(8)})`;
310
+ if ((dir3.mode & 2) !== 0) return `anyone can write its folder (mode ${(dir3.mode & 511).toString(8)})`;
311
+ return void 0;
312
+ } catch (err) {
313
+ return `it cannot be checked (${err.code ?? "error"})`;
314
+ }
315
+ }
316
+ function refuseUntrusted(path) {
317
+ const reason = existsSync(path) ? untrustedReason(path) : void 0;
318
+ if (reason === void 0) return;
319
+ throw new KensoError({
320
+ code: "folder_file_untrusted",
321
+ message: `kenso does not use ${path}: ${reason}.`,
322
+ exitCode: ExitCode.Usage,
323
+ hint: "A kenso.json another user could have written could pick the workspace your key acts in. Make it yours and writable only by you (chmod o-w on it and its folder), or move your files to a folder only you can write."
324
+ });
325
+ }
326
+ function findFolderFile(start, home2 = homedir(), onSkip) {
327
+ const top = resolve(home2);
302
328
  let dir3 = resolve(start);
303
329
  for (; ; ) {
330
+ const fromDir = relative(dir3, top);
331
+ if (fromDir !== "" && !isAbsolute(fromDir) && fromDir.split(sep)[0] !== "..") return void 0;
304
332
  const path = join(dir3, FOLDER_FILE);
305
- if (existsSync(path)) return readFolderFile(path);
306
- if (existsSync(join(dir3, ".git"))) return void 0;
333
+ const reason = existsSync(path) ? untrustedReason(path) : void 0;
334
+ if (reason !== void 0) onSkip?.(path, reason);
335
+ else if (existsSync(path)) return readFolderFile(path);
336
+ if (existsSync(join(dir3, ".git")) || dir3 === top) return void 0;
307
337
  const parent = dirname(dir3);
308
338
  if (parent === dir3) return void 0;
309
339
  dir3 = parent;
310
340
  }
311
341
  }
312
342
  function writeFolderFile(file) {
343
+ refuseUntrusted(file.path);
313
344
  let out = {};
314
345
  if (existsSync(file.path)) {
315
346
  try {
@@ -350,11 +381,11 @@ var init_folder = __esm({
350
381
 
351
382
  // src/core/config.ts
352
383
  import { chmodSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync as renameSync2, rmSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
353
- import { homedir } from "node:os";
384
+ import { homedir as homedir2 } from "node:os";
354
385
  import { join as join2 } from "node:path";
355
386
  function configDir(env = process.env) {
356
387
  const override2 = env.KENSO_CONFIG_DIR?.trim();
357
- return override2 ? override2 : join2(homedir(), ".kenso");
388
+ return override2 ? override2 : join2(homedir2(), ".kenso");
358
389
  }
359
390
  function configPath(env = process.env) {
360
391
  return join2(configDir(env), CONFIG_FILE);
@@ -457,7 +488,8 @@ function nonEmpty(value) {
457
488
  }
458
489
  function resolveAuth(flags, env = process.env, cwd = process.cwd()) {
459
490
  const config = readConfig(env);
460
- const folder = findFolderFile(cwd);
491
+ let skipped;
492
+ const folder = findFolderFile(cwd, void 0, (path, reason) => skipped ??= `${path}: ${reason}`);
461
493
  const chosenProfile = nonEmpty(flags.profile) ?? nonEmpty(env.KENSO_PROFILE);
462
494
  const profileName = chosenProfile ?? folder?.profile ?? config.activeProfile;
463
495
  const profile = config.profiles[profileName] ?? {};
@@ -478,7 +510,8 @@ function resolveAuth(flags, env = process.env, cwd = process.cwd()) {
478
510
  profileName,
479
511
  source,
480
512
  ...folder ? { folderFile: folder.path } : {},
481
- ...folder?.profile && !chosenProfile ? { profileFromFolder: true } : {}
513
+ ...folder?.profile && !chosenProfile ? { profileFromFolder: true } : {},
514
+ ...skipped ? { folderFileSkipped: skipped } : {}
482
515
  };
483
516
  }
484
517
  function folderProfileNotice(auth) {
@@ -3389,7 +3422,7 @@ var VERSION;
3389
3422
  var init_version = __esm({
3390
3423
  "src/core/version.ts"() {
3391
3424
  "use strict";
3392
- VERSION = true ? "0.1.157" : "0.0.0-dev";
3425
+ VERSION = true ? "0.1.159" : "0.0.0-dev";
3393
3426
  }
3394
3427
  });
3395
3428
 
@@ -3684,9 +3717,9 @@ async function readAnswer(ctx) {
3684
3717
  const lines = createInterface({ input: ctx.stdin ?? process.stdin, terminal: false });
3685
3718
  let onAbort;
3686
3719
  try {
3687
- return await new Promise((resolve23, reject) => {
3688
- lines.once("line", resolve23);
3689
- lines.once("close", () => resolve23(""));
3720
+ return await new Promise((resolve24, reject) => {
3721
+ lines.once("line", resolve24);
3722
+ lines.once("close", () => resolve24(""));
3690
3723
  onAbort = () => reject(interrupted());
3691
3724
  ctx.signal.addEventListener("abort", onAbort, { once: true });
3692
3725
  });
@@ -3729,9 +3762,9 @@ function mustRethrow(err) {
3729
3762
  }
3730
3763
  function creditsCheck(neededMillicredits, availableMillicredits2) {
3731
3764
  return {
3732
- needed: neededMillicredits / 1e3,
3765
+ needed: neededMillicredits === void 0 ? null : neededMillicredits / 1e3,
3733
3766
  available: availableMillicredits2 === void 0 ? null : availableMillicredits2 / 1e3,
3734
- sufficient: availableMillicredits2 === void 0 ? null : neededMillicredits <= availableMillicredits2
3767
+ sufficient: neededMillicredits === void 0 || availableMillicredits2 === void 0 ? null : neededMillicredits <= availableMillicredits2
3735
3768
  };
3736
3769
  }
3737
3770
  async function ask(ctx, path, body2, read2) {
@@ -4221,6 +4254,57 @@ var init_rate_card = __esm({
4221
4254
  }
4222
4255
  });
4223
4256
 
4257
+ // src/commands/credits/common.ts
4258
+ function toCredits(millicredits) {
4259
+ return typeof millicredits === "number" && Number.isFinite(millicredits) ? Math.round(millicredits) / 1e3 : void 0;
4260
+ }
4261
+ function positiveFlag(flags, name) {
4262
+ const raw = flags[name];
4263
+ if (raw === void 0) return void 0;
4264
+ const text4 = String(raw).trim();
4265
+ if (!/^\d+$/.test(text4) || Number(text4) < 1 || !Number.isSafeInteger(Number(text4))) {
4266
+ throw usageError(`--${name} must be a positive whole number, not "${text4}".`, { field: name });
4267
+ }
4268
+ return Number(text4);
4269
+ }
4270
+ function instantFlag(flags, name) {
4271
+ const raw = flags[name];
4272
+ if (typeof raw !== "string") return void 0;
4273
+ const text4 = raw.trim();
4274
+ const back = /^(\d+)([dh])$/.exec(text4);
4275
+ if (back) return new Date(Date.now() - Number(back[1]) * (back[2] === "d" ? DAY_MS : DAY_MS / 24)).toISOString();
4276
+ const day = /^\d{4}-\d{2}-\d{2}$/.test(text4);
4277
+ const ms = Date.parse(day ? `${text4}T00:00:00Z` : text4);
4278
+ if (Number.isNaN(ms)) {
4279
+ throw usageError(`--${name} "${text4}" is not a date.`, { field: name, hint: "Use 7d, 12h, 2026-11-01 or 2026-11-01T09:00:00Z." });
4280
+ }
4281
+ return new Date(day && name === "until" ? ms + DAY_MS - 1 : ms).toISOString();
4282
+ }
4283
+ async function readAvailable(ctx) {
4284
+ try {
4285
+ const res = await ctx.client.request({ method: "GET", path: "/v1/credits", signal: ctx.signal });
4286
+ const available = unwrap(res.body)?.availableMillicredits;
4287
+ return { available: typeof available === "number" ? available : void 0 };
4288
+ } catch (err) {
4289
+ if (err instanceof KensoError && (err.exitCode === ExitCode.Auth || err.exitCode === ExitCode.Interrupted)) throw err;
4290
+ ctx.output.warn(`Could not read the available credits: ${err instanceof Error ? err.message : String(err)}`);
4291
+ return { estimateError: err instanceof KensoError ? { code: err.code, message: err.message } : { message: String(err) } };
4292
+ }
4293
+ }
4294
+ function estimateFailed(error) {
4295
+ return new KensoError({ code: error.code ?? "estimate_failed", message: error.message, exitCode: ExitCode.Error });
4296
+ }
4297
+ var DAY_MS;
4298
+ var init_common = __esm({
4299
+ "src/commands/credits/common.ts"() {
4300
+ "use strict";
4301
+ init_errors();
4302
+ init_exit_codes();
4303
+ init_http();
4304
+ DAY_MS = 864e5;
4305
+ }
4306
+ });
4307
+
4224
4308
  // src/core/sse.ts
4225
4309
  var SseParser;
4226
4310
  var init_sse = __esm({
@@ -4607,7 +4691,7 @@ var init_results = __esm({
4607
4691
 
4608
4692
  // src/batch/runs.ts
4609
4693
  import { randomBytes } from "node:crypto";
4610
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, statSync } from "node:fs";
4694
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, statSync as statSync2 } from "node:fs";
4611
4695
  import { open, readdir, realpath, rename, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
4612
4696
  import { join as join7, resolve as resolve3 } from "node:path";
4613
4697
  function runsRoot(env = process.env) {
@@ -4681,7 +4765,7 @@ function ensureDir(dir3, mode) {
4681
4765
  throw notPrivateError(dir3, `kenso cannot set its mode (${err.code ?? String(err)})`);
4682
4766
  }
4683
4767
  if (uid === void 0) return;
4684
- const stats = statSync(dir3);
4768
+ const stats = statSync2(dir3);
4685
4769
  if (stats.uid !== uid) throw notPrivateError(dir3, `another user (uid ${stats.uid}) owns it`);
4686
4770
  if ((stats.mode & 18 & ~mode) !== 0) throw notPrivateError(dir3, `its mode stayed ${modeText(stats)} after kenso set it`);
4687
4771
  }
@@ -7368,7 +7452,10 @@ async function runEach(ctx, op, values, file, opts = {}) {
7368
7452
  const args = eachArgs(op, opts.argValues ?? values, file);
7369
7453
  const applyCommand = commandLine(op, args, ctx, ["--yes"]);
7370
7454
  if (!isRead(op) && ctx.flags.yes !== true && ctx.flags.dryRun !== true) {
7371
- 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 });
7455
+ throw usageError(`--each sends one ${op.method} per row: run --dry-run to see the plan first, then its next adds --yes.`, {
7456
+ field: "yes",
7457
+ next: commandLine(op, args, ctx, ["--dry-run"])
7458
+ });
7372
7459
  }
7373
7460
  const input = await readInput(file, { stdin: ctx.stdin });
7374
7461
  const index2 = paramIndex(op);
@@ -7383,6 +7470,7 @@ async function runEach(ctx, op, values, file, opts = {}) {
7383
7470
  invalid2.push({ row, status: "invalid", reason: err.code, error: err.message, ...err.field ? { field: err.field } : {} });
7384
7471
  }
7385
7472
  });
7473
+ const spend = ctx.flags.dryRun === true && op.effect === "spend" ? await spendCost(ctx, op, items.map((item) => item.request)) : {};
7386
7474
  const outcome = await runBatch(
7387
7475
  {
7388
7476
  command: `${op.resource} ${op.action}`,
@@ -7397,7 +7485,7 @@ async function runEach(ctx, op, values, file, opts = {}) {
7397
7485
  execChunk: (chunk, chunkCtx) => sendRow(chunk[0], chunkCtx),
7398
7486
  invalid: invalid2,
7399
7487
  dryRun: ctx.flags.dryRun === true,
7400
- dryRunExtra: { operationId: op.id, firstRequest: preview(items[0]?.request, op) },
7488
+ dryRunExtra: { operationId: op.id, firstRequest: preview(items[0]?.request, op), ...spend },
7401
7489
  applyCommand
7402
7490
  },
7403
7491
  ctx
@@ -7435,7 +7523,8 @@ __export(execute_exports, {
7435
7523
  operationExamples: () => operationExamples,
7436
7524
  operationFlags: () => operationFlags,
7437
7525
  operationToCommand: () => operationToCommand,
7438
- secretParams: () => secretParams
7526
+ secretParams: () => secretParams,
7527
+ spendCost: () => spendCost
7439
7528
  });
7440
7529
  function isRecord4(value) {
7441
7530
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -7841,19 +7930,49 @@ async function* paginateLean(ctx, lean, plain2, opts) {
7841
7930
  yield* ctx.client.paginate(plain2, opts);
7842
7931
  }
7843
7932
  }
7844
- async function spendCost(ctx, op, req) {
7933
+ function chargedLines(op, req) {
7845
7934
  const skip = SKIPPED_CREDITS[op.id];
7846
- const skipped = skip !== void 0 && req.query?.[skip.query] === skip.value;
7847
- const lines = skipped ? (op.credits ?? []).filter((line) => !skip.drops.includes(line.action)) : op.credits ?? [];
7848
- if (skipped && lines.length === 0) return { cost: { lines: [], text: `not charged in credits (${skip.why})`, rateCard: null }, credits: creditsCheck(0, void 0) };
7849
- if (lines.length === 0) return { cost: { lines: [], rateCard: null } };
7850
- const cards = await loadRateCards(ctx);
7851
- return {
7852
- cost: {
7853
- lines: lines.map((line) => ({ ...line, price: priceLine(line, cards) })),
7854
- rateCard: { source: cards[0]?.source ?? "bundled", versions: cards.map((card) => card.version) }
7855
- }
7935
+ if (skip === void 0 || req.query?.[skip.query] !== skip.value) return { lines: op.credits ?? [] };
7936
+ return { lines: (op.credits ?? []).filter((line) => !skip.drops.includes(line.action)), skipped: skip.why };
7937
+ }
7938
+ function callMillicredits(op, charged, cards) {
7939
+ if (charged.lines.length === 0) return charged.skipped !== void 0 ? 0 : void 0;
7940
+ if (!ONE_UNIT_PER_CALL.has(op.id)) return void 0;
7941
+ let total = 0;
7942
+ for (const line of charged.lines) {
7943
+ const price = line.pricing === "varies" ? void 0 : unitMillicredits(line.action, cards);
7944
+ if (price === void 0) return void 0;
7945
+ total += price;
7946
+ }
7947
+ return total;
7948
+ }
7949
+ async function dryRunBalance(ctx) {
7950
+ try {
7951
+ return await readAvailable(ctx);
7952
+ } catch (err) {
7953
+ if (!(err instanceof KensoError) || err.exitCode !== ExitCode.Auth) throw err;
7954
+ ctx.output.warn(`Could not read the available credits: ${err.message}`);
7955
+ return { estimateError: { code: err.code, message: err.message } };
7956
+ }
7957
+ }
7958
+ async function spendCost(ctx, op, requests) {
7959
+ const charged = requests.map((req) => chargedLines(op, req));
7960
+ const first = charged[0] ?? { lines: op.credits ?? [] };
7961
+ if (charged.length > 0 && charged.every((c) => c.skipped !== void 0 && c.lines.length === 0)) {
7962
+ return { cost: { lines: [], text: `not charged in credits (${first.skipped})`, rateCard: null }, credits: creditsCheck(0, void 0) };
7963
+ }
7964
+ const cards = (op.credits?.length ?? 0) > 0 ? await loadRateCards(ctx) : [];
7965
+ const cost = first.lines.length === 0 ? { lines: [], rateCard: null } : {
7966
+ lines: first.lines.map((line) => ({ ...line, price: priceLine(line, cards) })),
7967
+ rateCard: { source: cards[0]?.source ?? "bundled", versions: cards.map((card) => card.version) }
7856
7968
  };
7969
+ let needed = 0;
7970
+ for (const call2 of charged) {
7971
+ const millicredits = callMillicredits(op, call2, cards);
7972
+ needed = needed === void 0 || millicredits === void 0 ? void 0 : needed + millicredits;
7973
+ }
7974
+ const { available, estimateError } = await dryRunBalance(ctx);
7975
+ return { cost, credits: creditsCheck(needed, available), ...estimateError ? { estimateError } : {} };
7857
7976
  }
7858
7977
  async function runOperation(ctx, op, flags) {
7859
7978
  const secrets = secretParams(op);
@@ -7873,7 +7992,7 @@ async function runOperation(ctx, op, flags) {
7873
7992
  const plain2 = buildRequest(op, values);
7874
7993
  const req = lean ? buildRequest(op, { ...values, ...lean }) : plain2;
7875
7994
  if (ctx.flags.dryRun) {
7876
- const cost = op.effect === "spend" ? await spendCost(ctx, op, req) : {};
7995
+ const cost = op.effect === "spend" ? await spendCost(ctx, op, [req]) : {};
7877
7996
  ctx.output.object({ dryRun: true, operationId: op.id, request: describeRequest(req, op), ...cost });
7878
7997
  return ExitCode.Ok;
7879
7998
  }
@@ -8002,7 +8121,7 @@ ${api}` : api,
8002
8121
  run: (ctx, args) => runOperation(ctx, op, args.flags)
8003
8122
  };
8004
8123
  }
8005
- var STREAM_HELP, DATA_KEY, IDEMPOTENCY_KEY, IDEMPOTENCY_KEY_FLAG, SCALAR_TYPES, FLAG_ALIASES, OUT_FLAG, CONTACT_FIELDS, COMPACT_FIELDS, COMPACT_NOTES, FULL_FLAG, LEAN_PARAMS, LIST_PARAM_TEXT, SKIPPED_CREDITS, HELP_NOTES_MAX, HELP_FLAG_MAX, FOOTER_FLAGS;
8124
+ var STREAM_HELP, DATA_KEY, IDEMPOTENCY_KEY, IDEMPOTENCY_KEY_FLAG, SCALAR_TYPES, FLAG_ALIASES, OUT_FLAG, CONTACT_FIELDS, COMPACT_FIELDS, COMPACT_NOTES, FULL_FLAG, LEAN_PARAMS, LIST_PARAM_TEXT, SKIPPED_CREDITS, ONE_UNIT_PER_CALL, HELP_NOTES_MAX, HELP_FLAG_MAX, FOOTER_FLAGS;
8006
8125
  var init_execute = __esm({
8007
8126
  "src/generated/execute.ts"() {
8008
8127
  "use strict";
@@ -8015,6 +8134,7 @@ var init_execute = __esm({
8015
8134
  init_secret_flags();
8016
8135
  init_transfer();
8017
8136
  init_rate_card();
8137
+ init_common();
8018
8138
  init_stream();
8019
8139
  STREAM_HELP = "A live stream: it prints one JSON line per event ({event, id, data}) as it arrives and runs until Ctrl-C, reconnecting when the server closes it (with Last-Event-ID once events carry an id). --until <event> ends after that event, --max-events <n> after n events, --once when the server closes it.";
8020
8140
  DATA_KEY = "$data";
@@ -8077,6 +8197,7 @@ var init_execute = __esm({
8077
8197
  why: "--skip-research: no research or committee run"
8078
8198
  }
8079
8199
  };
8200
+ ONE_UNIT_PER_CALL = /* @__PURE__ */ new Set(["email-finds.create", "search.get-place", "search.place-photos", "search.place-reviews"]);
8080
8201
  HELP_NOTES_MAX = 320;
8081
8202
  HELP_FLAG_MAX = 140;
8082
8203
  FOOTER_FLAGS = /* @__PURE__ */ new Set(["each", "concurrency", "data"]);
@@ -8712,7 +8833,7 @@ function warnDropped(ctx, mapping) {
8712
8833
  ctx.output.warn(`Not sent: ${list2}. Rename a column with --map '{"<column>": "customVariables.<name>"}'.`);
8713
8834
  }
8714
8835
  var OUT_FLAG2, CONCURRENCY_FLAG;
8715
- var init_common = __esm({
8836
+ var init_common2 = __esm({
8716
8837
  "src/commands/contacts/common.ts"() {
8717
8838
  "use strict";
8718
8839
  init_errors();
@@ -9050,7 +9171,7 @@ var init_bulk_update = __esm({
9050
9171
  init_errors();
9051
9172
  init_exit_codes();
9052
9173
  init_http();
9053
- init_common();
9174
+ init_common2();
9054
9175
  init_wait();
9055
9176
  POLL_MS = 2e3;
9056
9177
  MAX_IDS = 1e3;
@@ -9131,7 +9252,7 @@ var init_merge = __esm({
9131
9252
  init_errors();
9132
9253
  init_exit_codes();
9133
9254
  init_http();
9134
- init_common();
9255
+ init_common2();
9135
9256
  command3 = {
9136
9257
  resource: "accounts",
9137
9258
  action: "merge",
@@ -9344,7 +9465,7 @@ async function releaseClaim(ctx, claimId, headers = {}) {
9344
9465
  return isRecord6(data) && typeof data.released === "number" ? data.released : 0;
9345
9466
  }
9346
9467
  var BETA, KINDS_TEXT, MAX_PER_FILE, MIN_LEASE_MINUTES, MAX_LEASE_MINUTES, KIND_FLAG, CAMPAIGN_FLAG, LIVE_ONLY_FLAG, PER_FILE_FLAG, LEASE_FLAG, OUT_FLAG3, UNTIL_DONE, WORK_TIMING, MAX_UNAVAILABLE_WAITS;
9347
- var init_common2 = __esm({
9468
+ var init_common3 = __esm({
9348
9469
  "src/commands/work/common.ts"() {
9349
9470
  "use strict";
9350
9471
  init_errors();
@@ -9385,7 +9506,7 @@ var init_duplicates = __esm({
9385
9506
  init_errors();
9386
9507
  init_exit_codes();
9387
9508
  init_http();
9388
- init_common2();
9509
+ init_common3();
9389
9510
  STATUSES2 = ["open", "dismissed", "merged"];
9390
9511
  command4 = {
9391
9512
  resource: "accounts",
@@ -9459,8 +9580,8 @@ var init_merges = __esm({
9459
9580
  init_errors();
9460
9581
  init_exit_codes();
9461
9582
  init_http();
9462
- init_common();
9463
9583
  init_common2();
9584
+ init_common3();
9464
9585
  MERGED_BY = ["user", "agent", "api_key", "workflow", "system"];
9465
9586
  command5 = {
9466
9587
  resource: "accounts",
@@ -9733,7 +9854,7 @@ var init_client = __esm({
9733
9854
  var agents_default;
9734
9855
  var init_agents = __esm({
9735
9856
  "docs/agents.md"() {
9736
- agents_default = '# Coding agents\n\nThe CLI is built to be driven by a coding agent: Claude Code, Codex, Cursor, Gemini CLI or anything else that runs shell commands. An agent learns it from the Agent Skill, `kenso --help` and `kenso describe`, and never needs these web pages.\n\n## Set up an agent in three steps\n\n1. Install the CLI where the agent runs: on macOS or Linux, the [install script](https://ken.so/install.sh) piped to `sh` needs no Node; anywhere, `npm i -g kenso` needs Node 22 or newer. Without a global install, `npx -y kenso@latest <command>` runs any command.\n2. Give it a key. Either set `KENSO_API_KEY` (and `KENSO_WORKSPACE_ID` when the key reaches several workspaces) in the agent\'s environment, or log in once on that machine:\n\n```bash\nkenso auth login\nkenso workspace use 1234\n```\n\n3. Install the Agent Skill and connect the Kenso MCP server in one step, then check everything:\n\n```bash\nkenso agent setup\nkenso agent setup -y\nkenso doctor\n```\n\nTo hand the whole setup to an agent, give it [ken.so/get-started.md](https://ken.so/get-started.md): it runs these steps and stops only where a person has to act.\n\n## kenso agent setup\n\n`kenso agent setup` installs the `kenso` and `kenso-cli` skills (as `kenso skill install` does) and registers the Kenso MCP server, `https://mcp.ken.so/mcp`, with each coding agent:\n\n| Agent | `--client` | MCP server added with |\n|---|---|---|\n| Claude Code | `claude-code` | `claude mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| Codex | `codex` | `codex mcp add kenso --url https://mcp.ken.so/mcp` |\n| Cursor | `cursor` | a `kenso` entry in `~/.cursor/mcp.json` |\n| Gemini CLI | `gemini` | `gemini mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| OpenCode | `opencode` | a `kenso` entry in `~/.config/opencode/opencode.json` |\n\n```bash\nkenso agent setup --client claude-code -y\nkenso agent setup --client all -y\nkenso agent setup --status --json\n```\n\n- Without `--client`, it sets up the agent that runs it, else every agent found on the machine (its command on `PATH` or its config folder present).\n- Without `-y` it prints the plan and changes nothing; the plan\'s `next` applies it. `--status` reports, for every agent, the state of each bundled skill (`missing`, `current`, `stale` from an older kenso, or `edited` by hand) and whether the MCP server is `registered`, `missing`, in `conflict` or `unknown` (a config file it cannot read as JSON), and changes nothing. `--json` prints JSON on a terminal too.\n- An MCP entry with the Kenso URL under another name (such as `ken-ai` from the plugin) counts as registered, and nothing is added. A `kenso` entry pointing at another URL is left alone (`conflict`). A config file that is not plain JSON (it has comments) is left alone (`skipped`), and so is an agent whose command is not on `PATH`: their `next` is the command or edit to make by hand.\n- A missing `SKILL.md` and one an older kenso wrote are written. One edited by hand is left alone (`"status":"edited"`, with a stderr line naming `--force`) while the rest of the setup runs; `--force` replaces it. After a successful run, four requests to start with follow on stderr.\n- It exits 1 when any agent was not fully set up. The MCP server signs in with your Kenso account in the browser the first time the agent uses it; each agent\'s `next` says how (in Claude Code, `/mcp`).\n\n## An AGENTS.md section for your repo\n\nPaste this into the `AGENTS.md` (or `CLAUDE.md`) of a repo whose agents work in Kenso:\n\n```markdown\n## Kenso\n\n- Kenso is our outbound platform. One record or a question: use the Kenso MCP server (https://mcp.ken.so/mcp). A file or more than about 50 records: use the `kenso` CLI.\n- Setup: `npm i -g kenso`, `kenso auth login` (a person approves in the browser), `kenso agent setup -y`, `kenso doctor`.\n- Every write runs first with `--dry-run`; apply with the plan\'s `next`. Never put an API key in a flag, a file or the chat: use `KENSO_API_KEY`.\n- Code that calls the API: send `Authorization: Bearer $KENSO_API_KEY`, `Ken-Version` and `X-Ken-Workspace-Id`. Reference: ken.so/docs.md; the kenso-api skill is listed at ken.so/.well-known/skills/index.json.\n```\n\n## The Agent Skills\n\n`kenso skill install` writes the two skills bundled with this CLI, each one `SKILL.md` in a folder named like the skill, where each agent looks for skills:\n\n- `kenso`, the entry skill: it sends the agent to the Kenso skill for the job and sets the rules for the workspace, credits, sends and the final reply. Agents load it first; every help under an agent starts with `Agents: load the kenso skill first: kenso skill show kenso`.\n- `kenso-cli`: the CLI\'s commands for work from a file or over about 50 records.\n\n| Agent | `--client` | Folders |\n|---|---|---|\n| Claude Code | `claude-code` | `~/.claude/skills/kenso/`, `~/.claude/skills/kenso-cli/` |\n| Codex | `codex` | `~/.agents/skills/kenso/`, `~/.agents/skills/kenso-cli/` |\n| Cursor | `cursor` | `~/.cursor/skills/kenso/`, `~/.cursor/skills/kenso-cli/` |\n| Gemini CLI | `gemini` | `~/.gemini/skills/kenso/`, `~/.gemini/skills/kenso-cli/` |\n| OpenCode | `opencode` | `~/.config/opencode/skills/kenso/`, `~/.config/opencode/skills/kenso-cli/` |\n\nClaude Code\'s folders follow `CLAUDE_CONFIG_DIR` when that is set. Without `--client`, it installs for the agent that runs it when that is Claude Code, Codex or Cursor (detected from the environment, see below), else for all five. It prints what it wrote:\n\n```json\n{"installed":[{"client":"claude-code","path":"/home/you/.claude/skills/kenso-cli/SKILL.md","status":"created"},{"client":"claude-code","path":"/home/you/.claude/skills/kenso/SKILL.md","status":"created"}]}\n```\n\n```bash\nkenso skill install --client claude-code\nkenso skill install --client all\nkenso skill install --skill kenso\nkenso skill install --dir .claude/skills/kenso-cli\nkenso skill install --force\n```\n\n- `--skill <name>` installs one of the two. `--dir` writes one skill into that folder instead (`--skill`, else `kenso-cli`), for example a project\'s own skills folder. Name the folder like the skill, as agents expect.\n- A missing file is written (`"status":"created"`) and one an older kenso wrote is replaced (`"status":"updated"`); the same file is left as it is (`"status":"unchanged"`). A `SKILL.md` edited by hand is left alone (`"status":"edited"`) with a stderr line that names `--force`, and the command still exits 0. `--force` replaces it (`"status":"replaced"`).\n- `--dry-run` writes nothing and exits 0. It prints each target\'s status and a `next` that applies it.\n- Under a detected agent, when a bundled skill in that agent\'s folder is from an older kenso, a command ends with one stderr line, once per agent session: `The installed <name> skill is from an older kenso: kenso skill install`. It reads the files only, and nothing is replaced until you run `kenso skill install` or `kenso agent setup`. `KENSO_NO_SKILL_NOTICE=1` turns it off.\n- Cursor also reads `~/.claude/skills/` and `~/.agents/skills/` (Gemini CLI and OpenCode read `~/.agents/skills/` too), so after a default install for all of them an agent may list each Kenso skill more than once. To avoid that, install with `--client cursor` only, or remove the copies you do not need.\n\nBoth skills also ship in the Kenso plugin for Claude Code (`Ken-Technology/ken-ai-plugin`), so `npx skills add Ken-Technology/ken-ai-plugin` installs them along with the MCP skills; the plugin\'s copies are these files byte for byte. The other Kenso skills come from the MCP: list them, and read any of them without installing it:\n\n```bash\nkenso skill list\nkenso skill show kenso\nkenso skill show workflows --reference files.md\n```\n\n`kenso skill show` prints `kenso` and `kenso-cli` from the CLI itself, with no network and no sign-in. Any other skill is read from the Kenso MCP with your key.\n\n## Rules the skill teaches\n\n- **Data is on stdout, as JSON when piped.** Progress, warnings and errors are on stderr. Parse stdout; read stderr when the exit code is not 0.\n- **Plan, then apply.** Run a write with `--dry-run`, read the plan, then run the exact command in its `next` (the same command with `--yes`). A command with no dry run refuses `--dry-run` with `usage_error` and does nothing.\n- **Pass files, not rows.** Never paste a CSV into the conversation. Write the file, pass its path with `--file`, and read the summary.\n- **Read failures only.** If the summary\'s `failed`, `notFound` and `invalid` are 0, the work is done. Otherwise read just the problem rows from `results.csv` or `invalid.csv`.\n- **Follow `next`.** Every error with a known fix carries the exact command to run.\n- **Branch on the exit code:** 0 ok, 2 fix the command, 3 fix the key, 5 some rows failed, 6 wait or raise a limit, 130 resume.\n- **Look things up, do not guess.** `kenso describe <resource> <action>` prints any command\'s flags and body schema as JSON.\n- **Find, then look up.** `kenso discover` turns a plain request into the command, doc, skill or workflow step for it, offline, with the next command to run.\n- **See the cost first.** Every dry run of paid work prints `credits` with `needed`, `available` and `sufficient`. `kenso credits` reads the balance, usage and prices.\n\n## What a command does and what it costs\n\nEvery command declares its effect. Help and `kenso describe` print it, so an agent can tell a look from a change before it runs anything:\n\n| Effect | Meaning |\n|---|---|\n| `read` | Changes nothing and charges nothing |\n| `write` | Creates or changes workspace data. Charges nothing the API contract declares. Nothing leaves Kenso |\n| `spend` | Can charge credits under at least one of its flags |\n| `send` | Sends an email, a LinkedIn message, a call or an invitation, or starts or resumes sending |\n| `destructive` | Deletes, archives, removes or merges |\n\nA `write` is not proof that a command is free: the API contract does not mark every route that charges. The dry run\'s `credits` and estimate are the authority on what a command costs.\n\n- Command help prints `Effect: <effect>.` under the summary. A command that charges adds a `Cost:` line in credits, priced from your workspace\'s rate card; signed out or offline it shows both rate cards, labelled `rate card v1` and `rate card v2`. Work your plan bills another way reads `not charged in credits`. No price is typed into the CLI: it comes from the rate card or a dry run\'s estimate.\n- A command that spends, sends or deletes, and each command an agent starts with (`kenso doctor`, `kenso describe`, `kenso docs`, `kenso agent setup`, `kenso skill install`, `kenso auth login`), also prints `When:` (when to pick it) and `Next:` (what to run after it) under its description.\n- A command that only reads says `Read-only.` under its global flags line.\n- `kenso describe <resource> <action>` has the same `effect` and `cost` as JSON.\n- `kenso api`, `kenso mcp call` and `kenso runs resume` read `destructive`, because one call of theirs can do anything. Read-only mode judges each call on its own.\n\n```bash\nkenso describe email-finds create\nkenso email-finds create --help\n```\n\n### Read-only mode\n\nSet `KENSO_READ_ONLY=1`, or pass `--read-only`, while an agent looks into something: every command whose effect is not `read` is refused before it sends a request, with exit 2 and the code `read_only` (see [Output and errors](output-and-errors.md)). A POST that only reads still runs, and a GET that charges is refused. A dry run still prints its plan; the dry run of `bulk-update` and `bulk-delete` asks Kenso for a preview, which Kenso stores. `kenso api` has the effect of the route it calls, and on a route this CLI does not know only a `GET` runs. `kenso mcp call` runs `list_skills` and `load_skill` only.\n\n```bash\nKENSO_READ_ONLY=1 kenso contacts search --limit 1\nkenso --read-only describe email-finds create\n```\n\n## Find a command: kenso discover\n\n`kenso discover` searches every command, doc topic, skill and workflow step type this release has, with no network and no key. Each argument is one query: plain words, or `"<what you have> -> <what you need>"`.\n\n```bash\nkenso discover "linkedin url -> email"\nkenso discover "pause a campaign" "export leads" --kind command --limit 3\nkenso describe email-finds create\n```\n\nIt prints one object per query, `{"query", "hits", "more"}` (NDJSON when piped). Each hit has its `kind`, `id`, `summary`, `effect` (`read`, `write`, `spend`, `send` or `destructive`), `cost` (in credits, from your saved or the bundled rate card, or `null`) and `describe`, the exact command to run next. `--limit` is 5 by default and at most 10. A query with no hit prints an empty `hits` and exits 0. The index is built when the CLI is released, so a skill added since then shows up in the next release.\n\n## Credits\n\nPrices are in credits only, from your workspace\'s own rate card. A skill or a doc never states a price: ask the CLI.\n\n```bash\nkenso credits balance\nkenso credits rate-card --action email_found\nkenso credits quote --kind leads --count 200\nkenso credits usage --since 7d\nkenso credits usage --run <runId>\n```\n\n- `balance`: credits `available`, and where they come from.\n- `rate-card`: what each action costs on your card. Offline it prints the card saved in the last day, else the two bundled cards, labelled.\n- `quote`: an estimate before you run anything, as `credits` with `needed`, `available` and `sufficient`. `--kind` is `campaign`, `build`, `infra`, `accounts`, `leads` or `places`; `--workflow <id or file> --records <n>` prices a workflow run.\n- `usage`: the ledger, filtered by `--run`, `--workflow`, `--campaign`, `--action`, `--since` and `--until`, with the total on stderr. With no filter, this billing month\'s spend by category.\n- `limit` (beta) shows the workflow spend limits, and `savings` the work Kenso did without taking credits.\n\n## The token-saving pattern\n\nAdding 5,000 leads through the MCP sends every lead through the model, hundreds of thousands of tokens. Through the CLI it is two commands and two short JSON objects:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThen, only if the summary shows failures:\n\n```bash\ngrep -E \'^[0-9]+,(failed|not_found|invalid),\' ~/.kenso/runs/r_tdi5cdnx/results.csv | head -50\n```\n\n## Environment variables\n\n| Variable | What it does |\n|---|---|\n| `KENSO_API_KEY` | The API key. Wins over any saved profile |\n| `KENSO_WORKSPACE_ID` | The workspace for every command. `--workspace` wins over it |\n| `KENSO_PROFILE` | The saved profile to use. `--profile` wins over it |\n| `KENSO_API_URL` | The API, default `https://api.ken.so` |\n| `KENSO_CONFIG_DIR` | Where the config file and cache live, default `~/.kenso` |\n| `KENSO_RUNS_DIR` | Where run folders live, default `<config dir>/runs` |\n| `KENSO_MCP_URL` | The MCP for `kenso mcp`, default `https://mcp.ken.so/mcp` |\n| `KENSO_READ_ONLY` | Set to `1` to refuse every command that is not a read, as `--read-only` does. Any value except empty, `0` or `false` turns it on |\n| `KENSO_AGENT_SESSION` | The agent session id: the full agent help, the update notice and the stale-skill notice each print once per session |\n| `KENSO_NO_UPDATE_NOTIFIER` | Set to `1` to turn off the "a newer kenso is out" line on stderr. A person at a terminal gets it after the weekly check; under a detected agent it comes from the last check, once per agent session, with no request. Never in CI |\n| `KENSO_NO_SKILL_NOTICE` | Set to `1` to turn off the line that says an installed skill is from an older kenso |\n\n## Cloud sandboxes\n\nCloud agents (Claude Code on the web, Codex cloud, Cursor background agents and similar) often run with a network allowlist. Allow:\n\n- `api.ken.so`: every command\n- `mcp.ken.so`: only `kenso mcp tools` and `kenso mcp call`\n- `registry.npmjs.org`: to install the CLI with npm\n\nStore the key as the platform\'s secret and expose it as `KENSO_API_KEY`. Run `kenso doctor` as the first command: it checks Node, the config, that the API is reachable, that the key works, and that the skills and the Kenso MCP server are set up for the agent. It exits 0 when the first four checks pass (the skill and MCP checks never change the exit code), and its `next` names the command to run.\n\n```bash\nkenso doctor\n```\n\nPoint the run folders at the workspace if the home folder does not persist between sessions: `KENSO_RUNS_DIR=./.kenso-runs`. Keep that folder out of git.\n\n## How Kenso knows an agent ran a command\n\nThe CLI checks these environment variables, in this order: `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` (Claude Code), `CODEX_SANDBOX` and `CODEX_THREAD_ID` (Codex), `CURSOR_AGENT` (Cursor), `GEMINI_CLI` (Gemini CLI), `OPENCODE` (OpenCode), then `AI_AGENT`, a free-form name any other agent can set. When one is set:\n\n- every request carries `X-Ken-Client: Kenso CLI via <agent>`, and writes carry `X-Ken-Actor: agent`, so Kenso shows the change as made by you through that agent;\n- help starts with `Agents: load the kenso skill first: kenso skill show kenso`;\n- the first help an agent reads in a session ends with the "For agents" block. After that the block is one line, `Agent rules: kenso --help --verbose (dry-run first, one command per file, next is the next command).`, and `kenso --help --verbose` always prints it in full;\n- browser login never opens a browser itself: it prints the link for you to open.\n\nA session is `KENSO_AGENT_SESSION` when that is set, else `CODEX_THREAD_ID`, else `CLAUDE_CODE_SESSION_ID`, else the agent\'s name and the current two-hour block of the day (UTC), so an agent that sets none of them reads the whole block again every two hours. The CLI keeps what it has shown in `session-seen.json` in the config folder (mode 0600) and forgets an entry after 7 days.\n\n`kenso doctor` shows the agent it detected.\n\n## MCP-only tools\n\nA few Kenso MCP tools have no API route, such as the skills Kenso\'s own agents use. Reach them from the shell with the same key:\n\n```bash\nkenso mcp tools\nkenso mcp call list_skills\nkenso mcp call load_skill --args \'{"name":"create-campaign"}\'\nkenso mcp call contacts_read --operation list --args \'{"limit":5}\'\n```\n\n`mcp call` prints the tool\'s structured result, else its text parsed as JSON, else the text. A tool error exits 1 with `mcp_tool_error`.\n';
9857
+ agents_default = '# Coding agents\n\nThe CLI is built to be driven by a coding agent: Claude Code, Codex, Cursor, Gemini CLI or anything else that runs shell commands. An agent learns it from the Agent Skill, `kenso --help` and `kenso describe`, and never needs these web pages.\n\n## Set up an agent in three steps\n\n1. Install the CLI where the agent runs: on macOS or Linux, the [install script](https://ken.so/install.sh) piped to `sh` needs no Node; anywhere, `npm i -g kenso` needs Node 22 or newer. Without a global install, `npx -y kenso@latest <command>` runs any command.\n2. Give it a key. Either set `KENSO_API_KEY` (and `KENSO_WORKSPACE_ID` when the key reaches several workspaces) in the agent\'s environment, or log in once on that machine:\n\n```bash\nkenso auth login\nkenso workspace use 1234\n```\n\n An agent with no key hands the login to you: `kenso login --no-wait` prints a link and a code without waiting, you open the link and approve, then the agent runs `kenso auth wait` to save the key. Under an agent, `kenso doctor` names `kenso login --no-wait` as the key check\'s `next`.\n\n3. Install the Agent Skill and connect the Kenso MCP server in one step, then check everything:\n\n```bash\nkenso agent setup\nkenso agent setup -y\nkenso doctor\n```\n\nTo hand the whole setup to an agent, give it [ken.so/get-started.md](https://ken.so/get-started.md): it runs these steps and stops only where a person has to act.\n\n## kenso agent setup\n\n`kenso agent setup` installs the `kenso` and `kenso-cli` skills (as `kenso skill install` does) and registers the Kenso MCP server, `https://mcp.ken.so/mcp`, with each coding agent:\n\n| Agent | `--client` | MCP server added with |\n|---|---|---|\n| Claude Code | `claude-code` | `claude mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| Codex | `codex` | `codex mcp add kenso --url https://mcp.ken.so/mcp` |\n| Cursor | `cursor` | a `kenso` entry in `~/.cursor/mcp.json` |\n| Gemini CLI | `gemini` | `gemini mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| OpenCode | `opencode` | a `kenso` entry in `~/.config/opencode/opencode.json` |\n\n```bash\nkenso agent setup --client claude-code -y\nkenso agent setup --client all -y\nkenso agent setup --status --json\n```\n\n- Without `--client`, it sets up the agent that runs it, else every agent found on the machine (its command on `PATH` or its config folder present).\n- Without `-y` it prints the plan and changes nothing; the plan\'s `next` applies it. `--status` reports, for every agent, the state of each bundled skill (`missing`, `current`, `stale` from an older kenso, or `edited` by hand) and whether the MCP server is `registered`, `missing`, in `conflict` or `unknown` (a config file it cannot read as JSON), and changes nothing. `--json` prints JSON on a terminal too.\n- An MCP entry with the Kenso URL under another name (such as `ken-ai` from the plugin) counts as registered, and nothing is added. A `kenso` entry pointing at another URL is left alone (`conflict`). A config file that is not plain JSON (it has comments) is left alone (`skipped`), and so is an agent whose command is not on `PATH`: their `next` is the command or edit to make by hand.\n- A missing `SKILL.md` and one an older kenso wrote are written. One edited by hand is left alone (`"status":"edited"`, with a stderr line naming `--force`) while the rest of the setup runs; `--force` replaces it. After a successful run, four requests to start with follow on stderr.\n- It exits 1 when any agent was not fully set up. The MCP server signs in with your Kenso account in the browser the first time the agent uses it; each agent\'s `next` says how (in Claude Code, `/mcp`).\n\n## An AGENTS.md section for your repo\n\nPaste this into the `AGENTS.md` (or `CLAUDE.md`) of a repo whose agents work in Kenso:\n\n```markdown\n## Kenso\n\n- Kenso is our outbound platform. One record or a question: use the Kenso MCP server (https://mcp.ken.so/mcp). A file or more than about 50 records: use the `kenso` CLI.\n- Setup: `npm i -g kenso`, `kenso auth login` (a person approves in the browser), `kenso agent setup -y`, `kenso doctor`.\n- Every write runs first with `--dry-run`; apply with the plan\'s `next`. Never put an API key in a flag, a file or the chat: use `KENSO_API_KEY`.\n- Code that calls the API: send `Authorization: Bearer $KENSO_API_KEY`, `Ken-Version` and `X-Ken-Workspace-Id`. Reference: ken.so/docs.md; the kenso-api skill is listed at ken.so/.well-known/skills/index.json.\n```\n\n## The Agent Skills\n\n`kenso skill install` writes the two skills bundled with this CLI, each one `SKILL.md` in a folder named like the skill, where each agent looks for skills:\n\n- `kenso`, the entry skill: it sends the agent to the Kenso skill for the job and sets the rules for the workspace, credits, sends and the final reply. Agents load it first; every help under an agent starts with `Agents: load the kenso skill first: kenso skill show kenso`.\n- `kenso-cli`: the CLI\'s commands for work from a file or over about 50 records.\n\n| Agent | `--client` | Folders |\n|---|---|---|\n| Claude Code | `claude-code` | `~/.claude/skills/kenso/`, `~/.claude/skills/kenso-cli/` |\n| Codex | `codex` | `~/.agents/skills/kenso/`, `~/.agents/skills/kenso-cli/` |\n| Cursor | `cursor` | `~/.cursor/skills/kenso/`, `~/.cursor/skills/kenso-cli/` |\n| Gemini CLI | `gemini` | `~/.gemini/skills/kenso/`, `~/.gemini/skills/kenso-cli/` |\n| OpenCode | `opencode` | `~/.config/opencode/skills/kenso/`, `~/.config/opencode/skills/kenso-cli/` |\n\nClaude Code\'s folders follow `CLAUDE_CONFIG_DIR` when that is set. Without `--client`, it installs for the agent that runs it when that is Claude Code, Codex or Cursor (detected from the environment, see below), else for all five. It prints what it wrote:\n\n```json\n{"installed":[{"client":"claude-code","path":"/home/you/.claude/skills/kenso-cli/SKILL.md","status":"created"},{"client":"claude-code","path":"/home/you/.claude/skills/kenso/SKILL.md","status":"created"}]}\n```\n\n```bash\nkenso skill install --client claude-code\nkenso skill install --client all\nkenso skill install --skill kenso\nkenso skill install --dir .claude/skills/kenso-cli\nkenso skill install --force\n```\n\n- `--skill <name>` installs one of the two. `--dir` writes one skill into that folder instead (`--skill`, else `kenso-cli`), for example a project\'s own skills folder. Name the folder like the skill, as agents expect.\n- A missing file is written (`"status":"created"`) and one an older kenso wrote is replaced (`"status":"updated"`); the same file is left as it is (`"status":"unchanged"`). A `SKILL.md` edited by hand is left alone (`"status":"edited"`) with a stderr line that names `--force`, and the command still exits 0. `--force` replaces it (`"status":"replaced"`).\n- `--dry-run` writes nothing and exits 0. It prints each target\'s status and a `next` that applies it.\n- Under a detected agent, when a bundled skill in that agent\'s folder is from an older kenso, a command ends with one stderr line, once per agent session: `The installed <name> skill is from an older kenso: kenso skill install`. It reads the files only, and nothing is replaced until you run `kenso skill install` or `kenso agent setup`. `KENSO_NO_SKILL_NOTICE=1` turns it off.\n- Cursor also reads `~/.claude/skills/` and `~/.agents/skills/` (Gemini CLI and OpenCode read `~/.agents/skills/` too), so after a default install for all of them an agent may list each Kenso skill more than once. To avoid that, install with `--client cursor` only, or remove the copies you do not need.\n\nBoth skills also ship in the Kenso plugin for Claude Code (`Ken-Technology/ken-ai-plugin`), so `npx skills add Ken-Technology/ken-ai-plugin` installs them along with the MCP skills; the plugin\'s copies are these files byte for byte. The other Kenso skills come from the MCP: list them, and read any of them without installing it:\n\n```bash\nkenso skill list\nkenso skill show kenso\nkenso skill show workflows --reference files.md\n```\n\n`kenso skill show` prints `kenso` and `kenso-cli` from the CLI itself, with no network and no sign-in. Any other skill is read from the Kenso MCP with your key.\n\n## Rules the skill teaches\n\n- **Data is on stdout, as JSON when piped.** Progress, warnings and errors are on stderr. Parse stdout; read stderr when the exit code is not 0.\n- **Plan, then apply.** Run a write with `--dry-run`, read the plan, then run the exact command in its `next` (the same command with `--yes`). A command with no dry run refuses `--dry-run` with `usage_error` and does nothing.\n- **Pass files, not rows.** Never paste a CSV into the conversation. Write the file, pass its path with `--file`, and read the summary.\n- **Read failures only.** If the summary\'s `failed`, `notFound` and `invalid` are 0, the work is done. Otherwise read just the problem rows from `results.csv` or `invalid.csv`.\n- **Follow `next`.** Every error with a known fix carries the exact command to run.\n- **Branch on the exit code:** 0 ok, 2 fix the command, 3 fix the key, 5 some rows failed, 6 wait or raise a limit, 130 resume.\n- **Look things up, do not guess.** `kenso describe <resource> <action>` prints any command\'s flags and body schema as JSON.\n- **Find, then look up.** `kenso discover` turns a plain request into the command, doc, skill or workflow step for it, offline, with the next command to run.\n- **See the cost first.** The dry run of every `spend` command, one call or an `--each` file, and of `kenso workflows run` prints `credits` with `needed`, `available` and `sufficient`, each `null` when the CLI cannot read or price it. A generated command has a `needed` only where one call charges one unit (an email find, a place opened): its rate-card price times the calls. Every other generated spend prints `needed: null`, because the API decides how many units one call charges (an AI run charges each contact of the campaign). `null` is unknown, never free. A dry run without a key still prints its plan, with `available: null`. `kenso credits` reads the balance, usage and prices.\n\n## What a command does and what it costs\n\nEvery command declares its effect. Help and `kenso describe` print it, so an agent can tell a look from a change before it runs anything:\n\n| Effect | Meaning |\n|---|---|\n| `read` | Changes nothing and charges nothing |\n| `write` | Creates or changes workspace data. Charges nothing the API contract declares. Nothing leaves Kenso |\n| `spend` | Can charge credits under at least one of its flags |\n| `send` | Sends an email, a LinkedIn message, a call or an invitation, or starts or resumes sending |\n| `destructive` | Deletes, archives, removes or merges |\n\nA `write` or a `send` is not proof that a command is free: the API contract does not mark every route that charges, and `kenso workflows run` is a `send` that charges for the workflow\'s steps. The dry run\'s `credits` and estimate are the authority on what a command costs.\n\n- Command help prints `Effect: <effect>.` under the summary. A command that charges adds a `Cost:` line in credits, priced from your workspace\'s rate card; signed out or offline it shows both rate cards, labelled `rate card v1` and `rate card v2`. Work your plan bills another way reads `not charged in credits`. No price is typed into the CLI: it comes from the rate card or a dry run\'s estimate.\n- A command that spends, sends or deletes, and each command an agent starts with (`kenso doctor`, `kenso describe`, `kenso docs`, `kenso agent setup`, `kenso skill install`, `kenso auth login`), also prints `When:` (when to pick it) and `Next:` (what to run after it) under its description.\n- A command that only reads says `Read-only.` under its global flags line.\n- `kenso describe <resource> <action>` has the same `effect` and `cost` as JSON. `cost` is `null` only for a command that declares no charge; a hand-written command that says what it charges has it as `cost.text`, whatever its effect.\n- `kenso api`, `kenso mcp call` and `kenso runs resume` read `destructive`, because one call of theirs can do anything. Read-only mode judges each call on its own.\n\n```bash\nkenso describe email-finds create\nkenso email-finds create --help\n```\n\n### Read-only mode\n\nSet `KENSO_READ_ONLY=1`, or pass `--read-only`, while an agent looks into something: every command whose effect is not `read` is refused before it sends a request, with exit 2 and the code `read_only` (see [Output and errors](output-and-errors.md)). A POST that only reads still runs, and a GET that charges is refused. A dry run still prints its plan; the dry run of `bulk-update` and `bulk-delete` asks Kenso for a preview, which Kenso stores. `kenso api` has the effect of the route it calls, and on a route this CLI does not know only a `GET` runs. `kenso mcp call` runs `list_skills` and `load_skill` only.\n\n```bash\nKENSO_READ_ONLY=1 kenso contacts search --limit 1\nkenso --read-only describe email-finds create\n```\n\n## Find a command: kenso discover\n\n`kenso discover` searches every command, doc topic, skill and workflow step type this release has, with no network and no key. Each argument is one query: plain words, or `"<what you have> -> <what you need>"`.\n\n```bash\nkenso discover "linkedin url -> email"\nkenso discover "pause a campaign" "export leads" --kind command --limit 3\nkenso describe email-finds create\n```\n\nIt prints one object per query, `{"query", "hits", "more"}` (NDJSON when piped). Each hit has its `kind`, `id`, `summary`, `effect` (`read`, `write`, `spend`, `send` or `destructive`), `cost` (in credits, from your saved or the bundled rate card, or `null`) and `describe`, the exact command to run next. `--limit` is 5 by default and at most 10. A query with no hit prints an empty `hits` and exits 0. The index is built when the CLI is released, so a skill added since then shows up in the next release.\n\n## Credits\n\nPrices are in credits only, from your workspace\'s own rate card. A skill or a doc never states a price: ask the CLI.\n\n```bash\nkenso credits balance\nkenso credits rate-card --action email_found\nkenso credits quote --kind leads --count 200\nkenso credits usage --since 7d\nkenso credits usage --run <runId>\n```\n\n- `balance`: credits `available`, and where they come from.\n- `rate-card`: what each action costs on your card. Offline it prints the card saved in the last day, else the two bundled cards, labelled.\n- `quote`: an estimate before you run anything, as `credits` with `needed`, `available` and `sufficient`. `--kind` is `campaign`, `build`, `infra`, `accounts`, `leads` or `places`; `--workflow <id or file> --records <n>` prices a workflow run.\n- `usage`: the ledger, filtered by `--run`, `--workflow`, `--campaign`, `--action`, `--since` and `--until`, with the total on stderr. With no filter, this billing month\'s spend by category.\n- `limit` (beta) shows the workflow spend limits, and `savings` the work Kenso did without taking credits.\n\n## The token-saving pattern\n\nAdding 5,000 leads through the MCP sends every lead through the model, hundreds of thousands of tokens. Through the CLI it is two commands and two short JSON objects:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThen, only if the summary shows failures:\n\n```bash\ngrep -E \'^[0-9]+,(failed|not_found|invalid),\' ~/.kenso/runs/r_tdi5cdnx/results.csv | head -50\n```\n\n## Environment variables\n\n| Variable | What it does |\n|---|---|\n| `KENSO_API_KEY` | The API key. Wins over any saved profile |\n| `KENSO_WORKSPACE_ID` | The workspace for every command. `--workspace` wins over it |\n| `KENSO_PROFILE` | The saved profile to use. `--profile` wins over it |\n| `KENSO_API_URL` | The API, default `https://api.ken.so` |\n| `KENSO_CONFIG_DIR` | Where the config file and cache live, default `~/.kenso` |\n| `KENSO_RUNS_DIR` | Where run folders live, default `<config dir>/runs` |\n| `KENSO_MCP_URL` | The MCP for `kenso mcp`, default `https://mcp.ken.so/mcp` |\n| `KENSO_READ_ONLY` | Set to `1` to refuse every command that is not a read, as `--read-only` does. Any value except empty, `0` or `false` turns it on |\n| `KENSO_AGENT_SESSION` | The agent session id: the full agent help, the update notice and the stale-skill notice each print once per session |\n| `KENSO_NO_UPDATE_NOTIFIER` | Set to `1` to turn off the "a newer kenso is out" line on stderr. A person at a terminal gets it after the weekly check; under a detected agent it comes from the last check, once per agent session, with no request. Never in CI |\n| `KENSO_NO_SKILL_NOTICE` | Set to `1` to turn off the line that says an installed skill is from an older kenso |\n\n## Cloud sandboxes\n\nCloud agents (Claude Code on the web, Codex cloud, Cursor background agents and similar) often run with a network allowlist. Allow:\n\n- `api.ken.so`: every command\n- `mcp.ken.so`: only `kenso mcp tools` and `kenso mcp call`\n- `registry.npmjs.org`: to install the CLI with npm\n\nStore the key as the platform\'s secret and expose it as `KENSO_API_KEY`. Run `kenso doctor` as the first command: it checks Node, the config, that the API is reachable, that the key works, and that the skills and the Kenso MCP server are set up for the agent. It exits 0 when the first four checks pass (the skill and MCP checks never change the exit code), and its `next` names the command to run.\n\n```bash\nkenso doctor\n```\n\nPoint the run folders at the workspace if the home folder does not persist between sessions: `KENSO_RUNS_DIR=./.kenso-runs`. Keep that folder out of git.\n\n## How Kenso knows an agent ran a command\n\nThe CLI checks these environment variables, in this order: `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` (Claude Code), `CODEX_SANDBOX` and `CODEX_THREAD_ID` (Codex), `CURSOR_AGENT` (Cursor), `GEMINI_CLI` (Gemini CLI), `OPENCODE` (OpenCode), then `AI_AGENT`, a free-form name any other agent can set. When one is set:\n\n- every request carries `X-Ken-Client: Kenso CLI via <agent>`, and writes carry `X-Ken-Actor: agent`, so Kenso shows the change as made by you through that agent;\n- help starts with `Agents: load the kenso skill first: kenso skill show kenso`;\n- the first help an agent reads in a session ends with the "For agents" block. After that the block is one line, `Agent rules: kenso --help --verbose (dry-run first, one command per file, next is the next command).`, and `kenso --help --verbose` always prints it in full;\n- browser login never opens a browser itself: it prints the link for you to open.\n\nA session is `KENSO_AGENT_SESSION` when that is set, else `CODEX_THREAD_ID`, else `CLAUDE_CODE_SESSION_ID`, else the agent\'s name and the current two-hour block of the day (UTC), so an agent that sets none of them reads the whole block again every two hours. The CLI keeps what it has shown in `session-seen.json` in the config folder (mode 0600) and forgets an entry after 7 days.\n\n`kenso doctor` shows the agent it detected.\n\n## MCP-only tools\n\nA few Kenso MCP tools have no API route, such as the skills Kenso\'s own agents use. Reach them from the shell with the same key:\n\n```bash\nkenso mcp tools\nkenso mcp call list_skills\nkenso mcp call load_skill --args \'{"name":"create-campaign"}\'\nkenso mcp call contacts_read --operation list --args \'{"limit":5}\'\n```\n\n`mcp call` prints the tool\'s structured result, else its text parsed as JSON, else the text. A tool error exits 1 with `mcp_tool_error`.\n';
9737
9858
  }
9738
9859
  });
9739
9860
 
@@ -9741,7 +9862,7 @@ var init_agents = __esm({
9741
9862
  var auth_default;
9742
9863
  var init_auth = __esm({
9743
9864
  "docs/auth.md"() {
9744
- auth_default = '# Authentication\n\nThe CLI calls the Kenso API with a Kenso API key (`kenso_live_` plus 49 characters, or an older key: `ken_` plus 43 characters). It sends the key as `Authorization: Bearer <key>` and never prints it, logs it or puts it in an error.\n\n`kenso login`, `kenso logout` and `kenso whoami` are the same commands as `kenso auth login`, `kenso auth logout` and `kenso auth status`.\n\n## Log in with an API key\n\n1. In app.ken.so, go to Settings > Integrations > API keys and create a key.\n2. Pipe it to `kenso auth login --with-key`. The key is read from stdin, never from a flag, so it stays out of your shell history and process list.\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso auth login --with-key --profile client-a --workspace 1234 < key.txt\n```\n\nThe CLI checks the key with `GET /v1/me`, then saves it to `~/.kenso/config.json` (file mode 0600, folder mode 0700). It prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","workspaceCount":1}\n```\n\nA developer sandbox does not count here unless every workspace is one: a key whose user has one workspace and a sandbox saves that workspace. When the key reaches several workspaces and you did not pass `--workspace`, no workspace is saved and the output carries `"next":"kenso workspace list --search <name>"`. A key in the wrong format exits 2 (`invalid_key_format`). A key Kenso rejects exits 3.\n\n## Browser login\n\n```bash\nkenso auth login\nkenso auth login --no-browser --device-name "build box"\n```\n\nBrowser login is available to every workspace. The CLI prints a link and a code on stderr. You open the link, sign in to app.ken.so, check that the code matches the one in your terminal, pick the workspace to start in and approve. The CLI then saves a new API key to the profile and prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","keyExpiresAt":"2027-02-02T06:26:59Z"}\n```\n\nThe key is the same kind you create in the app. It is named `Kenso CLI - <device name>` (`--device-name`, else `kenso-cli on <hostname>`), lasts 90 days, and shows in your API key list at Settings > Integrations > API keys, where you can revoke it. The CLI opens the browser itself only when no coding agent is detected and the machine has a display. An agent prints the link and asks you to open it. The login expires after 10 minutes (`login_expired`, exit 3), and a denied login exits 3 with `access_denied`. If the API answers that browser login is off (`browser_login_unavailable`, exit 3, `"next":"kenso auth login --with-key"`), log in with an API key as above.\n\n## Hand a login to a person (agents)\n\nAn agent that should not sit in a 10-minute wait starts the login, hands the link and code to its person, and collects the key once the person has approved:\n\n```bash\nkenso login --no-wait\nkenso auth wait\nkenso auth wait --timeout 2m\n```\n\n`kenso login --no-wait` (or `kenso auth login --no-wait`) starts a browser login, opens no browser and returns at once:\n\n```json\n{"verificationUrl":"https://app.ken.so/cli/login?code=WXYZ-2345","userCode":"WXYZ-2345","expiresAt":"2026-11-21T10:10:00.000Z","next":"kenso auth wait"}\n```\n\nIt saves the login in `~/.kenso/pending-login.json` (file mode 0600). The file holds the login\'s poll id, which can pick up the key, so the CLI never prints it and removes the file when the login ends. Running `kenso login --no-wait` again while that login is pending for the same profile and API URL, with more than a minute left, prints the same link and code and starts nothing new; `kenso login` without the flag reuses it too and waits for it. A waiting `kenso login` that is stopped leaves the file behind, so `kenso auth wait` can still collect the login.\n\n`kenso auth wait` polls only the API the login was started on, saves the key to the profile the login was started for, and prints what `kenso auth login` prints. By default it waits until the code expires; `--timeout` stops it sooner, after at least one poll, so `--timeout 0` checks once. `--workspace <id>` saves that workspace instead of the one the person approved. The pending login keeps no workspace, so `kenso login --no-wait --workspace <id>` is refused (exit 2): give the workspace to `kenso auth wait`. If the pending login is for another profile whose API differs, `kenso auth wait` answers `no_pending_login` with `next` set to `kenso auth wait --profile <name>`.\n\n| Outcome | Exit | Code | `next` | Pending file |\n|---|---|---|---|---|\n| Approved | 0 | - | - | removed |\n| No pending login, or one started on another API URL | 2 | `no_pending_login` | `kenso login --no-wait` | kept |\n| Denied in the browser | 3 | `login_denied` | `kenso login --no-wait` | removed |\n| The code expired | 3 | `login_expired` | `kenso login --no-wait` | removed |\n| `--timeout` passed first | 3 | `login_pending` | `kenso auth wait` | kept |\n\n## The workspace line\n\nUnder a coding agent, a command that is not a read prints one line on stderr before it runs, its `--dry-run` included: the workspace it acts in and where that came from.\n\n```text\nworkspace: 1234 (--workspace)\nworkspace: 1234 (KENSO_WORKSPACE_ID)\nworkspace: 1234 (profile client-a)\nworkspace: none set (the API picks the key\'s only workspace or answers workspace_required)\n```\n\nRead commands, the login and logout commands, and commands that bring their own credential print no line. The line costs no request.\n\n## CI, scripts and agents: use the environment\n\nYou do not need to log in on a machine that has the key in its environment:\n\n```bash\nexport KENSO_API_KEY=kenso_live_...\nexport KENSO_WORKSPACE_ID=1234\nkenso auth status\n```\n\n`KENSO_API_KEY` wins over any saved profile. Store it as a secret in your CI or agent platform, never in a file in the repo.\n\n## Workspaces\n\nA key reaches every workspace its user belongs to. Each command runs in one workspace, picked in this order:\n\n1. `--workspace <id>` on the command\n2. `KENSO_WORKSPACE_ID`\n3. the workspace saved in the profile (`kenso workspace use`)\n\n```bash\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --workspace 5678\n```\n\n`workspace list` prints one page and says on stderr when there are more: add `--all` for every page. A command that needs a workspace when none is picked fails with `workspace_required` (exit 2) and `"next":"kenso workspace list --search <name>"`.\n\n## Workspace-owned keys\n\nA workspace admin can create a key the workspace owns: it keeps working when the admin leaves and acts with exactly the permissions of its template (`admin`, `editor` or `viewer`). Workspace keys are on for every workspace. The command is in beta: `kenso --help` and `kenso workspace --help` list it, marked beta, once the CLI has read the workspace\'s features from `GET /v1/me`. When it cannot read them (no key, or the lookup fails or takes more than 1.5 seconds), help hides the command and names it on its "Beta, hidden" line instead; `--all-commands` shows it. It runs when typed either way.\n\n```bash\nkenso workspace keys create --name "Zapier sync" --template editor --expires-in-days 90\n```\n\nNo API key may create a workspace key, the one the CLI logs in with included. The command prints the API\'s refusal (`forbidden`) with `"next":"A workspace admin can create it in the app: Settings > API keys > Workspace keys"` and exits 3, without retrying. A member who is not a workspace admin gets a 403 too (`permission_denied`), with the same next step. An admin creates the key there; the secret is shown once.\n\n## Profiles\n\nA profile holds a key, a workspace, an optional API URL and the email. Use one per client or per key:\n\n```bash\nkenso auth login --with-key --profile client-a < client-a-key.txt\nkenso campaigns list --profile client-a\nKENSO_PROFILE=client-a kenso auth status\n```\n\nThe profile is `--profile`, else `KENSO_PROFILE`, else the active one (the last one you logged in to).\n\n## Check the setup\n\n```bash\nkenso auth status\nkenso doctor\n```\n\n`auth status` prints who the key belongs to and when it expires, and warns on stderr when that is within 14 days:\n\n```json\n{"email":"you@acme.io","workspaceCount":3,"activeWorkspace":{"id":"1234","name":"Acme"},"keyExpiresAt":"2027-01-31T00:00:00Z","keySource":"profile","profile":"default"}\n```\n\n`doctor` prints the version, Node, the config folder, the profile, the key source, the API URL, the workspace and the detected agent, then seven checks: `node_version`, `config_permissions`, `api_reachable`, `key_valid`, `skill_installed`, `skill_current` and `mcp_registered`. A failed check carries the `next` command that fixes it, and the top-level `next` is the first of those; when every check passes, `starters` lists four requests to start with. It exits 0 when the first four checks pass, 3 when the key is missing or rejected, else 1.\n\n## Log out\n\n```bash\nkenso auth logout\nkenso auth logout --profile client-a\nkenso auth logout --keep-key\n```\n\nThis removes the profile and its key from this machine. When browser login made the key, logout revokes it first, so it stops working everywhere; `--keep-key` leaves it valid. If the revoke fails (no network, or the key was already revoked), logout warns and still removes the profile. A key you saved with `--with-key` was made by you in the app, so logout leaves it valid: revoke it at Settings > Integrations > API keys. The output adds `revoked: true` or `false`.\n\n## Where things live\n\n| What | Default | Override |\n|---|---|---|\n| Config file with profiles and keys | `~/.kenso/config.json` | `KENSO_CONFIG_DIR` |\n| Pending browser login (`kenso login --no-wait`) | `~/.kenso/pending-login.json` | follows `KENSO_CONFIG_DIR` |\n| Run folders | `~/.kenso/runs/` | `KENSO_RUNS_DIR` |\n| Cached workspace features (1 hour) | `~/.kenso/cache/` | follows `KENSO_CONFIG_DIR` |\n| Last update check (once every 7 days) | `~/.kenso/update-check.json` | follows `KENSO_CONFIG_DIR`; `KENSO_NO_UPDATE_NOTIFIER=1` turns the check off |\n| API | `https://api.ken.so` | `KENSO_API_URL` |\n| MCP (for `kenso mcp`) | `https://mcp.ken.so/mcp` | `KENSO_MCP_URL` |\n\n`--verbose` prints each request line to stderr with the key redacted.\n';
9865
+ auth_default = '# Authentication\n\nThe CLI calls the Kenso API with a Kenso API key (`kenso_live_` plus 49 characters, or an older key: `ken_` plus 43 characters). It sends the key as `Authorization: Bearer <key>` and never prints it, logs it or puts it in an error.\n\n`kenso login`, `kenso logout` and `kenso whoami` are the same commands as `kenso auth login`, `kenso auth logout` and `kenso auth status`.\n\n## Log in with an API key\n\n1. In app.ken.so, go to Settings > Integrations > API keys and create a key.\n2. Pipe it to `kenso auth login --with-key`. The key is read from stdin, never from a flag, so it stays out of your shell history and process list.\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso auth login --with-key --profile client-a --workspace 1234 < key.txt\n```\n\nThe CLI checks the key with `GET /v1/me`, then saves it to `~/.kenso/config.json` (file mode 0600, folder mode 0700). It prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","workspaceCount":1}\n```\n\nA developer sandbox does not count here unless every workspace is one: a key whose user has one workspace and a sandbox saves that workspace. When the key reaches several workspaces and you did not pass `--workspace`, no workspace is saved and the output carries `"next":"kenso workspace list --search <name>"`. A key in the wrong format exits 2 (`invalid_key_format`). A key Kenso rejects exits 3.\n\n## Browser login\n\n```bash\nkenso auth login\nkenso auth login --no-browser --device-name "build box"\n```\n\nBrowser login is available to every workspace. The CLI prints a link and a code on stderr. You open the link, sign in to app.ken.so, check that the code matches the one in your terminal, pick the workspace to start in and approve. The CLI then saves a new API key to the profile and prints:\n\n```json\n{"profile":"default","email":"you@acme.io","workspaceId":"1234","keyExpiresAt":"2027-02-02T06:26:59Z"}\n```\n\nThe key is the same kind you create in the app. It is named `Kenso CLI - <device name>` (`--device-name`, else `kenso-cli on <hostname>`), lasts 90 days, and shows in your API key list at Settings > Integrations > API keys, where you can revoke it. The CLI opens the browser itself only when no coding agent is detected and the machine has a display. An agent prints the link and asks you to open it. The login expires after 10 minutes (`login_expired`, exit 3), and a denied login exits 3 with `access_denied`. If the API answers that browser login is off (`browser_login_unavailable`, exit 3, `"next":"kenso auth login --with-key"`), log in with an API key as above.\n\n## Hand a login to a person (agents)\n\nAn agent that should not sit in a 10-minute wait starts the login, hands the link and code to its person, and collects the key once the person has approved:\n\n```bash\nkenso login --no-wait\nkenso auth wait\nkenso auth wait --timeout 2m\n```\n\n`kenso login --no-wait` (or `kenso auth login --no-wait`) starts a browser login, opens no browser and returns at once:\n\n```json\n{"verificationUrl":"https://app.ken.so/cli/login?code=WXYZ-2345","userCode":"WXYZ-2345","expiresAt":"2026-11-21T10:10:00.000Z","next":"kenso auth wait"}\n```\n\nIt saves the login in `~/.kenso/pending-login.json` (file mode 0600). The file holds the login\'s poll id, which can pick up the key, so the CLI never prints it and removes the file when the login ends. Running `kenso login --no-wait` again while that login is pending for the same profile and API URL, with more than a minute left, prints the same link and code and starts nothing new; `kenso login` without the flag reuses it too and waits for it. A waiting `kenso login` that is stopped leaves the file behind, so `kenso auth wait` can still collect the login.\n\n`kenso auth wait` polls only the API the login was started on, saves the key to the profile the login was started for, and prints what `kenso auth login` prints. By default it waits until the code expires; `--timeout` stops it sooner, after at least one poll, so `--timeout 0` checks once. `--workspace <id>` saves that workspace instead of the one the person approved. The pending login keeps no workspace, so `kenso login --no-wait --workspace <id>` is refused (exit 2): give the workspace to `kenso auth wait`. If the pending login is for another profile whose API differs, `kenso auth wait` answers `no_pending_login` with `next` set to `kenso auth wait --profile <name>`.\n\n| Outcome | Exit | Code | `next` | Pending file |\n|---|---|---|---|---|\n| Approved | 0 | - | - | removed |\n| No pending login, or one started on another API URL | 2 | `no_pending_login` | `kenso login --no-wait` | kept |\n| Denied in the browser | 3 | `login_denied` | `kenso login --no-wait` | removed |\n| The code expired | 3 | `login_expired` | `kenso login --no-wait` | removed |\n| `--timeout` passed first | 3 | `login_pending` | `kenso auth wait` | kept |\n\n## The workspace line\n\nUnder a coding agent, a command that is not a read prints one line on stderr before it runs, its `--dry-run` included: the workspace it acts in and where that came from.\n\n```text\nworkspace: 1234 (--workspace)\nworkspace: 1234 (KENSO_WORKSPACE_ID)\nworkspace: 1234 (kenso.json)\nworkspace: 1234 (profile client-a)\nworkspace: none set (the API picks the key\'s only workspace or answers workspace_required)\n```\n\nRead commands, the login and logout commands, and commands that bring their own credential print no line. The line costs no request.\n\n## CI, scripts and agents: use the environment\n\nYou do not need to log in on a machine that has the key in its environment:\n\n```bash\nexport KENSO_API_KEY=kenso_live_...\nexport KENSO_WORKSPACE_ID=1234\nkenso auth status\n```\n\n`KENSO_API_KEY` wins over any saved profile. Store it as a secret in your CI or agent platform, never in a file in the repo.\n\n## Workspaces\n\nA key reaches every workspace its user belongs to. Each command runs in one workspace, picked in this order:\n\n1. `--workspace <id>` on the command\n2. `KENSO_WORKSPACE_ID`\n3. `workspaceId` in a `kenso.json` in this folder or a folder above it, up to the repository root or your home folder (see [kenso.json](workflows.md#kensojson))\n4. the workspace saved in the profile (`kenso workspace use`)\n\n```bash\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --workspace 5678\n```\n\n`workspace list` prints one page and says on stderr when there are more: add `--all` for every page. A command that needs a workspace when none is picked fails with `workspace_required` (exit 2) and `"next":"kenso workspace list --search <name>"`.\n\n## Workspace-owned keys\n\nA workspace admin can create a key the workspace owns: it keeps working when the admin leaves and acts with exactly the permissions of its template (`admin`, `editor` or `viewer`). Workspace keys are on for every workspace. The command is in beta: `kenso --help` and `kenso workspace --help` list it, marked beta, once the CLI has read the workspace\'s features from `GET /v1/me`. When it cannot read them (no key, or the lookup fails or takes more than 1.5 seconds), help hides the command and names it on its "Beta, hidden" line instead; `--all-commands` shows it. It runs when typed either way.\n\n```bash\nkenso workspace keys create --name "Zapier sync" --template editor --expires-in-days 90\n```\n\nNo API key may create a workspace key, the one the CLI logs in with included. The command prints the API\'s refusal (`forbidden`) with `"next":"A workspace admin can create it in the app: Settings > API keys > Workspace keys"` and exits 3, without retrying. A member who is not a workspace admin gets a 403 too (`permission_denied`), with the same next step. An admin creates the key there; the secret is shown once.\n\n## Profiles\n\nA profile holds a key, a workspace, an optional API URL and the email. Use one per client or per key:\n\n```bash\nkenso auth login --with-key --profile client-a < client-a-key.txt\nkenso campaigns list --profile client-a\nKENSO_PROFILE=client-a kenso auth status\n```\n\nThe profile is `--profile`, else `KENSO_PROFILE`, else the active one (the last one you logged in to).\n\n## Check the setup\n\n```bash\nkenso auth status\nkenso doctor\n```\n\n`auth status` prints who the key belongs to and when it expires, and warns on stderr when that is within 14 days:\n\n```json\n{"email":"you@acme.io","workspaceCount":3,"activeWorkspace":{"id":"1234","name":"Acme"},"keyExpiresAt":"2027-01-31T00:00:00Z","keySource":"profile","profile":"default"}\n```\n\n`doctor` prints the version, Node, the config folder, the profile, the key source, the API URL, the workspace and the detected agent, then seven checks: `node_version`, `config_permissions`, `api_reachable`, `key_valid`, `skill_installed`, `skill_current` and `mcp_registered`. A failed check carries the `next` command that fixes it, and the top-level `next` is the first of those; when every check passes, `starters` lists four requests to start with. It exits 0 when the first four checks pass, 3 when the key is missing or rejected, else 1.\n\n## Log out\n\n```bash\nkenso auth logout\nkenso auth logout --profile client-a\nkenso auth logout --keep-key\n```\n\nThis removes the profile and its key from this machine. When browser login made the key, logout revokes it first, so it stops working everywhere; `--keep-key` leaves it valid. If the revoke fails (no network, or the key was already revoked), logout warns and still removes the profile. A key you saved with `--with-key` was made by you in the app, so logout leaves it valid: revoke it at Settings > Integrations > API keys. The output adds `revoked: true` or `false`.\n\n## Where things live\n\n| What | Default | Override |\n|---|---|---|\n| Config file with profiles and keys | `~/.kenso/config.json` | `KENSO_CONFIG_DIR` |\n| Pending browser login (`kenso login --no-wait`) | `~/.kenso/pending-login.json` | follows `KENSO_CONFIG_DIR` |\n| Run folders | `~/.kenso/runs/` | `KENSO_RUNS_DIR` |\n| Cached workspace features (1 hour) | `~/.kenso/cache/` | follows `KENSO_CONFIG_DIR` |\n| Last update check (once every 7 days) | `~/.kenso/update-check.json` | follows `KENSO_CONFIG_DIR`; `KENSO_NO_UPDATE_NOTIFIER=1` turns the check off |\n| API | `https://api.ken.so` | `KENSO_API_URL` |\n| MCP (for `kenso mcp`) | `https://mcp.ken.so/mcp` | `KENSO_MCP_URL` |\n\n`--verbose` prints each request line to stderr with the key redacted.\n';
9745
9866
  }
9746
9867
  });
9747
9868
 
@@ -9781,7 +9902,7 @@ var init_leads = __esm({
9781
9902
  var output_and_errors_default;
9782
9903
  var init_output_and_errors = __esm({
9783
9904
  "docs/output-and-errors.md"() {
9784
- 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, removes or merges, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive`, `kenso people merge` 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`, `kenso notes add` 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. A command that reads before it writes (`kenso layouts set --header` reads the layout it edits) still reads with `--dry-run`, and prints the write it would send. A POST that changes nothing, such as `kenso accounts search` or `kenso reports query`, is a read like a GET.\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`, or with `Read-only.` when the command only reads, and `kenso describe <resource> <action>` shows `"dryRun": false`. Every command that only reads, generated ones included, says `Read-only.` there.\n- A dry run of a command that can charge credits adds `credits`: `{"needed": n, "available": n, "sufficient": true}`, in credits. A batch command prices the whole file; a single API command adds `cost`, its price lines from your rate card. No output shows a currency amount.\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, such as a delete) | key-value lines: `ok`, `status`, `request` | `{"ok":true,"status":204,"request":{"method":"DELETE","path":"/v1/tasks/7"}}` |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table`, `ids` or `csv`. `--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- `-o csv` prints a header row, then one row per item (RFC 4180, `\\n` line ends). The columns are the `--fields` names in the order you give them; without `--fields`, the top-level keys of the first 100 rows, in the order they first appear. A nested field is `a.b`, an object or array in a cell is its compact JSON, and `null` or a missing key is an empty cell. With `--all` the header is fixed from the first 100 rows, and a later row\'s other keys are dropped with one line on stderr naming them. A single object prints as a two-line CSV. Values are written as they are: nothing is cut, and line breaks stay inside the quotes.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso campaigns list --limit 3 -o csv --fields id,name,status\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- A thread list\'s `preview` is a one-line preview by default: the first 280 characters of the newest message\'s text (the API\'s `bodyFormat=snippet`), in every format. `--full`, or `--fields` that names `preview` or `htmlBody`, prints the whole message text, and `kenso threads list-messages --thread-id <id>` reads every message of a thread whole.\n- A contact list asks the API for only the fields it prints (the API\'s `fields`), so a page downloads what it shows. A thread list printed with `-o ids`, or with `--fields` that names neither `preview` nor `htmlBody`, asks for no message bodies (`bodyFormat=none`). `--full` and `--query` ask for every field, and `--param-fields` or `--body-format` sent by hand wins.\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 --fields id,subject,preview\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| `read_only` | 2 | `--read-only` or `KENSO_READ_ONLY` is on and the command is not a read: nothing was sent. `next` (with `--read-only` only, on a command with a dry run) is the same command with `--dry-run`, which prints the plan and changes nothing |\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| `local_changes` | 7 | `studio pull` would replace files that no earlier pull wrote or push sent, or that changed since; nothing was written, and `next` adds `--force` to replace them |\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 is not a file of the Studio bundle layout (such as a dotfile, `opencode.json` or `CLAUDE.md`), would land outside `--dir`, or passes through a symbolic link, or a `samples/*.json` that does not hold a sample |\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## Effect, cost and read-only mode\n\nEvery command has an effect: `read` (changes nothing, charges nothing), `write` (changes workspace data, charges nothing the API contract declares, nothing leaves Kenso), `spend` (can charge credits), `send` (sends an email, a LinkedIn message, a call or an invitation, or starts or resumes sending) or `destructive` (deletes, archives, removes or merges). Command help prints `Effect: <effect>.` under the summary, and a command that charges adds a `Cost:` line in credits from your workspace\'s rate card.\n\n`kenso describe <resource> <action>` adds `effect` and `cost` to its JSON. `cost` is `null` for a command that does not charge, else `{"lines": [...], "rateCard": {"source": ..., "versions": [...]}}`: each line is the command\'s credit line with its `price` text, and `source` is `live`, `cache` or `bundled`. A command that charges something no rate-card row prices has `{"lines": [], "rateCard": null}`, with `text` saying what it charges when the command states it. `kenso describe` and `kenso describe <resource>` add `effect` to each row.\n\nA generated command that charges prints the same `cost` in its `--dry-run` plan, for the request it would send. A flag that turns off every charge says so: `kenso accounts create --skip-research --dry-run` prints `"cost": {"lines": [], "text": "not charged in credits (--skip-research: no research or committee run)", "rateCard": null}` and `"credits": {"needed": 0, "available": null, "sufficient": null}`, and reads nothing.\n\n`--read-only`, or `KENSO_READ_ONLY=1` in the environment, refuses every command whose effect is not `read` before it sends a request, with exit 2:\n\n```json\n{"error":{"code":"read_only","message":"kenso campaigns launch is a send command, and this session is read-only.","hint":"Read-only is on through --read-only: next prints the plan. Run the command again without --read-only to make the change.","next":"kenso --read-only campaigns launch --campaign-id 1 --dry-run"}}\n```\n\n`next` never makes the change: on a command with a dry run it is the same command with `--dry-run` and without `--yes`, which prints the plan. A command with no dry run gets no `next`, and its hint says to run it again without `--read-only`. A command with its own `--body-read-only` option (`kenso api-keys create`) gets no `next` either, and its hint names that option. When the variable turned read-only on, the hint reads `KENSO_READ_ONLY is set: unset it to run this command.` and there is no `next`, so an agent that runs `next` cannot loop. A POST that only reads, such as `kenso contacts search`, still runs; a GET that charges, such as `kenso search get-place`, is refused; a command with a dry run still prints its plan with `--dry-run`; `kenso api` has the effect of the route it calls, and on a route this CLI does not know only a `GET` runs.\n\n```bash\nKENSO_READ_ONLY=1 kenso contacts search --limit 1\nkenso --read-only describe email-finds create\n```\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';
9905
+ 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, removes or merges, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive`, `kenso people merge` 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`, `kenso notes add` 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. A command that reads before it writes (`kenso layouts set --header` reads the layout it edits) still reads with `--dry-run`, and prints the write it would send. A POST that changes nothing, such as `kenso accounts search` or `kenso reports query`, is a read like a GET.\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`, or with `Read-only.` when the command only reads, and `kenso describe <resource> <action>` shows `"dryRun": false`. Every command that only reads, generated ones included, says `Read-only.` there.\n- A dry run of a command that can charge credits adds `credits`: `{"needed": n, "available": n, "sufficient": true}`, in credits. A batch command prices the whole file; a single API command adds `cost`, its price lines from your rate card. No output shows a currency amount.\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, such as a delete) | key-value lines: `ok`, `status`, `request` | `{"ok":true,"status":204,"request":{"method":"DELETE","path":"/v1/tasks/7"}}` |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table`, `ids` or `csv`. `--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- `-o csv` prints a header row, then one row per item (RFC 4180, `\\n` line ends). The columns are the `--fields` names in the order you give them; without `--fields`, the top-level keys of the first 100 rows, in the order they first appear. A nested field is `a.b`, an object or array in a cell is its compact JSON, and `null` or a missing key is an empty cell. With `--all` the header is fixed from the first 100 rows, and a later row\'s other keys are dropped with one line on stderr naming them. A single object prints as a two-line CSV. Values are written as they are: nothing is cut, and line breaks stay inside the quotes.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso campaigns list --limit 3 -o csv --fields id,name,status\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- A thread list\'s `preview` is a one-line preview by default: the first 280 characters of the newest message\'s text (the API\'s `bodyFormat=snippet`), in every format. `--full`, or `--fields` that names `preview` or `htmlBody`, prints the whole message text, and `kenso threads list-messages --thread-id <id>` reads every message of a thread whole.\n- A contact list asks the API for only the fields it prints (the API\'s `fields`), so a page downloads what it shows. A thread list printed with `-o ids`, or with `--fields` that names neither `preview` nor `htmlBody`, asks for no message bodies (`bodyFormat=none`). `--full` and `--query` ask for every field, and `--param-fields` or `--body-format` sent by hand wins.\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 --fields id,subject,preview\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| `read_only` | 2 | `--read-only` or `KENSO_READ_ONLY` is on and the command is not a read: nothing was sent. `next` (with `--read-only` only, on a command with a dry run) is the same command with `--dry-run`, which prints the plan and changes nothing |\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| `folder_file_untrusted` | 2 | A workflow command would read or write a `kenso.json` that another user owns or anyone can write: kenso skips such a file and names it on stderr, and nothing was written or sent. Make it yours and writable only by you, or work in a folder only you can write |\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 (for `kenso workflows run`, a run on the same input), or `studio fill` already ran with this file and these flags |\n| `already_started` | 7 | `kenso workflows run`: an earlier run on the same input already sent starts, and this one would start records differently (another `--max-credits`), so it would start them twice. Nothing was sent: `not-started.txt` in that run\'s folder holds the ids it did not start, and `next` runs only those |\n| `local_changes` | 7 | `studio pull` would replace files that no earlier pull wrote or push sent, or that changed since; nothing was written, and `next` adds `--force` to replace them |\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 is not a file of the Studio bundle layout (such as a dotfile, `opencode.json` or `CLAUDE.md`), would land outside `--dir`, or passes through a symbolic link, or a `samples/*.json` that does not hold a sample |\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), a run another process holds (`run_in_progress`), or a workflow run that would start records twice (`already_started`) |\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## Effect, cost and read-only mode\n\nEvery command has an effect: `read` (changes nothing, charges nothing), `write` (changes workspace data, charges nothing the API contract declares, nothing leaves Kenso), `spend` (can charge credits), `send` (sends an email, a LinkedIn message, a call or an invitation, or starts or resumes sending) or `destructive` (deletes, archives, removes or merges). Command help prints `Effect: <effect>.` under the summary, and a command that charges adds a `Cost:` line in credits from your workspace\'s rate card.\n\n`kenso describe <resource> <action>` adds `effect` and `cost` to its JSON. `cost` is `null` for a command that does not charge, else `{"lines": [...], "rateCard": {"source": ..., "versions": [...]}}`: each line is the command\'s credit line with its `price` text, and `source` is `live`, `cache` or `bundled`. A command that charges something no rate-card row prices has `{"lines": [], "rateCard": null}`, with `text` saying what it charges when the command states it. `kenso describe` and `kenso describe <resource>` add `effect` to each row.\n\nA generated command that charges prints the same `cost` in its `--dry-run` plan, for the request it would send. A flag that turns off every charge says so: `kenso accounts create --skip-research --dry-run` prints `"cost": {"lines": [], "text": "not charged in credits (--skip-research: no research or committee run)", "rateCard": null}` and `"credits": {"needed": 0, "available": null, "sufficient": null}`, and reads nothing.\n\n`--read-only`, or `KENSO_READ_ONLY=1` in the environment, refuses every command whose effect is not `read` before it sends a request, with exit 2:\n\n```json\n{"error":{"code":"read_only","message":"kenso campaigns launch is a send command, and this session is read-only.","hint":"Read-only is on through --read-only: next prints the plan. Run the command again without --read-only to make the change.","next":"kenso --read-only campaigns launch --campaign-id 1 --dry-run"}}\n```\n\n`next` never makes the change: on a command with a dry run it is the same command with `--dry-run` and without `--yes`, which prints the plan. A command with no dry run gets no `next`, and its hint says to run it again without `--read-only`. A command with its own `--body-read-only` option (`kenso api-keys create`) gets no `next` either, and its hint names that option. When the variable turned read-only on, the hint reads `KENSO_READ_ONLY is set: unset it to run this command.` and there is no `next`, so an agent that runs `next` cannot loop. A POST that only reads, such as `kenso contacts search`, still runs; a GET that charges, such as `kenso search get-place`, is refused; a command with a dry run still prints its plan with `--dry-run`; `kenso api` has the effect of the route it calls, and on a route this CLI does not know only a `GET` runs.\n\n```bash\nKENSO_READ_ONLY=1 kenso contacts search --limit 1\nkenso --read-only describe email-finds create\n```\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';
9785
9906
  }
9786
9907
  });
9787
9908
 
@@ -9829,7 +9950,7 @@ var init_work = __esm({
9829
9950
  var workflows_default;
9830
9951
  var init_workflows = __esm({
9831
9952
  "docs/workflows.md"() {
9832
- workflows_default = '# Workflows (beta)\n\nA workflow is automation in Kenso: one trigger, a list of steps and limits. With the CLI you keep a workflow as a JSON file in your folder or repo: write it, check it, push it to the draft, test the draft, publish the version you tested, and run it on records with a credit cap and a results file.\n\nThe commands are beta: they show where your workspace has the `workflows` feature. Help hides them until your workspace has it; `kenso --help --all-commands` shows them. `kenso workflows test` and `kenso workflows run` also need `workflows_runtime`. Without it `test` stops with `runtime_off` (exit 4), "Workflows cannot run in this workspace yet.", with no retry, and a run that `kenso workflows run` starts stays `queued`, which `--wait` reports at its timeout.\n\n| Command | What it does |\n|---|---|\n| `workflows init [name]` | Write a new workflow file, blank or from a template, and a `kenso.json` |\n| `workflows pull <workflowId>` | Write a saved workflow\'s definition to a file and bind the file |\n| `workflows check <file>` | Validate the file and estimate one record; saves nothing |\n| `workflows push <file>` | Create the workflow or save the file to its draft; with `--publish`, publish it |\n| `workflows test <file>` | Run the saved draft once on one record |\n| `workflows diff <file>` | Compare the file with the published version or the draft |\n| `workflows schema` | Print a JSON Schema for workflow files, for editors |\n| `workflows run <file or id>` | Run the published workflow on ids or a CSV, estimate first |\n| `workflow-runs logs <runId>` | One row per step of a run: status, credits, error |\n\nThe other workflow commands are generated from the API, one per route: `kenso workflows publish`, `unpublish`, `get` and `list`, `kenso workflow-versions`, `kenso workflow-runs list`, `get`, `cancel`, `restart`, `retry` and `replay`, `kenso workflow-templates` and `kenso workflow-step-types`. `kenso <command> --help` shows their flags.\n\n## The file\n\nA workflow file is one JSON object in the `kenWorkflow: "1"` format, named `<name>.workflow.json`:\n\n```json\n{\n "kenWorkflow": "1",\n "name": "Qualify accounts",\n "description": "Scores each account against a simple ICP.",\n "trigger": { "type": "trigger.manual@1", "with": { "recordType": "account" } },\n "steps": [\n { "id": "qualify", "type": "ai.qualify@1", "with": { "criteria": "B2B SaaS, 50+ people", "tier": "cheap" } }\n ],\n "limits": { "creditsPerMonth": 100, "creditsPerRun": 5, "runsPerDay": 50, "atLimit": "ask" }\n}\n```\n\nThe format (trigger, steps, references, formulas, limits) is the `workflows` skill\'s `references/definition-format.md`. `kenso workflows schema` prints a JSON Schema (draft 2020-12) of the file with each step type\'s inputs, for an editor, offline; the server\'s validate stays the authority. `kenso workflow-step-types get` prints one step type\'s inputs and an example.\n\n```bash\nkenso workflows schema --out workflow.schema.json\nkenso workflow-step-types get --type ai.qualify@1\nkenso mcp call load_skill --args \'{"name":"workflows","reference":"references/definition-format.md"}\'\n```\n\n## kenso.json\n\n`kenso.json` binds workflow files to workflow ids and pins the folder\'s workspace. `init`, `pull` and `push` write it; you rarely edit it by hand.\n\n```json\n{\n "workspaceId": "3047",\n "profile": "client-a",\n "workflows": { "workflows/qualify.workflow.json": 412 }\n}\n```\n\n- All three keys are optional. `workspaceId` is a string of digits. `profile` is a profile name. `workflows` maps a path relative to `kenso.json` (forward slashes) to a workflow id. One file holds one workflow and one workflow is bound to one file: binding a second is `already_bound` (exit 7). Other keys are kept when the CLI rewrites the file.\n- The CLI looks for it from the current folder up to the first folder that holds `.git`; for a command given a file, from that file\'s folder.\n- The workspace is `--workspace`, else `KENSO_WORKSPACE_ID`, else `kenso.json`, else the profile\'s. The profile is `--profile`, else `KENSO_PROFILE`, else `kenso.json`, else the active profile. `kenso.json` never changes the API URL or the key.\n- A file command run in another workspace than the one `kenso.json` names stops with `workspace_mismatch` (exit 2): its workflow ids belong to that workspace.\n- It never holds a key or an API URL. A file with `apiKey`, `key`, `token`, a value starting with `kenso_`, or `apiUrl` is `folder_file_invalid` (exit 2), "kenso.json never holds a key or an API URL: remove <name>.", and nothing reads it. Invalid JSON, or a key of the wrong type, is the same error with the path and the key.\n- `kenso whoami` and `kenso auth status` print `workspaceSource` (`flag`, `env`, `folder`, `profile` or `none`) and, for `folder`, `folderFile`.\n\n```bash\nkenso whoami -o json\n```\n\n## The first run\n\nFrom a template to records:\n\n```bash\nkenso workflow-templates list\nkenso workflows init qualify --template <templateKey>\nkenso workflows push qualify.workflow.json\nkenso workflows check qualify.workflow.json --mode publish\nkenso workflows test qualify.workflow.json --record account:<accountId>\nkenso workflows push qualify.workflow.json --publish --expected-hash <definitionHash>\nkenso workflows run qualify.workflow.json --ids ids.txt --dry-run\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits 10 --yes\n```\n\nFill the template\'s `<fill in: ...>` placeholders and set `limits` in the file before the first push. `check --mode publish` names everything publish would refuse, with a `fix` for each issue.\n\n## The commands\n\n### init\n\n```bash\nkenso workflows init qualify --template <templateKey> --dir workflows\n```\n\nWrites `<name>.workflow.json`: the template\'s definition with `--template`, else a blank definition with `trigger.manual@1` and no steps. Writes `kenso.json` with the resolved workspace when no folder file is found. It never replaces a file (`file_exists`, exit 7), sends no request without `--template`, and creates nothing in Kenso. Prints `{file, template, folderFile, folderFileCreated, workspaceId}`.\n\n### pull\n\n```bash\nkenso workflows pull 412 --out qualify.workflow.json\n```\n\nWrites the draft\'s definition (else the published one; `--published` takes the published one) to `--out` or `<slug of the name>.workflow.json`, with 2-space indents and a final newline, and binds the file in `kenso.json`. An existing file is replaced only when `kenso.json` binds it to this workflow (else `file_exists`, exit 7). When the workflow is bound to another file already, the new file is an unbound copy. Prints `{file, workflowId, draftVersion, draftHash, publishedHash, status}`.\n\n### check\n\n```bash\nkenso workflows check qualify.workflow.json --mode publish\n```\n\nSends the file as the definition to validate (saving nothing) and to the estimate for one record. Prints `{valid, issues, perRecord, draftHash, inSync, next}`: each issue has `path`, `code`, `message`, `fix` and `severity`; `perRecord` is `{expectedCredits, maxCredits}`; `draftHash` is the saved draft\'s hash, and `inSync` says whether the file equals that draft. Exit 0 when valid, 5 when not. `--mode draft` (the default) checks structure, schemas, references and formulas; `--mode publish` also checks limits, secrets and connected apps. An unbound file is `workflow_not_bound` (exit 2), "check needs a workflow id: a draft runs nothing and costs nothing.", with `next: kenso workflows push <file>`.\n\n### push\n\n```bash\nkenso workflows push qualify.workflow.json --note "Raise the size floor"\nkenso workflows push qualify.workflow.json --dry-run\n```\n\nAn unbound file creates the workflow and binds the file. A bound file is saved to the draft when it differs from it, on top of the draft version just read; an identical file saves nothing. Prints `{workflowId, saved, draftVersion, draftHash, published, status, next}`. `--dry-run` prints `wouldSend`: which of create, update and publish it would send. `--publish` publishes after the save, and `--expected-hash` goes with it (see The hash rule).\n\n### test\n\n```bash\nkenso workflows test qualify.workflow.json --record account:<accountId> --wait 50\n```\n\nRuns the saved draft once on one record: `--record <type:id>` (`person:812`; the types are `account`, `person`, `lead` and `place`), else the newest record of the trigger\'s type. `--wait` is the seconds the API waits for the run, 0 to 50 (50 by default). AI and data steps run for real and are charged; sends and CRM writes are simulated. A file that differs from the draft is refused (`draft_out_of_sync`, exit 7, `next: kenso workflows push <file>`). Prints `{testPassed, timedOut, definitionHash, publishPassRecorded, run: {id, status, creditsCharged}, hint, next}`; after a pass, `next` is the publish command with `--expected-hash <definitionHash>`. Exit 1 when the test did not pass.\n\n### diff\n\n```bash\nkenso workflows diff qualify.workflow.json --against draft\n```\n\nCompares the file with the published version (the default; the draft when nothing is published) or with the draft. Prints `{against, same, nameChanged, triggerChanged, limitsChanged, stepsAdded, stepsRemoved, stepsChanged}` with step ids. Exit 0 either way.\n\n### schema\n\n```bash\nkenso workflows schema --out workflow.schema.json\n```\n\nPrints, or writes to `--out`, the JSON Schema of a workflow file. It needs no sign-in and no network, and `--out` replaces only a schema it wrote.\n\n## The hash rule\n\n`definitionHash` is computed by the server for a saved draft and leaves `plain` out; the CLI never computes one. When the CLI compares a file with a saved definition, it compares them as JSON with keys sorted at every level: whitespace and key order never count.\n\n- Publish needs a passed test on the draft\'s hash. Without one the CLI stops with `test_required` (exit 7), "Publish needs a passed test on this exact draft.", and `next: kenso workflows test <file>`.\n- `--expected-hash <hash>` makes push compare the draft\'s hash after the save with the value. A mismatch is `hash_mismatch` (exit 7), "The draft\'s hash is <actual>, not <expected>.", and nothing is published; the saved draft stays. Pass the hash `kenso workflows test` printed.\n- Under a coding agent, `--publish` without `--expected-hash` is refused (`usage_error`, "an agent publishes only the version it tested: pass --expected-hash"). A person at a terminal may publish without it.\n- **The gap.** The publish route takes no hash, so a save that lands between the CLI\'s hash check and the publish call can be published. The server\'s `version_conflict` on a concurrent save and its rule that publish needs a passed test bound it.\n- A save that meets a newer draft is `version_conflict` (exit 7), "Someone saved this workflow since you read it.", with `next: kenso workflows diff <file> --against draft`.\n- A definition the server refuses on save or publish is `invalid_definition` (exit 5) with its issues (`path`, `code`, `message`); on a publish, `next` is `kenso workflows check <file> --mode publish`, which adds a `fix` to each.\n\n## Run on records\n\n```bash\nkenso accounts list --limit 50 -o ids > ids.txt\nkenso workflows run qualify.workflow.json --ids ids.txt --dry-run\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits 10 --wait --out results.csv --yes\nkenso workflows run 412 --file people.csv --record-type person --dry-run\n```\n\n- **Target.** A number is a workflow id. A file must be bound in `kenso.json` and equal to the published version, else `unpublished_changes` (exit 7), "This file differs from the published version.", with `next` naming the push that publishes it (with `--expected-hash` when the saved draft holds the file). A workflow that is not live is `invalid_state` (exit 7) with `next: kenso workflows publish --workflow-id <id>`. Nothing publishes by itself.\n- **Record type** is the trigger\'s (`trigger.manual@1` takes its `with.recordType`); `--record-type` (`account`, `person`, `lead` or `place`) overrides it. A trigger that names no record type needs the flag (`not_runnable_on_records`, exit 2).\n- **Input.** `--ids` is one id per line (`-` reads stdin). `--file` is a CSV: with an `id` column, those ids; without one and with record type `person`, each row is matched or created as a person in chunks of 200, with the columns `kenso people import` accepts and no email finding. Any other record type without an `id` column is `ids_required` (exit 2), which names `kenso contacts import` or `kenso accounts import`. Duplicated ids run once. A saved list runs through a workflow whose trigger is `trigger.saved_list@1` or `trigger.csv@1`; `--list` is not a flag.\n- **Dry run.** `--dry-run`, and a run without `--yes`, estimate per chunk of up to 1,000 records, start nothing, and print `{dryRun, workflowId, records, recordType, credits: {needed, available, sufficient}, perRecord, expectedCredits, cap, next}`. `needed` is the estimate\'s maximum. A CSV without ids is estimated on its row count and creates no person.\n- **Confirmation.** Without `--yes`, a person at a terminal is asked once with the plan on screen. Under a coding agent the command prints the plan and stops, with `next` naming the same command with `--yes`.\n- **`--max-credits <n>`** is enforced by the CLI; the server is sent no cap. The ceiling per record is the definition\'s `limits.creditsPerRun` when set (`cap.kind: "hard"`), else the estimate\'s maximum per record (`cap.kind: "estimate"`). The CLI starts the first `floor(n / ceiling)` records and reports the rest as `not_started` with reason `over --max-credits`. The plan and the summary print `cap: {maxCredits, kind, perRecord, willStart, notStarted}`. A cap below one record\'s ceiling starts nothing: `cap_too_low` (exit 6), with `next` naming the smallest cap that starts one record. A workspace out of credits starts nothing either (`out_of_credits`, exit 6).\n- **`--wait`** follows each started run, up to 8 reads at a time, until it leaves `queued`, `running` and `waiting`, or `--timeout` (90s, 10m, 1h; default 30m) passes. A run still `waiting` at the timeout is reported as `waiting`. `--timeout` goes with `--wait`.\n- **`--out <results.csv>`** (needs `--wait`) writes one row per input record when the batch ends: `row, id, status, runId, runStatus, creditsCharged, missReason, error`, then one column per step id holding that step\'s output as compact JSON. The path is checked before the first request: its folder must exist, and an existing file is refused (`file_exists`, exit 7) unless it is this run\'s own.\n- **Summary.** One JSON object with `records`, `started`, `deduplicated`, `notStarted`, `succeeded`, `failed`, `waiting`, `missed` (reason to count), `creditsCharged` (`"pending"` without `--wait` or while runs are open), `cap`, `resultsCsv`, `appUrl` (the workflow\'s page in the app) and `next`, and the same counts on one stderr line. With `--wait`, a run that failed makes `next` its `kenso workflow-runs logs <runId>`.\n\n## The run folder\n\nEach applied run writes a run folder (`~/.kenso/runs/<id>`) that records every chunk\'s response, as every batch command does: see [Batch runs](batch.md). `kenso runs resume <runId>` never resends a chunk it has an answer for. A chunk that was sent and has no recorded answer is not resent either: resume stops with `chunk_outcome_unknown` (exit 5), the chunk\'s first and last row, and `next: kenso workflow-runs list --workflow-id <id> --created-after <chunk start time>`, so you can see what started.\n\n```bash\nkenso runs resume <runId>\nkenso workflow-runs list --workflow-id 412 --created-after 2026-11-21T10:00:00Z\n```\n\n## Read a run\n\n```bash\nkenso workflow-runs logs <runId>\nkenso workflow-runs logs <runId> --step qualify --full\n```\n\nOne row per step run in start order: `{nodeId, stepType, status, attempt, startedAt, endedAt, ms, credits, error}`, NDJSON when piped. `--step` keeps one node; `--full` adds each step\'s `input`, `output` and `attempts`. A header line on stderr gives the run\'s status, workflow, record and the credits it charged, and `needs attention: <reason>` when one is set. A failed run ends with `next: kenso workflow-runs retry --run-id <id> --dry-run`.\n\n## Step outputs are kept 7 days\n\nA succeeded run\'s step outputs are dropped 7 days after it finishes, unless the workflow keeps success details. `--out` writes them when the batch ends, so run with `--wait --out` when you need the results later.\n\n## Exit codes\n\n| Exit | When |\n|---|---|\n| 0 | Done. For `run`, every record started and, with `--wait`, none failed |\n| 1 | `test`: the test did not pass |\n| 2 | Usage: `workflow_not_bound`, `folder_file_invalid`, `workspace_mismatch`, `not_runnable_on_records`, `ids_required`, or `--publish` without `--expected-hash` under a coding agent |\n| 4 | `test`: `runtime_off`, the workspace cannot run workflows yet |\n| 5 | `check` found the file not valid, the server refused a definition (`invalid_definition`), `run` has records that failed, were not found or were not started, or resume met `chunk_outcome_unknown` |\n| 6 | `run`: the cap started nothing (`cap_too_low`), or the workspace is out of credits |\n| 7 | A conflict: `file_exists`, `already_bound`, `draft_out_of_sync`, `hash_mismatch`, `test_required`, `version_conflict`, `unpublished_changes`, `invalid_state`, or an existing `--out` file |\n\nEvery error is one JSON line on stderr with `code`, `message`, `hint` and `next`: see [Output and errors](output-and-errors.md).\n';
9953
+ workflows_default = '# Workflows (beta)\n\nA workflow is automation in Kenso: one trigger, a list of steps and limits. With the CLI you keep a workflow as a JSON file in your folder or repo: write it, check it, push it to the draft, test the draft, publish the version you tested, and run it on records with a credit cap and a results file.\n\nThe commands are beta: they show where your workspace has the `workflows` feature. Help hides them until your workspace has it; `kenso --help --all-commands` shows them. `kenso workflows test` and `kenso workflows run` also need `workflows_runtime`. Without it `test` stops with `runtime_off` (exit 4), "Workflows cannot run in this workspace yet.", with no retry, and a run that `kenso workflows run` starts stays `queued`, which `--wait` reports at its timeout.\n\n| Command | What it does |\n|---|---|\n| `workflows init [name]` | Write a new workflow file, blank or from a template, and a `kenso.json` |\n| `workflows pull <workflowId>` | Write a saved workflow\'s definition to a file and bind the file |\n| `workflows check <file>` | Validate the file and estimate one record; saves nothing |\n| `workflows push <file>` | Create the workflow or save the file to its draft; with `--publish`, publish it |\n| `workflows test <file>` | Run the saved draft once on one record |\n| `workflows diff <file>` | Compare the file with the published version or the draft |\n| `workflows schema` | Print a JSON Schema for workflow files, for editors |\n| `workflows run <file or id>` | Run the published workflow on ids or a CSV, estimate first |\n| `workflow-runs logs <runId>` | One row per step of a run: status, credits, error |\n\nThe other workflow commands are generated from the API, one per route: `kenso workflows publish`, `unpublish`, `get` and `list`, `kenso workflow-versions`, `kenso workflow-runs list`, `get`, `cancel`, `restart`, `retry` and `replay`, `kenso workflow-templates` and `kenso workflow-step-types`. `kenso <command> --help` shows their flags.\n\n## The file\n\nA workflow file is one JSON object in the `kenWorkflow: "1"` format, named `<name>.workflow.json`:\n\n```json\n{\n "kenWorkflow": "1",\n "name": "Qualify accounts",\n "description": "Scores each account against a simple ICP.",\n "trigger": { "type": "trigger.manual@1", "with": { "recordType": "account" } },\n "steps": [\n { "id": "qualify", "type": "ai.qualify@1", "with": { "criteria": "B2B SaaS, 50+ people", "tier": "cheap" } }\n ],\n "limits": { "creditsPerMonth": 100, "creditsPerRun": 5, "runsPerDay": 50, "atLimit": "ask" }\n}\n```\n\nThe format (trigger, steps, references, formulas, limits) is the `workflows` skill\'s `references/definition-format.md`. `kenso workflows schema` prints a JSON Schema (draft 2020-12) of the file with each step type\'s inputs, for an editor, offline; the server\'s validate stays the authority. `kenso workflow-step-types get` prints one step type\'s inputs and an example.\n\n```bash\nkenso workflows schema --out workflow.schema.json\nkenso workflow-step-types get --type ai.qualify@1\nkenso mcp call load_skill --args \'{"name":"workflows","reference":"references/definition-format.md"}\'\n```\n\n## kenso.json\n\n`kenso.json` binds workflow files to workflow ids and pins the folder\'s workspace. `init`, `pull` and `push` write it; you rarely edit it by hand.\n\n```json\n{\n "workspaceId": "3047",\n "profile": "client-a",\n "workflows": { "workflows/qualify.workflow.json": 412 }\n}\n```\n\n- All three keys are optional. `workspaceId` is a string of digits. `profile` is a profile name. `workflows` maps a path relative to `kenso.json` (forward slashes) to a workflow id. One file holds one workflow and one workflow is bound to one file: binding a second is `already_bound` (exit 7). Other keys are kept when the CLI rewrites the file.\n- The CLI looks for it from the current folder up to the first folder that holds `.git`, else up to your home folder, never above it; for a command given a file, from that file\'s folder. It skips a `kenso.json` another user owns, or that anyone can write or sits in a folder anyone can write (such as `/tmp`): another user could have put it there to pick your workspace. A skipped file is named on stderr, and `init`, `pull`, `push` or `run` on a workflow file beside it stops with `folder_file_untrusted` (exit 2) instead of reading or writing over its bindings. Some mounts show every file as anyone\'s to write (WSL `/mnt/c`, SMB, exFAT): keep workflow files on a Linux folder there.\n- The workspace is `--workspace`, else `KENSO_WORKSPACE_ID`, else `kenso.json`, else the profile\'s. The profile is `--profile`, else `KENSO_PROFILE`, else `kenso.json`, else the active profile. `kenso.json` never changes the API URL or the key.\n- A file command run in another workspace than the one `kenso.json` names stops with `workspace_mismatch` (exit 2): its workflow ids belong to that workspace.\n- It never holds a key or an API URL. A file with `apiKey`, `key`, `token`, a value starting with `kenso_`, or `apiUrl` is `folder_file_invalid` (exit 2), "kenso.json never holds a key or an API URL: remove <name>.", and nothing reads it. Invalid JSON, or a key of the wrong type, is the same error with the path and the key.\n- `kenso whoami` and `kenso auth status` print `workspaceSource` (`flag`, `env`, `folder`, `profile` or `none`) and, for `folder`, `folderFile`.\n\n```bash\nkenso whoami -o json\n```\n\n## The first run\n\nFrom a template to records:\n\n```bash\nkenso workflow-templates list\nkenso workflows init qualify --template <templateKey>\nkenso workflows push qualify.workflow.json\nkenso workflows check qualify.workflow.json --mode publish\nkenso workflows test qualify.workflow.json --record account:<accountId>\nkenso workflows push qualify.workflow.json --publish --expected-hash <definitionHash>\nkenso workflows run qualify.workflow.json --ids ids.txt --dry-run\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits 10 --yes\n```\n\nFill the template\'s `<fill in: ...>` placeholders and set `limits` in the file before the first push. `check --mode publish` names everything publish would refuse, with a `fix` for each issue.\n\n## The commands\n\n### init\n\n```bash\nkenso workflows init qualify --template <templateKey> --dir workflows\n```\n\nWrites `<name>.workflow.json`: the template\'s definition with `--template`, else a blank definition with `trigger.manual@1` and no steps. Writes `kenso.json` with the resolved workspace when no folder file is found. It never replaces a file (`file_exists`, exit 7), sends no request without `--template`, and creates nothing in Kenso. Prints `{file, template, folderFile, folderFileCreated, workspaceId}`.\n\n### pull\n\n```bash\nkenso workflows pull 412 --out qualify.workflow.json\n```\n\nWrites the draft\'s definition (else the published one; `--published` takes the published one) to `--out` or `<slug of the name>.workflow.json`, with 2-space indents and a final newline, and binds the file in `kenso.json`. An existing file is replaced only when `kenso.json` binds it to this workflow (else `file_exists`, exit 7). When the workflow is bound to another file already, the new file is an unbound copy. Prints `{file, workflowId, draftVersion, draftHash, publishedHash, status}`.\n\n### check\n\n```bash\nkenso workflows check qualify.workflow.json --mode publish\n```\n\nSends the file as the definition to validate (saving nothing) and to the estimate for one record. Prints `{valid, issues, perRecord, draftHash, inSync, next}`: each issue has `path`, `code`, `message`, `fix` and `severity`; `perRecord` is `{expectedCredits, maxCredits}`; `draftHash` is the saved draft\'s hash, and `inSync` says whether the file equals that draft. Exit 0 when valid, 5 when not. `--mode draft` (the default) checks structure, schemas, references and formulas; `--mode publish` also checks limits, secrets and connected apps. An unbound file is `workflow_not_bound` (exit 2), "check needs a workflow id: a draft runs nothing and costs nothing.", with `next: kenso workflows push <file>`.\n\n### push\n\n```bash\nkenso workflows push qualify.workflow.json --note "Raise the size floor"\nkenso workflows push qualify.workflow.json --dry-run\n```\n\nAn unbound file creates the workflow and binds the file. A bound file is saved to the draft when it differs from it, on top of the draft version just read; an identical file saves nothing. Prints `{workflowId, saved, draftVersion, draftHash, published, status, next}`. `--dry-run` prints `wouldSend`: which of create, update and publish it would send. `--publish` publishes after the save, and `--expected-hash` goes with it (see The hash rule).\n\n### test\n\n```bash\nkenso workflows test qualify.workflow.json --record account:<accountId> --wait 50\n```\n\nRuns the saved draft once on one record: `--record <type:id>` (`person:812`; the types are `account`, `person`, `lead` and `place`), else the newest record of the trigger\'s type. `--wait` is the seconds the API waits for the run, 0 to 50 (50 by default). AI and data steps run for real and are charged; sends and CRM writes are simulated. A file that differs from the draft is refused (`draft_out_of_sync`, exit 7, `next: kenso workflows push <file>`). Prints `{testPassed, timedOut, definitionHash, publishPassRecorded, run: {id, status, creditsCharged}, hint, next}`; after a pass, `next` is the publish command with `--expected-hash <definitionHash>`. Exit 1 when the test did not pass.\n\n### diff\n\n```bash\nkenso workflows diff qualify.workflow.json --against draft\n```\n\nCompares the file with the published version (the default; the draft when nothing is published) or with the draft. Prints `{against, same, nameChanged, triggerChanged, limitsChanged, stepsAdded, stepsRemoved, stepsChanged}` with step ids. Exit 0 either way.\n\n### schema\n\n```bash\nkenso workflows schema --out workflow.schema.json\n```\n\nPrints, or writes to `--out`, the JSON Schema of a workflow file. It needs no sign-in and no network, and `--out` replaces only a schema it wrote.\n\n## The hash rule\n\n`definitionHash` is computed by the server for a saved draft and leaves `plain` out; the CLI never computes one. When the CLI compares a file with a saved definition, it compares them as JSON with keys sorted at every level: whitespace and key order never count.\n\n- Publish needs a passed test on the draft\'s hash. Without one the CLI stops with `test_required` (exit 7), "Publish needs a passed test on this exact draft.", and `next: kenso workflows test <file>`.\n- `--expected-hash <hash>` makes push compare the draft\'s hash after the save with the value. A mismatch is `hash_mismatch` (exit 7), "The draft\'s hash is <actual>, not <expected>.", and nothing is published; the saved draft stays. Pass the hash `kenso workflows test` printed.\n- Under a coding agent, `--publish` without `--expected-hash` is refused (`usage_error`, "an agent publishes only the version it tested: pass --expected-hash"). A person at a terminal may publish without it.\n- **The gap.** The publish route takes no hash, so a save that lands between the CLI\'s hash check and the publish call can be published. The server\'s `version_conflict` on a concurrent save and its rule that publish needs a passed test bound it.\n- A save that meets a newer draft is `version_conflict` (exit 7), "Someone saved this workflow since you read it.", with `next: kenso workflows diff <file> --against draft`.\n- A definition the server refuses on save or publish is `invalid_definition` (exit 5) with its issues (`path`, `code`, `message`); on a publish, `next` is `kenso workflows check <file> --mode publish`, which adds a `fix` to each.\n\n## Run on records\n\n```bash\nkenso accounts list --limit 50 -o ids > ids.txt\nkenso workflows run qualify.workflow.json --ids ids.txt --dry-run\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits 10 --wait --out results.csv --yes\nkenso workflows run 412 --file people.csv --record-type person --dry-run\n```\n\n- **Target.** A number is a workflow id. A file must be bound in `kenso.json` and equal to the published version, else `unpublished_changes` (exit 7), "This file differs from the published version.", with `next` naming the push that publishes it (with `--expected-hash` when the saved draft holds the file). A workflow that is not live is `invalid_state` (exit 7) with `next: kenso workflows publish --workflow-id <id>`. Nothing publishes by itself.\n- **Record type** is the trigger\'s (`trigger.manual@1` takes its `with.recordType`); `--record-type` (`account`, `person`, `lead` or `place`) overrides it. A trigger that names no record type needs the flag (`not_runnable_on_records`, exit 2).\n- **Input.** `--ids` is one id per line (`-` reads stdin). `--file` is a CSV: with an `id` column, those ids; without one and with record type `person`, each row is matched or created as a person in chunks of 200, with the columns `kenso people import` accepts and no email finding. Any other record type without an `id` column is `ids_required` (exit 2), which names `kenso contacts import` or `kenso accounts import`. Duplicated ids run once. A saved list runs through a workflow whose trigger is `trigger.saved_list@1` or `trigger.csv@1`; `--list` is not a flag.\n- **Dry run.** `--dry-run`, and a run without `--yes`, estimate per chunk of up to 1,000 records, start nothing, and print `{dryRun, workflowId, records, recordType, credits: {needed, available, sufficient}, perRecord, expectedCredits, cap, next}`. `needed` is the estimate\'s maximum and `available` the workspace\'s balance. A value that could not be read is `null`, and the plan adds `estimateError` or `balanceError` with the reason. A CSV without ids is estimated on its row count and creates no person.\n- **Confirmation.** Without `--yes`, a person at a terminal is asked once with the plan on screen. Under a coding agent the command prints the plan and stops, with `next` naming the same command with `--yes`.\n- **`--max-credits <n>`** is enforced by the CLI; the server is sent no cap. The ceiling per record is the definition\'s `limits.creditsPerRun` when set (`cap.kind: "hard"`), else the estimate\'s maximum per record (`cap.kind: "estimate"`). The CLI starts the first `floor(n / ceiling)` records and reports the rest as `not_started` with reason `over --max-credits`. The plan and the summary print `cap: {maxCredits, kind, perRecord, willStart, notStarted}`. A cap below one record\'s ceiling starts nothing: `cap_too_low` (exit 6), with `next` naming the smallest cap that starts one record. A workspace out of credits starts nothing either (`out_of_credits`, exit 6).\n- **`--wait`** follows each started run, up to 8 reads at a time, until it leaves `queued`, `running` and `waiting`, or `--timeout` (90s, 10m, 1h; default 30m) passes. A run still `waiting` at the timeout is reported as `waiting`. `--timeout` goes with `--wait`.\n- **`--out <results.csv>`** (needs `--wait`) writes one row per input record when the batch ends: `row, id, status, runId, runStatus, creditsCharged, missReason, error`, then one column per step id holding that step\'s output as compact JSON. The path is checked before the first request: its folder must exist, and an existing file is refused (`file_exists`, exit 7) unless it is this run\'s own.\n- **Summary.** One JSON object with `records`, `started`, `deduplicated`, `notStarted`, `succeeded`, `failed`, `waiting`, `missed` (reason to count), `creditsCharged` (`"pending"` without `--wait` or while runs are open), `cap`, `resultsCsv`, `appUrl` (the workflow\'s page in the app, in the run\'s workspace: `https://app.ken.so/<workspaceId>/workflows/<id>`) and `next`, and the same counts on one stderr line. With `--wait`, a run that failed makes `next` its `kenso workflow-runs logs <runId>`.\n- **Never twice.** A run is known by its input file\'s content, the workflow it resolves to and the workspace, not by how the command was typed: `ids.txt`, `./ids.txt` and a copy of the file are one input, and so are a bound file and its workflow id. The same run again starts nothing and answers from the finished run\'s folder with `alreadyDone: true`; with `--wait` and `--out` it reads that run\'s runs and writes the results file. A run on that input that would start records differently (another `--max-credits`, or a people file whose matches changed) is refused with `already_started` (exit 7) once the earlier run sent starts: `not-started.txt` in its folder holds the ids it did not start, and `next` runs only those. A run on that input that another kenso process is running now is `run_in_progress` (exit 7).\n\n## The run folder\n\nEach applied run writes a run folder (`~/.kenso/runs/<id>`) that records every chunk\'s response, as every batch command does: see [Batch runs](batch.md). `kenso runs resume <runId>` never resends a chunk it has an answer for. A chunk that was sent and has no recorded answer is not resent either: resume stops with `chunk_outcome_unknown` (exit 5), the chunk\'s first and last row, and `next: kenso workflow-runs list --workflow-id <id> --created-after <chunk start time>`, so you can see what started.\n\n```bash\nkenso runs resume <runId>\nkenso workflow-runs list --workflow-id 412 --created-after 2026-11-21T10:00:00Z\n```\n\n## Read a run\n\n```bash\nkenso workflow-runs logs <runId>\nkenso workflow-runs logs <runId> --step qualify --full\n```\n\nOne row per step run in start order: `{nodeId, stepType, status, attempt, startedAt, endedAt, ms, credits, error}`, NDJSON when piped. `--step` keeps one node; `--full` adds each step\'s `input`, `output` and `attempts`. A header line on stderr gives the run\'s status, workflow, record and the credits it charged, and `needs attention: <reason>` when one is set. A failed run ends with `next: kenso workflow-runs restart --run-id <id> --dry-run`, because `retry` refuses a run that has ended.\n\n## Step outputs are kept 7 days\n\nA succeeded run\'s step outputs are dropped 7 days after it finishes, unless the workflow keeps success details. `--out` writes them when the batch ends, so run with `--wait --out` when you need the results later.\n\n## Exit codes\n\n| Exit | When |\n|---|---|\n| 0 | Done. For `run`, every record started and, with `--wait`, none failed |\n| 1 | `test`: the test did not pass |\n| 2 | Usage: `workflow_not_bound`, `folder_file_invalid`, `folder_file_untrusted`, `workspace_mismatch`, `not_runnable_on_records`, `ids_required`, or `--publish` without `--expected-hash` under a coding agent |\n| 4 | `test`: `runtime_off`, the workspace cannot run workflows yet |\n| 5 | `check` found the file not valid, the server refused a definition (`invalid_definition`), `run` has records that failed, were not found or were not started, or resume met `chunk_outcome_unknown` |\n| 6 | `run`: the cap started nothing (`cap_too_low`), or the workspace is out of credits |\n| 7 | A conflict: `file_exists`, `already_bound`, `draft_out_of_sync`, `hash_mismatch`, `test_required`, `version_conflict`, `unpublished_changes`, `invalid_state`, an existing `--out` file, or a `run` on an input an earlier run started (`already_started`) or another process is running (`run_in_progress`) |\n\nEvery error is one JSON line on stderr with `code`, `message`, `hint` and `next`: see [Output and errors](output-and-errors.md).\n';
9833
9954
  }
9834
9955
  });
9835
9956
 
@@ -9837,7 +9958,7 @@ var init_workflows = __esm({
9837
9958
  var SKILL_default;
9838
9959
  var init_SKILL = __esm({
9839
9960
  "skill/kenso/SKILL.md"() {
9840
- SKILL_default = '---\nname: kenso\ndescription: "Use for any outbound work in Kenso: leads, lists, campaigns, sequences, replies, accounts, signals, workflows, Studio, sending setup, reporting. Routes to the Kenso skill for the job and sets the rules for workspace, spend, sends and the final reply."\n---\n\n# Kenso: start here\n\nThis skill comes first for any work in Kenso. It sends you to the skill for the job and sets the rules every other Kenso skill follows: the workspace, spend, sends and the final reply. When another skill says "the spend rules", it means section 5 below.\n\n## 1. First\n\n```bash\nkenso doctor\nkenso whoami\nkenso workspace list\nkenso credits balance\n```\n\n- `kenso doctor` checks the CLI, the key, the skills and the MCP. When a check fails, run its `next` before anything else.\n- `kenso whoami` shows the workspace this folder and key use (`activeWorkspace`, with its `id` and `name`) and where it comes from (`workspaceSource`); `kenso workspace list` lists every workspace the key reaches. Before any change, tell the person: "I will work in <name> (<id>)."\n- `kenso credits balance` shows the credits `available`. Read it before you plan anything that charges.\n\n## 2. The loop\n\n```bash\nkenso discover "find work emails for a list of people"\nkenso describe email-finds create\n```\n\n1. `kenso discover` with the request in plain words finds the command, doc, skill or workflow step for it, offline. Each hit has its `effect` (read, write, spend, send or destructive), its cost line and the `describe` command to run next.\n2. `kenso describe <resource> <action>` prints the command\'s flags, body, `effect` and `cost` as JSON.\n3. Run it with `--dry-run` and read the plan: what it would send and, for paid work, `credits` with `needed`, `available` and `sufficient`.\n4. Run it for real only as the rules below allow, with the plan\'s `next`.\n\nWhile you only look around, set `KENSO_READ_ONLY=1`: any command that is not a read is then refused before it sends anything, and a `--dry-run` still prints its plan.\n\n## 3. Which skill\n\nLoad a skill with `kenso skill show` and its name, for example `kenso skill show workflows`, or with `load_skill` through the Kenso MCP. `kenso skill list` shows the ones this workspace can use.\n\n| Need | Skill |\n|---|---|\n| Count my market, size it and build the list | `tam-builder` |\n| People-search filters for a campaign | `ken-search` |\n| Build a campaign from an ICP and an offer, to launch-ready | `create-campaign` |\n| Why a campaign is up or down; my best and worst campaign | `campaign-diagnosis` |\n| Fix the email that is not working in a live campaign | `campaign-improvement` |\n| Go through replies, draft answers, offer meeting times | `reply-handling` |\n| What needs my attention: what failed, stalled or came out wrong, and what to fix first | `kenso-triage` |\n| My Today queue: the touches due today, to draft, snooze or skip | `today-review` |\n| Bounces up or sends dropped | `deliverability-guard` |\n| Sending setup: inboxes, domains, LinkedIn accounts, the link host | `delivery-setup` |\n| Connect my own sending domains | `connect-domains` |\n| Review or order sending domains | `domain-selection` |\n| Inbox limits, display names, signatures, reply forwarding | `inbox-configuration` |\n| How many domains and inboxes I need | `infra-planning` |\n| Set up a new workspace | `setup-workspace` |\n| Sign up from the agent, with no workspace yet | `onboarding-signup` |\n| Company, offer and voice files in Knowledge | `knowledge-setup` |\n| Edit the skills in Knowledge > Skills | `skill-editor` |\n| Target accounts: add, research, map who buys, plan touches | `accounts` |\n| A one-page brief on an account before a call | `account-brief` |\n| Hiring, funding, job changes, website visits or replies that start outreach | `signals` |\n| Outreach around a conference or trade show | `event-outbound` |\n| A job opening turned into a candidate campaign | `role-intake` |\n| Someone\'s social profiles and recent posts | `social-data` |\n| Build, test and run a workflow, as a file or in the app | `workflows` |\n| Build or edit a Studio template | `studio-template` |\n| Fill a Studio page for an account or a candidate | `studio-asset` |\n| Prep for a call, then follow it up | `meeting-prep-and-followup` |\n| A MEDDIC summary of a call | `meddic-summary` |\n| The objections raised on a call | `objection-log` |\n| The next-steps email after a call | `next-step-email` |\n| The handoff to the AE after a call | `handoff-to-ae` |\n| Open deals by stage, and the stuck ones | `pipeline-review` |\n| The weekly or monthly results report | `report` |\n| The person asks for the start interview | `kenso-start` |\n\n**CLI or MCP.** Use the CLI for work from a file, or on more than about 50 records: imports, updates, exports and workflow runs. The kenso-cli skill has those commands; `kenso agent setup` installs it beside this one. For one record or a question, the MCP is fine.\n\n**What to offer.** Look first:\n\n```bash\nkenso campaigns list --limit 5\n```\n\nA workspace with campaigns: offer "Diagnose my best and worst campaign" (`campaign-diagnosis`) and "Triage today\'s replies" (`reply-handling`). A new workspace: offer the starter menu.\n\n1. Count my market: how many companies and people match my ICP?\n2. Check my sending setup and tell me what to fix before I launch.\n3. Draft a campaign for my company from my website and show it to me before anything is sent.\n4. Tell me what you want to get done.\n\nThey lead to `tam-builder`, `delivery-setup` and `create-campaign`; for the fourth, find the skill in the table or run `kenso discover` with the person\'s words.\n\n## 4. Workspace\n\nName the workspace before the first change, and again whenever it changes. A yes that does not name the workspace is not a yes: ask again, with its name. Under a coding agent, every command that is not a read prints `workspace: <id> (<source>)` on stderr: stop when it is not the workspace the person approved. A `kenso.json` in a folder holds that folder\'s workspace.\n\n## 5. Spend\n\nThese rules hold in every Kenso skill.\n\n- A bounded request ("find emails for these 200 people") covers that scope and nothing wider. An open one ("find me leads") needs a row count and a budget from the person first.\n- Sample first. When a paid step covers more than 25 records, or the estimate\'s `credits.needed` is over 10, run 3 to 5 records first, show the result and the projected cost of the rest, and ask before the rest. These four numbers are thresholds of this contract, not prices.\n- Prices come from a `--dry-run`, `kenso credits quote` or `kenso credits rate-card`, never from memory or from a skill.\n- `Effect: write.` in a command\'s help is not proof that it is free: not every route that charges is marked. The dry run or `kenso credits quote` is the authority.\n- Ask once, with one approval block, and wait for the yes:\n\n```text\nPlan: <what will run>\nRecords: <how many, and from where>\nEstimate: <needed> of <available> available credits (from the dry run)\nCap: --max-credits <the cap you will set>\nReply yes to run it.\n```\n\n- On `kenso workflows run`, always set `--max-credits` to the cap in the approval block.\n- Out of credits (`sufficient: false` in the plan, or a run that stops because the credits ran out): stop, show what finished, and give the billing link, https://app.ken.so/<workspace id>/settings/billing. Never retry in a loop.\n\n```bash\nkenso credits quote --kind leads --count 200\nkenso credits rate-card --action email_found\n```\n\n## 6. Sends\n\nSends, launches, CRM writes and schedule changes need a yes that names the campaign or the record set ("launch campaign 812", "update these 40 deals in the CRM"). A yes to a plan is not a yes to send. A delete, archive or remove runs with `--yes` only after the person said yes to that delete.\n\n## 7. Workflows, signals and tools\n\n- A **workflow** is a saved set of steps that runs on each record (an account, a person, a lead), started by hand, on a schedule or by a signal. The `workflows` skill builds one; its file loop is `kenso skill show workflows --reference files.md`.\n- A **signal** is an event that starts a workflow: hiring, funding, a job change, a website visit, a reply. `kenso signals types` lists them; the `signals` skill watches for them.\n- A **tool** is one command you run yourself (`kenso discover` finds it) or one MCP operation.\n\nThe first run of a workflow template is five commands: `init --template`, `push`, `test`, `push --publish --expected-hash` with the hash `test` printed, and `run`. Check the file after every edit, and dry-run the run before the paid one:\n\n```bash\nkenso workflow-templates list\nkenso workflows init qualify --template <templateKey>\nkenso workflows push qualify.workflow.json\nkenso workflows check qualify.workflow.json --mode publish\nkenso workflows test qualify.workflow.json --record account:<accountId>\nkenso workflows push qualify.workflow.json --publish --expected-hash <definitionHash>\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits <cap> --dry-run\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits <cap> --wait --out results.csv --yes\n```\n\n## 8. Your own agent plan: kenso work\n\nWhere your workspace has it, `kenso work` runs Kenso AI steps on your own Claude or Codex plan at 0 Kenso AI credits. Check with `kenso work status`: it lists what waits for your agent, and answers `not_found` when the workspace does not have it yet. When most of an estimate is AI steps, name this to the person as an option before they approve.\n\n```bash\nkenso work status\n```\n\n## 9. The final reply\n\nEnd every job with this reply, in this order:\n\n```text\nOutcome: <what ran, on how many records, what it produced>\nMisses: <count and reason for each kind of miss, or none>\nLinks: <the app page> and <the results file>\nCredits spent: <from the run summary\'s creditsCharged, or kenso credits usage --run <runId>>\nNext: <the one next step you recommend>\n```\n\n## No Kenso account yet\n\nThese steps run on the Kenso MCP server, which signs in with a Kenso account. If the user has none, send them to https://app.ken.so/get-started to create one, then sign in when the agent asks.\n';
9961
+ SKILL_default = '---\nname: kenso\ndescription: "Use for any outbound work in Kenso: leads, lists, campaigns, sequences, replies, accounts, signals, workflows, Studio, sending setup, reporting. Routes to the Kenso skill for the job and sets the rules for workspace, spend, sends and the final reply."\n---\n\n# Kenso: start here\n\nThis skill comes first for any work in Kenso. It sends you to the skill for the job and sets the rules every other Kenso skill follows: the workspace, spend, sends and the final reply. When another skill says "the spend rules", it means section 5 below.\n\n## 1. First\n\n```bash\nkenso doctor\nkenso whoami\nkenso workspace list\nkenso credits balance\n```\n\n- `kenso doctor` checks the CLI, the key, the skills and the MCP. When a check fails, run its `next` before anything else.\n- No key, or `key_valid` failed: hand the sign-in to the person. `kenso login --no-wait` prints a link and a code; give both to the person, and once they say they approved it, run `kenso auth wait`.\n- `kenso whoami` shows the workspace this folder and key use (`activeWorkspace`, with its `id` and `name`) and where it comes from (`workspaceSource`); `kenso workspace list` lists every workspace the key reaches. Before any change, tell the person: "I will work in <name> (<id>)."\n- `kenso credits balance` shows the credits `available`. Read it before you plan anything that charges.\n\n## 2. The loop\n\n```bash\nkenso discover "find work emails for a list of people"\nkenso describe email-finds create\n```\n\n1. `kenso discover` with the request in plain words finds the command, doc, skill or workflow step for it, offline. Each hit has its `effect` (read, write, spend, send or destructive), its cost line and the `describe` command to run next.\n2. `kenso describe <resource> <action>` prints the command\'s flags, body, `effect` and `cost` as JSON.\n3. Run it with `--dry-run` and read the plan: what it would send and, for paid work, `credits` with `needed`, `available` and `sufficient` (`null` where the CLI could not read or price it). A `null` `needed` is unknown, never free: ask before you run it.\n4. Run it for real only as the rules below allow, with the plan\'s `next`.\n\nWhile you only look around, set `KENSO_READ_ONLY=1`: any command that is not a read is then refused before it sends anything, and a `--dry-run` still prints its plan.\n\n## 3. Which skill\n\nLoad a skill with `kenso skill show` and its name, for example `kenso skill show workflows`, or with `load_skill` through the Kenso MCP. `kenso skill list` shows the ones this workspace can use.\n\n| Need | Skill |\n|---|---|\n| Count my market, size it and build the list | `tam-builder` |\n| People-search filters for a campaign | `ken-search` |\n| Build a campaign from an ICP and an offer, to launch-ready | `create-campaign` |\n| Why a campaign is up or down; my best and worst campaign | `campaign-diagnosis` |\n| Fix the email that is not working in a live campaign | `campaign-improvement` |\n| Go through replies, draft answers, offer meeting times | `reply-handling` |\n| What needs my attention: what failed, stalled or came out wrong, and what to fix first | `kenso-triage` |\n| My Today queue: the touches due today, to draft, snooze or skip | `today-review` |\n| Bounces up or sends dropped | `deliverability-guard` |\n| Sending setup: inboxes, domains, LinkedIn accounts, the link host | `delivery-setup` |\n| Connect my own sending domains | `connect-domains` |\n| Review or order sending domains | `domain-selection` |\n| Inbox limits, display names, signatures, reply forwarding | `inbox-configuration` |\n| How many domains and inboxes I need | `infra-planning` |\n| Set up a new workspace | `setup-workspace` |\n| Sign up from the agent, with no workspace yet | `onboarding-signup` |\n| Company, offer and voice files in Knowledge | `knowledge-setup` |\n| Edit the skills in Knowledge > Skills | `skill-editor` |\n| Target accounts: add, research, map who buys, plan touches | `accounts` |\n| A one-page brief on an account before a call | `account-brief` |\n| Hiring, funding, job changes, website visits or replies that start outreach | `signals` |\n| Outreach around a conference or trade show | `event-outbound` |\n| A job opening turned into a candidate campaign | `role-intake` |\n| Someone\'s social profiles and recent posts | `social-data` |\n| Build, test and run a workflow, as a file or in the app | `workflows` |\n| Build or edit a Studio template | `studio-template` |\n| Fill a Studio page for an account or a candidate | `studio-asset` |\n| Prep for a call, then follow it up | `meeting-prep-and-followup` |\n| A MEDDIC summary of a call | `meddic-summary` |\n| The objections raised on a call | `objection-log` |\n| The next-steps email after a call | `next-step-email` |\n| The handoff to the AE after a call | `handoff-to-ae` |\n| Open deals by stage, and the stuck ones | `pipeline-review` |\n| The weekly or monthly results report | `report` |\n| The person asks for the start interview | `kenso-start` |\n\n**CLI or MCP.** Use the CLI for work from a file, or on more than about 50 records: imports, updates, exports and workflow runs. The kenso-cli skill has those commands; `kenso agent setup` installs it beside this one. For one record or a question, the MCP is fine.\n\n**What to offer.** Look first:\n\n```bash\nkenso campaigns list --limit 5\n```\n\nA workspace with campaigns: offer "Diagnose my best and worst campaign" (`campaign-diagnosis`) and "Triage today\'s replies" (`reply-handling`). A new workspace: offer the starter menu.\n\n1. Count my market: how many companies and people match my ICP?\n2. Check my sending setup and tell me what to fix before I launch.\n3. Draft a campaign for my company from my website and show it to me before anything is sent.\n4. Tell me what you want to get done.\n\nThey lead to `tam-builder`, `delivery-setup` and `create-campaign`; for the fourth, find the skill in the table or run `kenso discover` with the person\'s words.\n\n## 4. Workspace\n\nName the workspace before the first change, and again whenever it changes. A yes that does not name the workspace is not a yes: ask again, with its name. Under a coding agent, every command that is not a read prints `workspace: <id> (<source>)` on stderr: stop when it is not the workspace the person approved. A `kenso.json` in a folder holds that folder\'s workspace.\n\n## 5. Spend\n\nThese rules hold in every Kenso skill.\n\n- A bounded request ("find emails for these 200 people") covers that scope and nothing wider. An open one ("find me leads") needs a row count and a budget from the person first.\n- Sample first. When a paid step covers more than 25 records, or the estimate\'s `credits.needed` is over 10, run 3 to 5 records first, show the result and the projected cost of the rest, and ask before the rest. These four numbers are thresholds of this contract, not prices.\n - A workflow samples on the full ids file, never on a separate file of a few ids, which the full run would start again: `kenso workflows run` with a `--max-credits` that covers 3 to 5 records starts only those. After the yes, run the same command with only `--max-credits` changed: it stops with `already_started`, and its `next` runs only the records the sample did not start.\n - Any other paid batch: sample with a file of 3 to 5 rows, then run the rest from a file without them.\n- Prices come from a `--dry-run`, `kenso credits quote` or `kenso credits rate-card`, never from memory or from a skill.\n- `Effect: write.` or `Effect: send.` in a command\'s help is not proof that it is free: not every route that charges is marked, and `kenso workflows run` is a send that charges for its steps. The dry run or `kenso credits quote` is the authority.\n- Ask once, with one approval block, and wait for the yes:\n\n```text\nPlan: <what will run>\nRecords: <how many, and from where>\nEstimate: <needed> of <available> available credits (from the dry run)\nCap: --max-credits <the cap you will set>\nReply yes to run it.\n```\n\n- On `kenso workflows run`, always set `--max-credits` to the cap in the approval block.\n- Out of credits (`sufficient: false` in the plan, or a run that stops because the credits ran out): stop, show what finished, and give the billing link, https://app.ken.so/<workspace id>/settings/billing. Never retry in a loop.\n\n```bash\nkenso credits quote --kind leads --count 200\nkenso credits rate-card --action email_found\n```\n\n## 6. Sends\n\nSends, launches, CRM writes and schedule changes need a yes that names the campaign or the record set ("launch campaign 812", "update these 40 deals in the CRM"). A yes to a plan is not a yes to send. A delete, archive or remove runs with `--yes` only after the person said yes to that delete.\n\n## 7. Workflows, signals and tools\n\n- A **workflow** is a saved set of steps that runs on each record (an account, a person, a lead), started by hand, on a schedule or by a signal. The `workflows` skill builds one; its file loop is `kenso skill show workflows --reference files.md`.\n- A **signal** is an event that starts a workflow: hiring, funding, a job change, a website visit, a reply. `kenso signals types` lists them; the `signals` skill watches for them.\n- A **tool** is one command you run yourself (`kenso discover` finds it) or one MCP operation.\n\nThe first run of a workflow template is five commands: `init --template`, `push`, `test`, `push --publish --expected-hash` with the hash `test` printed, and `run`. Check the file after every edit, and dry-run the run before the paid one:\n\n```bash\nkenso workflow-templates list\nkenso workflows init qualify --template <templateKey>\nkenso workflows push qualify.workflow.json\nkenso workflows check qualify.workflow.json --mode publish\nkenso workflows test qualify.workflow.json --record account:<accountId>\nkenso workflows push qualify.workflow.json --publish --expected-hash <definitionHash>\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits <cap> --dry-run\nkenso workflows run qualify.workflow.json --ids ids.txt --max-credits <cap> --wait --out results.csv --yes\n```\n\n## 8. Your own agent plan: kenso work\n\nWhere your workspace has it, `kenso work` runs Kenso AI steps on your own Claude or Codex plan at 0 Kenso AI credits. Check with `kenso work status`: it lists what waits for your agent, and answers `not_found` when the workspace does not have it yet. When most of an estimate is AI steps, name this to the person as an option before they approve.\n\n```bash\nkenso work status\n```\n\n## 9. The final reply\n\nEnd every job with this reply, in this order:\n\n```text\nOutcome: <what ran, on how many records, what it produced>\nMisses: <count and reason for each kind of miss, or none>\nLinks: <the app page> and <the results file>\nCredits spent: <from the run summary\'s creditsCharged, or kenso credits usage --run <runId>>\nNext: <the one next step you recommend>\n```\n\n## No Kenso account yet\n\nThese steps run on the Kenso MCP server, which signs in with a Kenso account. If the user has none, send them to https://app.ken.so/get-started to create one, then sign in when the agent asks.\n';
9841
9962
  }
9842
9963
  });
9843
9964
 
@@ -9845,7 +9966,7 @@ var init_SKILL = __esm({
9845
9966
  var SKILL_default2;
9846
9967
  var init_SKILL2 = __esm({
9847
9968
  "skill/kenso-cli/SKILL.md"() {
9848
- SKILL_default2 = '---\nname: kenso-cli\ndescription: The Kenso CLI (kenso) for work from a file (of any size, even a few ids) or over about 50 records - import, update, remove (delete), pause, tag or export leads, import CRM accounts and people, edit Studio templates as local files and fill them, run an API operation per file row, resume an interrupted run, write the Kenso AI work a workspace gave to its own coding agent (My agent, with kenso work run, or work pull and submit with subagents), sign in with a key from a variable (pipe it to kenso auth login --with-key, no check first). For records listed in the message (under about 50), one record or a question, use the Kenso MCP.\n---\n\n1. Every write runs first with `--dry-run`; apply with the plan\'s `next` (a delete, archive or remove applies with `--yes`). `--yes` at once only to continue an interrupted run or apply what the person confirmed. A command with no dry run refuses `--dry-run` (exit 2, nothing ran): read its `--help`, then run it without.\n2. Many rows: one command on the file as it is (`--file`, `--ids`, `--each`). Run kenso only: no python, awk or shell tests, not even on a file or variable.\n3. Any output\'s `next` is the command to run; errors are JSON on stderr. `--force` only with the person\'s OK.\n4. Ids are flags: `--campaign-id 812` (or `--campaign 812`, the same flag). `--workspace <id>`; by name `kenso workspace list --search acme`. `--json` is `-o json`; `--query` takes JMESPath (there is no `--jq`). Other commands: `kenso --help`; `kenso api <METHOD> <path>` only when none fits.\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run # skips leads already in; --map \'{"Pain": "customVariables.pain_point", "Notes": null}\'; over 200 MB --server-import\nkenso contacts update --file edits.csv --match id --dry-run # also one lead; or --match email --campaign 812\nkenso contacts remove --ids ids.txt --dry-run # also pause, resume, restore; over 1,000: --confirm <count>\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --dry-run # also pause, resume; 2 = contains; no search first\nkenso contacts tag --tag 31 --ids ids.txt --dry-run # tag, restore: --ids only, so first kenso contacts list --campaign-id 812 --all -o ids > ids.txt\nkenso contact-imports create --source campaign --source-campaign-id 10601 --campaign-id 812 --dry-run # copy another campaign\'s leads in\nkenso contacts export --campaign 812 --out leads.csv # a segment: kenso contact-exports create --segment-id 55\nkenso runs resume <runId> # an interrupted run; terminal lost: kenso runs list finds it. A changed file is a new run\nkenso accounts import --file accounts.csv --dry-run # companies; a file of people: kenso people import --file people.csv\nkenso studio push 12 --dir ./tpl # to preview local edits push first (draft; live needs --publish), then studio preview 12\nkenso studio fill 12 --accounts ids.txt --dry-run # or --campaign 10546 --contacts leads.csv\nkenso opportunities update --each rows.csv --dry-run # any API command on a file of rows (CSV or JSONL; keys fill flags and body). One record: kenso campaigns update --campaign-id 812 --name Q4 --dry-run\nkenso mcp call list_skills # only to list Ken\'s skills\nkenso logs tail --status 4xx,5xx --since 10m # stream the workspace\'s failed API calls, one line each; Ctrl-C stops (exit 4 = not on for the workspace yet)\nkenso connect inbox --provider google # also calendar, crm, github, linkedin ...: hand the printed link to the person (only they can sign in), it waits and prints the connection\nkenso onboarding-builds events --build-id obd_2x --until done,error # live streams: one JSON line per event, reconnects itself\n```\n\nCharges: follow the kenso skill\'s spend rules; every dry run prints the credit estimate. `pinned_by_user`: with the person\'s OK, rerun with `--overwrite-pinned`. Workflows: `kenso docs workflows` first; secrets only as `{{secrets.NAME}}`. Key: `KENSO_API_KEY`, or pipe a variable, no check: `printf \'%s\' "$KEY" | kenso auth login --with-key`; never in a flag, output or file.\n\n## Work (beta): My agent\n\nA workspace can set a kind of Kenso AI work (personalization, qualification, segmentation, rewriting, meeting brief, call brief, workflow prompt) to My agent in Settings > AI work: then it waits for the person\'s own coding agent, at 0 Kenso AI credits. The `kenso work` commands take no `--dry-run`. Never read the items\' text into the chat: the files carry it.\n\n```bash\nkenso work status # what waits, per kind\nkenso work run --agent claude # does it all: claims, runs headless agents, submits; stops when the queue is empty. Other agents need --allow-unconfined; exit 6 = the plan\'s usage limit\nkenso work pull --files 4 --per-file 10 # by hand: prints the work file paths, never the items\nkenso work submit <dir>/*.answers.json # pull\'s next; exit 5 = some answers rejected (see each <claimId>.results.json)\nkenso work release <claimId> # give back work you will not finish\n```\n\nBy hand in a chat: run `kenso work pull`, then give each work file to its own subagent with only its path ("Read this work file and write its answers file as its rules say"), then run pull\'s `next`. More: `kenso docs work`.\n\n## Setup\n\n`kenso` missing: `curl -fsSL https://ken.so/install.sh | sh` (macOS or Linux, no Node needed) or `npm i -g kenso` (Node 22 or newer), or run a command as `npx -y kenso@latest <command>`. Then `kenso auth login` (the person approves in the browser) and `kenso doctor`. `kenso agent setup -y` installs this skill and the Kenso MCP server (`https://mcp.ken.so/mcp`) for the agent; the person signs in to the MCP once in the agent.\n\n## No Kenso account yet\n\nThe CLI signs in with a Kenso API key. If the user has no Kenso account, send them to https://app.ken.so/get-started to create one, then create a key in Kenso at Settings > Integrations > API keys.\n';
9969
+ SKILL_default2 = '---\nname: kenso-cli\ndescription: The Kenso CLI (kenso) for work from a file (of any size, even a few ids) or over about 50 records - import, update, remove (delete), pause, tag or export leads, import CRM accounts and people, edit Studio templates as local files and fill them, run an API operation per file row, resume an interrupted run, write the Kenso AI work a workspace gave to its own coding agent (My agent, with kenso work run, or work pull and submit with subagents), sign in with a key from a variable (pipe it to kenso auth login --with-key, no check first). For records listed in the message (under about 50), one record or a question, use the Kenso MCP.\n---\n\n1. Every write runs first with `--dry-run`; apply with the plan\'s `next` (a delete, archive or remove applies with `--yes`). `--yes` at once only to continue an interrupted run or apply what the person confirmed. A command with no dry run refuses `--dry-run` (exit 2, nothing ran): read its `--help`, then run it without.\n2. Many rows: one command on the file as it is (`--file`, `--ids`, `--each`). Run kenso only: no python, awk or shell tests, not even on a file or variable.\n3. Any output\'s `next` is the command to run; errors are JSON on stderr. `--force` only with the person\'s OK.\n4. Ids are flags: `--campaign-id 812` (or `--campaign 812`, the same flag). `--workspace <id>`; by name `kenso workspace list --search acme`. `--json` is `-o json`; `--query` takes JMESPath (there is no `--jq`). Other commands: `kenso --help`; `kenso api <METHOD> <path>` only when none fits.\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run # skips leads already in; --map \'{"Pain": "customVariables.pain_point", "Notes": null}\'; over 200 MB --server-import\nkenso contacts update --file edits.csv --match id --dry-run # also one lead; or --match email --campaign 812\nkenso contacts remove --ids ids.txt --dry-run # also pause, resume, restore; over 1,000: --confirm <count>\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --dry-run # also pause, resume; 2 = contains; no search first\nkenso contacts tag --tag 31 --ids ids.txt --dry-run # tag, restore: --ids only, so first kenso contacts list --campaign-id 812 --all -o ids > ids.txt\nkenso contact-imports create --source campaign --source-campaign-id 10601 --campaign-id 812 --dry-run # copy another campaign\'s leads in\nkenso contacts export --campaign 812 --out leads.csv # a segment: kenso contact-exports create --segment-id 55\nkenso runs resume <runId> # an interrupted run; terminal lost: kenso runs list finds it. A changed file is a new run\nkenso accounts import --file accounts.csv --dry-run # companies; a file of people: kenso people import --file people.csv\nkenso studio push 12 --dir ./tpl # to preview local edits push first (draft; live needs --publish), then studio preview 12\nkenso studio fill 12 --accounts ids.txt --dry-run # or --campaign 10546 --contacts leads.csv\nkenso opportunities update --each rows.csv --dry-run # any API command on a file of rows (CSV or JSONL; keys fill flags and body). One record: kenso campaigns update --campaign-id 812 --name Q4 --dry-run\nkenso mcp call list_skills # only to list Ken\'s skills\nkenso logs tail --status 4xx,5xx --since 10m # stream the workspace\'s failed API calls, one line each; Ctrl-C stops (exit 4 = not on for the workspace yet)\nkenso connect inbox --provider google # also calendar, crm, github, linkedin ...: hand the printed link to the person (only they can sign in), it waits and prints the connection\nkenso onboarding-builds events --build-id obd_2x --until done,error # live streams: one JSON line per event, reconnects itself\n```\n\nCharges: follow the kenso skill\'s spend rules; the dry run of a `spend` command (one call or an `--each` file) and of `kenso workflows run` prints `credits` (`needed`, `available`, `sufficient`; `null` where it cannot tell, and an unknown `needed` is never free). `pinned_by_user`: with the person\'s OK, rerun with `--overwrite-pinned`. Workflows: `kenso docs workflows` first; secrets only as `{{secrets.NAME}}`. Key: `KENSO_API_KEY`, or pipe a variable, no check: `printf \'%s\' "$KEY" | kenso auth login --with-key`; never in a flag, output or file.\n\n## Work (beta): My agent\n\nA workspace can set a kind of Kenso AI work (personalization, qualification, segmentation, rewriting, meeting brief, call brief, workflow prompt) to My agent in Settings > AI work: then it waits for the person\'s own coding agent, at 0 Kenso AI credits. The `kenso work` commands take no `--dry-run`. Never read the items\' text into the chat: the files carry it.\n\n```bash\nkenso work status # what waits, per kind\nkenso work run --agent claude # does it all: claims, runs headless agents, submits; stops when the queue is empty. Other agents need --allow-unconfined; exit 6 = the plan\'s usage limit\nkenso work pull --files 4 --per-file 10 # by hand: prints the work file paths, never the items\nkenso work submit <dir>/*.answers.json # pull\'s next; exit 5 = some answers rejected (see each <claimId>.results.json)\nkenso work release <claimId> # give back work you will not finish\n```\n\nBy hand in a chat: run `kenso work pull`, then give each work file to its own subagent with only its path ("Read this work file and write its answers file as its rules say"), then run pull\'s `next`. More: `kenso docs work`.\n\n## Setup\n\n`kenso` missing: `curl -fsSL https://ken.so/install.sh | sh` (macOS or Linux, no Node needed) or `npm i -g kenso` (Node 22 or newer), or run a command as `npx -y kenso@latest <command>`. Then sign in: `kenso login --no-wait` prints a link and a code for the person to open and approve, then `kenso auth wait` saves the key. Then `kenso doctor`. `kenso agent setup -y` installs this skill and the Kenso MCP server (`https://mcp.ken.so/mcp`) for the agent; the person signs in to the MCP once in the agent.\n\n## No Kenso account yet\n\nThe CLI signs in with a Kenso API key. If the user has no Kenso account, send them to https://app.ken.so/get-started to create one, then create a key in Kenso at Settings > Integrations > API keys.\n';
9849
9970
  }
9850
9971
  });
9851
9972
 
@@ -9913,10 +10034,10 @@ var init_bundled = __esm({
9913
10034
  });
9914
10035
 
9915
10036
  // src/commands/skill/clients.ts
9916
- import { homedir as homedir2 } from "node:os";
10037
+ import { homedir as homedir3 } from "node:os";
9917
10038
  import { join as join12 } from "node:path";
9918
10039
  function home(env) {
9919
- return env.HOME?.trim() || env.USERPROFILE?.trim() || homedir2();
10040
+ return env.HOME?.trim() || env.USERPROFILE?.trim() || homedir3();
9920
10041
  }
9921
10042
  function claudeDir(env) {
9922
10043
  return env.CLAUDE_CONFIG_DIR?.trim() || join12(home(env), ".claude");
@@ -9989,10 +10110,14 @@ var init_shipped = __esm({
9989
10110
  "8e79d18098e6ed3b79c3bce771a46180b50e9ed1b741e64ffcb301601282eb12",
9990
10111
  "fcac2e80b3d818394465a491bad232025d1c201515ef7fb778e4aa51669b3e61",
9991
10112
  "42fa3f163ab9aa70260040b443830c57dc7926e935a557c40896038e8817b088",
9992
- "b34e186f56f36b509bffa0dea2ee78b09e91654b90a659d6665563df4fa88f76"
10113
+ "b34e186f56f36b509bffa0dea2ee78b09e91654b90a659d6665563df4fa88f76",
10114
+ "df7d86e0af12727cf15cf0620f26ef4fe9aac63f0180f3594e4d357cf14b40d2",
10115
+ "812bb97591cefa7eb23596105ce63dfd382c0bd4c68e8b5d179775e9b72e927a"
9993
10116
  ],
9994
10117
  kenso: [
9995
- "6fb333a826726d51ba2ea3927745f843343490c8aa9098e5da682d24172323f7"
10118
+ "6fb333a826726d51ba2ea3927745f843343490c8aa9098e5da682d24172323f7",
10119
+ "7d88215cf4e6eb7aaeb28d22839fc3006c57a0491e12dde86db7623b635d6f90",
10120
+ "875c8ed2738ecdc963377be449c21f40c623a0750baf361d3e51b22818cf8e9d"
9996
10121
  ]
9997
10122
  };
9998
10123
  }
@@ -11301,7 +11426,7 @@ var status_exports = {};
11301
11426
  __export(status_exports, {
11302
11427
  default: () => status_default
11303
11428
  });
11304
- var EXPIRY_WARNING_DAYS, DAY_MS, command11, status_default;
11429
+ var EXPIRY_WARNING_DAYS, DAY_MS2, command11, status_default;
11305
11430
  var init_status = __esm({
11306
11431
  "src/commands/auth/status.ts"() {
11307
11432
  "use strict";
@@ -11311,7 +11436,7 @@ var init_status = __esm({
11311
11436
  init_exit_codes();
11312
11437
  init_http();
11313
11438
  EXPIRY_WARNING_DAYS = 14;
11314
- DAY_MS = 24 * 60 * 60 * 1e3;
11439
+ DAY_MS2 = 24 * 60 * 60 * 1e3;
11315
11440
  command11 = {
11316
11441
  resource: "auth",
11317
11442
  action: "status",
@@ -11370,8 +11495,8 @@ var init_status = __esm({
11370
11495
  }
11371
11496
  if (keyExpiresAt) {
11372
11497
  const left = Date.parse(keyExpiresAt) - Date.now();
11373
- if (!Number.isNaN(left) && left < EXPIRY_WARNING_DAYS * DAY_MS) {
11374
- const days = Math.max(0, Math.ceil(left / DAY_MS));
11498
+ if (!Number.isNaN(left) && left < EXPIRY_WARNING_DAYS * DAY_MS2) {
11499
+ const days = Math.max(0, Math.ceil(left / DAY_MS2));
11375
11500
  ctx.output.warn(
11376
11501
  `The API key expires ${keyExpiresAt} (in ${days} day${days === 1 ? "" : "s"}). Create a new one at Settings > Integrations > API keys, then run kenso auth login --with-key.`
11377
11502
  );
@@ -12817,7 +12942,7 @@ var EMAIL_PATTERN, PROFILE_URL, SALES_PATH, IN_SLUG, SALES_NAVIGATOR_ID, MESSAGE
12817
12942
  var init_import_rows = __esm({
12818
12943
  "src/commands/contacts/import-rows.ts"() {
12819
12944
  "use strict";
12820
- init_common();
12945
+ init_common2();
12821
12946
  init_mapping();
12822
12947
  EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
12823
12948
  PROFILE_URL = /^\s*([a-z][a-z0-9+.-]*:\/\/)?\/*[^/?#\s]*linkedin[^/?#\s]*\/+([^/?#]{2}([-_][^/?#]{2})?\/+)?(in|pub)\/+[^/?#\s]/i;
@@ -12931,7 +13056,7 @@ var init_import_send = __esm({
12931
13056
  init_errors();
12932
13057
  init_exit_codes();
12933
13058
  init_http();
12934
- init_common();
13059
+ init_common2();
12935
13060
  GATEWAY_TIMEOUT_MS = 12e4;
12936
13061
  RESEND_MARGIN_MS = 1e4;
12937
13062
  LIMIT_REACHED_HINT = "Raise the campaign or plan contact limit, then run the same command again to continue.";
@@ -13042,7 +13167,7 @@ var init_server_import = __esm({
13042
13167
  init_exit_codes();
13043
13168
  init_http();
13044
13169
  init_wait();
13045
- init_common();
13170
+ init_common2();
13046
13171
  init_normalize();
13047
13172
  SERVER_IMPORT_NOTE = "Per-row results are not available with --server-import.";
13048
13173
  DEFAULT_TIMEOUT = "30m";
@@ -13111,7 +13236,7 @@ var init_import2 = __esm({
13111
13236
  init_exit_codes();
13112
13237
  init_http();
13113
13238
  init_input();
13114
- init_common();
13239
+ init_common2();
13115
13240
  init_import_rows();
13116
13241
  init_import_send();
13117
13242
  init_mapping();
@@ -13329,7 +13454,7 @@ var init_update = __esm({
13329
13454
  init_errors();
13330
13455
  init_http();
13331
13456
  init_input();
13332
- init_common();
13457
+ init_common2();
13333
13458
  init_mapping();
13334
13459
  COMMAND3 = "kenso contacts update";
13335
13460
  CHUNK_SIZE3 = 1e3;
@@ -13717,7 +13842,7 @@ var init_bulk_ids = __esm({
13717
13842
  init_http();
13718
13843
  init_input();
13719
13844
  init_bulk_store();
13720
- init_common();
13845
+ init_common2();
13721
13846
  init_import_send();
13722
13847
  CHUNK_SIZE4 = 1e3;
13723
13848
  SEARCH_PAGE = 200;
@@ -13843,7 +13968,7 @@ var init_tag = __esm({
13843
13968
  init_errors();
13844
13969
  init_http();
13845
13970
  init_bulk_ids();
13846
- init_common();
13971
+ init_common2();
13847
13972
  CHUNK_SIZE5 = 250;
13848
13973
  DEFAULT_CONCURRENCY3 = 4;
13849
13974
  ENTITY_TYPE = "contact";
@@ -13911,7 +14036,7 @@ var init_export = __esm({
13911
14036
  init_http();
13912
14037
  init_transfer();
13913
14038
  init_wait();
13914
- init_common();
14039
+ init_common2();
13915
14040
  COMMAND4 = "kenso contacts export";
13916
14041
  JOB_TYPE = "contact_export";
13917
14042
  DEFAULT_TIMEOUT2 = "30m";
@@ -13999,57 +14124,6 @@ var init_contacts = __esm({
13999
14124
  }
14000
14125
  });
14001
14126
 
14002
- // src/commands/credits/common.ts
14003
- function toCredits(millicredits) {
14004
- return typeof millicredits === "number" && Number.isFinite(millicredits) ? Math.round(millicredits) / 1e3 : void 0;
14005
- }
14006
- function positiveFlag(flags, name) {
14007
- const raw = flags[name];
14008
- if (raw === void 0) return void 0;
14009
- const text4 = String(raw).trim();
14010
- if (!/^\d+$/.test(text4) || Number(text4) < 1 || !Number.isSafeInteger(Number(text4))) {
14011
- throw usageError(`--${name} must be a positive whole number, not "${text4}".`, { field: name });
14012
- }
14013
- return Number(text4);
14014
- }
14015
- function instantFlag(flags, name) {
14016
- const raw = flags[name];
14017
- if (typeof raw !== "string") return void 0;
14018
- const text4 = raw.trim();
14019
- const back = /^(\d+)([dh])$/.exec(text4);
14020
- if (back) return new Date(Date.now() - Number(back[1]) * (back[2] === "d" ? DAY_MS2 : DAY_MS2 / 24)).toISOString();
14021
- const day = /^\d{4}-\d{2}-\d{2}$/.test(text4);
14022
- const ms = Date.parse(day ? `${text4}T00:00:00Z` : text4);
14023
- if (Number.isNaN(ms)) {
14024
- throw usageError(`--${name} "${text4}" is not a date.`, { field: name, hint: "Use 7d, 12h, 2026-11-01 or 2026-11-01T09:00:00Z." });
14025
- }
14026
- return new Date(day && name === "until" ? ms + DAY_MS2 - 1 : ms).toISOString();
14027
- }
14028
- async function readAvailable(ctx) {
14029
- try {
14030
- const res = await ctx.client.request({ method: "GET", path: "/v1/credits", signal: ctx.signal });
14031
- const available = unwrap(res.body)?.availableMillicredits;
14032
- return { available: typeof available === "number" ? available : void 0 };
14033
- } catch (err) {
14034
- if (err instanceof KensoError && (err.exitCode === ExitCode.Auth || err.exitCode === ExitCode.Interrupted)) throw err;
14035
- ctx.output.warn(`Could not read the available credits: ${err instanceof Error ? err.message : String(err)}`);
14036
- return { estimateError: err instanceof KensoError ? { code: err.code, message: err.message } : { message: String(err) } };
14037
- }
14038
- }
14039
- function estimateFailed(error) {
14040
- return new KensoError({ code: error.code ?? "estimate_failed", message: error.message, exitCode: ExitCode.Error });
14041
- }
14042
- var DAY_MS2;
14043
- var init_common3 = __esm({
14044
- "src/commands/credits/common.ts"() {
14045
- "use strict";
14046
- init_errors();
14047
- init_exit_codes();
14048
- init_http();
14049
- DAY_MS2 = 864e5;
14050
- }
14051
- });
14052
-
14053
14127
  // src/commands/credits/balance.ts
14054
14128
  var balance_exports = {};
14055
14129
  __export(balance_exports, {
@@ -14061,7 +14135,7 @@ var init_balance = __esm({
14061
14135
  "use strict";
14062
14136
  init_exit_codes();
14063
14137
  init_http();
14064
- init_common3();
14138
+ init_common();
14065
14139
  command24 = {
14066
14140
  resource: "credits",
14067
14141
  action: "balance",
@@ -14102,7 +14176,7 @@ var init_limit = __esm({
14102
14176
  "use strict";
14103
14177
  init_exit_codes();
14104
14178
  init_http();
14105
- init_common3();
14179
+ init_common();
14106
14180
  command25 = {
14107
14181
  resource: "credits",
14108
14182
  action: "limit",
@@ -14214,7 +14288,7 @@ var init_quote = __esm({
14214
14288
  init_exit_codes();
14215
14289
  init_input();
14216
14290
  init_columns();
14217
- init_common3();
14291
+ init_common();
14218
14292
  KINDS2 = ["campaign", "build", "infra", "accounts", "leads", "places"];
14219
14293
  COUNT_FIELD = { campaign: "targetLeads", accounts: "accountCount", leads: "leadCount", places: "pages" };
14220
14294
  command26 = {
@@ -14271,7 +14345,7 @@ var init_rate_card2 = __esm({
14271
14345
  init_exit_codes();
14272
14346
  init_rate_card();
14273
14347
  init_columns();
14274
- init_common3();
14348
+ init_common();
14275
14349
  command27 = {
14276
14350
  resource: "credits",
14277
14351
  action: "rate-card",
@@ -14316,7 +14390,7 @@ var init_savings = __esm({
14316
14390
  "use strict";
14317
14391
  init_exit_codes();
14318
14392
  init_http();
14319
- init_common3();
14393
+ init_common();
14320
14394
  command28 = {
14321
14395
  resource: "credits",
14322
14396
  action: "savings",
@@ -14346,6 +14420,10 @@ var usage_exports = {};
14346
14420
  __export(usage_exports, {
14347
14421
  default: () => usage_default
14348
14422
  });
14423
+ function ledgerRunId(value) {
14424
+ const id = value?.trim();
14425
+ return id !== void 0 && /^[1-9]\d*$/.test(id) ? `wf:${id}` : value;
14426
+ }
14349
14427
  function lineOut(e) {
14350
14428
  const { id, createdAt, action, title, units, category, campaignId, workflowId } = e;
14351
14429
  return { id, createdAt, action, title, units, credits: toCredits(e.millicredits), category, campaignId, workflowId, runId: e.run?.id };
@@ -14357,7 +14435,7 @@ var init_usage = __esm({
14357
14435
  init_exit_codes();
14358
14436
  init_http();
14359
14437
  init_columns();
14360
- init_common3();
14438
+ init_common();
14361
14439
  LEDGER_FLAGS = ["run", "workflow", "campaign", "action", "since", "until", "all"];
14362
14440
  command29 = {
14363
14441
  resource: "credits",
@@ -14366,7 +14444,7 @@ var init_usage = __esm({
14366
14444
  description: "With a filter it reads GET /v1/credits/ledger and prints one row per ledger line in credits, with the total on stderr: one page of 200 lines, or every line with --all. With no flag it reads GET /v1/credits/spend for this billing month and prints the credits by category. --since and --until take 7d, 12h, a UTC day (2026-11-01) or an ISO time.",
14367
14445
  effect: "read",
14368
14446
  flags: {
14369
- run: { type: "string", description: "Only the lines of this run (a workflow run id)", aliases: ["run-id"] },
14447
+ run: { type: "string", description: "Only the lines of this run: a workflow run id, or a ledger run id such as wf:9001", aliases: ["run-id"] },
14370
14448
  workflow: { type: "string", description: "Only the lines of this workflow id", aliases: ["workflow-id"] },
14371
14449
  campaign: { type: "string", description: "Only the lines of this campaign id", aliases: ["campaign-id"] },
14372
14450
  action: { type: "string", description: "Only these credit actions, comma-separated: email_found,web_scrape" },
@@ -14388,7 +14466,7 @@ var init_usage = __esm({
14388
14466
  method: "GET",
14389
14467
  path: "/v1/credits/ledger",
14390
14468
  query: {
14391
- runId: stringFlag(flags.run),
14469
+ runId: ledgerRunId(stringFlag(flags.run)),
14392
14470
  workflowId: positiveFlag(flags, "workflow"),
14393
14471
  campaignId: positiveFlag(flags, "campaign"),
14394
14472
  action: stringFlag(flags.action),
@@ -14627,7 +14705,7 @@ function detailOf(entry, cards) {
14627
14705
  lines: lines.map((line) => ({ ...line, price: priceLine(line, cards) })),
14628
14706
  ...text4 ? { text: text4 } : {},
14629
14707
  rateCard: { source: cards[0]?.source ?? "bundled", versions: cards.map((card) => card.version) }
14630
- } : effectOf(entry) === "spend" ? { lines: [], ...text4 ? { text: text4 } : {}, rateCard: null } : null;
14708
+ } : text4 || effectOf(entry) === "spend" ? { lines: [], ...text4 ? { text: text4 } : {}, rateCard: null } : null;
14631
14709
  }
14632
14710
  return out;
14633
14711
  }
@@ -14917,7 +14995,7 @@ async function candidates() {
14917
14995
  for (const load2 of Object.values(area)) {
14918
14996
  const spec = await load2();
14919
14997
  const entry = specEntry(spec);
14920
- if (entry) out.push(candidate(entry, spec.cost ? void 0 : spec.doc?.cost));
14998
+ if (entry) out.push({ ...candidate(entry, spec.cost ? void 0 : spec.doc?.cost), handWritten: true });
14921
14999
  }
14922
15000
  }
14923
15001
  const hasSkillShow = handWritten.skill?.show !== void 0;
@@ -14951,10 +15029,12 @@ function rank(all, query, kind) {
14951
15029
  const a = score(c, have);
14952
15030
  const b = score(c, need);
14953
15031
  if (a.points + b.points === 0) continue;
14954
- out.push({ candidate: c, both: arrow < 0 || a.points > 0 && b.points > 0, matched: a.matched + b.matched, points: a.points + b.points });
15032
+ const inId = new Set(termsOf(c.entry.id));
15033
+ const named = [.../* @__PURE__ */ new Set([...have, ...need])].filter((token) => inId.has(token)).length;
15034
+ out.push({ candidate: c, both: arrow < 0 || a.points > 0 && b.points > 0, matched: a.matched + b.matched, points: a.points + b.points, named });
14955
15035
  }
14956
15036
  return out.sort(
14957
- (x, y) => Number(y.both) - Number(x.both) || y.matched - x.matched || y.points - x.points || x.candidate.terms.size - y.candidate.terms.size || x.candidate.entry.id.localeCompare(y.candidate.entry.id)
15037
+ (x, y) => Number(y.both) - Number(x.both) || y.matched - x.matched || y.points - x.points || Number(y.candidate.handWritten === true) - Number(x.candidate.handWritten === true) || y.named - x.named || x.candidate.terms.size - y.candidate.terms.size || x.candidate.entry.id.localeCompare(y.candidate.entry.id)
14958
15038
  );
14959
15039
  }
14960
15040
  function parseKind(value) {
@@ -15130,7 +15210,7 @@ var init_docs2 = __esm({
15130
15210
  });
15131
15211
 
15132
15212
  // src/commands/doctor/index.ts
15133
- import { statSync as statSync2 } from "node:fs";
15213
+ import { statSync as statSync3 } from "node:fs";
15134
15214
  function withNext(check, next) {
15135
15215
  return check.ok ? check : { ...check, next };
15136
15216
  }
@@ -15175,7 +15255,7 @@ function configCheck(env) {
15175
15255
  const file = configPath(env);
15176
15256
  let mode;
15177
15257
  try {
15178
- mode = statSync2(file).mode & 511;
15258
+ mode = statSync3(file).mode & 511;
15179
15259
  } catch (err) {
15180
15260
  if (err.code === "ENOENT") return { name: "config_permissions", ok: true, detail: `no config file at ${file}` };
15181
15261
  return { name: "config_permissions", ok: false, detail: `cannot read ${file}: ${err.message}` };
@@ -15209,7 +15289,7 @@ var init_doctor = __esm({
15209
15289
  effect: "read",
15210
15290
  doc: {
15211
15291
  when: "first in a new session, and after an error you cannot explain: it checks Node, the config, the API and the key",
15212
- next: "kenso auth login when key_valid fails, else kenso describe for the command map"
15292
+ next: "kenso auth login when key_valid fails (under an agent, kenso login --no-wait), else kenso describe for the command map"
15213
15293
  },
15214
15294
  description: "Prints the version, Node, platform, config location, profile, key source, API URL, workspace and detected agent, plus the checks node_version, config_permissions, api_reachable, key_valid, skill_installed, skill_current and mcp_registered; each failed check carries the next command that fixes it. The skill and MCP checks read the detected agent's files (every agent found on this machine when none is detected) and make no request. next is the first failed check's next; when every check passes, starters lists four requests to start with. Exits 0 when the first four checks pass, 3 when the key check fails, else 1: the skill and MCP checks never change the exit code.",
15215
15295
  flags: {},
@@ -15217,6 +15297,7 @@ var init_doctor = __esm({
15217
15297
  operationIds: ["me.get"],
15218
15298
  async run(ctx) {
15219
15299
  const checks = [withNext(nodeCheck(), INSTALL_PAGE), withNext(configCheck(ctx.env), `chmod 600 ${configPath(ctx.env)}`)];
15300
+ const login = ctx.agent ? "kenso login --no-wait" : "kenso auth login";
15220
15301
  const started = Date.now();
15221
15302
  let reachable;
15222
15303
  let keyValid;
@@ -15240,20 +15321,20 @@ var init_doctor = __esm({
15240
15321
  const ms = Date.now() - started;
15241
15322
  if (err.httpStatus === void 0) {
15242
15323
  reachable = { name: "api_reachable", ok: false, detail: `${err.message} (${ms} ms)` };
15243
- keyValid = { name: "key_valid", ok: false, detail: ctx.auth.apiKey ? "not checked: the API is unreachable" : "no API key: run kenso auth login" };
15324
+ keyValid = { name: "key_valid", ok: false, detail: ctx.auth.apiKey ? "not checked: the API is unreachable" : `no API key: run ${login}` };
15244
15325
  } else {
15245
15326
  reachable = { name: "api_reachable", ok: err.httpStatus < 500, detail: `${ctx.auth.apiUrl} answered ${err.httpStatus} in ${ms} ms` };
15246
15327
  if (!ctx.auth.apiKey) {
15247
- keyValid = { name: "key_valid", ok: false, detail: "no API key: run kenso auth login" };
15328
+ keyValid = { name: "key_valid", ok: false, detail: `no API key: run ${login}` };
15248
15329
  } else if (err.httpStatus === 401 || err.httpStatus === 403) {
15249
15330
  keyFailed = true;
15250
- keyValid = { name: "key_valid", ok: false, detail: `the key was rejected (${err.httpStatus}): run kenso auth login` };
15331
+ keyValid = { name: "key_valid", ok: false, detail: `the key was rejected (${err.httpStatus}): run ${login}` };
15251
15332
  } else {
15252
15333
  keyValid = { name: "key_valid", ok: false, detail: `not checked: ${err.message}` };
15253
15334
  }
15254
15335
  }
15255
15336
  }
15256
- checks.push(withNext(reachable, "kenso doctor --verbose"), withNext(keyValid, "kenso auth login"));
15337
+ checks.push(withNext(reachable, "kenso doctor --verbose"), withNext(keyValid, login));
15257
15338
  const exitCode = checks.every((c) => c.ok) ? ExitCode.Ok : keyFailed ? ExitCode.Auth : ExitCode.Error;
15258
15339
  checks.push(...await agentChecks(ctx));
15259
15340
  const allPass = checks.every((c) => c.ok);
@@ -16742,7 +16823,7 @@ var init_import5 = __esm({
16742
16823
  init_estimate();
16743
16824
  init_http();
16744
16825
  init_rate_card();
16745
- init_common3();
16826
+ init_common();
16746
16827
  init_columns();
16747
16828
  COMMAND5 = "people import";
16748
16829
  CHUNK_SIZE6 = 200;
@@ -16910,7 +16991,7 @@ var init_merge2 = __esm({
16910
16991
  init_errors();
16911
16992
  init_exit_codes();
16912
16993
  init_http();
16913
- init_common();
16994
+ init_common2();
16914
16995
  command47 = {
16915
16996
  resource: "people",
16916
16997
  action: "merge",
@@ -18118,7 +18199,7 @@ var init_common4 = __esm({
18118
18199
  // src/commands/studio/folder.ts
18119
18200
  import { createHash as createHash7 } from "node:crypto";
18120
18201
  import { lstat, readdir as readdir2, readFile as readFile10, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
18121
- import { extname as extname6, isAbsolute, join as join19, relative, resolve as resolve12, sep } from "node:path";
18202
+ import { extname as extname6, isAbsolute as isAbsolute2, join as join19, relative as relative2, resolve as resolve12, sep as sep2 } from "node:path";
18122
18203
  function textOf2(bytes) {
18123
18204
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
18124
18205
  try {
@@ -18159,7 +18240,7 @@ async function readFolder(dir3, skipped = []) {
18159
18240
  for (const entry of entries2) {
18160
18241
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
18161
18242
  const abs = join19(folder, entry.name);
18162
- const path = relative(root3, abs).split(sep).join("/");
18243
+ const path = relative2(root3, abs).split(sep2).join("/");
18163
18244
  if (entry.isDirectory()) {
18164
18245
  if (path === "assets" || path.startsWith("assets/") || path === "samples") await walk(abs);
18165
18246
  else skipped.push(`${path}/`);
@@ -18184,15 +18265,15 @@ async function readFolder(dir3, skipped = []) {
18184
18265
  }
18185
18266
  function safeJoin(root3, bundlePath) {
18186
18267
  const segments = bundlePath.split("/");
18187
- const bad = !inBundleLayout(bundlePath) || isAbsolute(bundlePath) || bundlePath.includes("\\") || bundlePath.includes("\0");
18268
+ const bad = !inBundleLayout(bundlePath) || isAbsolute2(bundlePath) || bundlePath.includes("\\") || bundlePath.includes("\0");
18188
18269
  const target2 = resolve12(root3, ...segments);
18189
- if (bad || !target2.startsWith(root3.endsWith(sep) ? root3 : root3 + sep)) {
18270
+ if (bad || !target2.startsWith(root3.endsWith(sep2) ? root3 : root3 + sep2)) {
18190
18271
  throw unsafePath(bundlePath, `it is not a file of a Studio bundle (${LAYOUT}) inside ${root3}`);
18191
18272
  }
18192
18273
  return target2;
18193
18274
  }
18194
18275
  async function existingFileNoLinks(root3, target2, bundlePath) {
18195
- const parts2 = relative(root3, target2).split(sep);
18276
+ const parts2 = relative2(root3, target2).split(sep2);
18196
18277
  let at = root3;
18197
18278
  for (const [i, part] of parts2.entries()) {
18198
18279
  at = join19(at, part);
@@ -19052,7 +19133,7 @@ var init_fill = __esm({
19052
19133
  init_estimate();
19053
19134
  init_exit_codes();
19054
19135
  init_http();
19055
- init_common3();
19136
+ init_common();
19056
19137
  init_columns();
19057
19138
  init_common4();
19058
19139
  init_fill_runs();
@@ -19669,7 +19750,7 @@ async function poll2(ctx, types, cursor2) {
19669
19750
  return unwrap(res.body) ?? {};
19670
19751
  }
19671
19752
  function readBody(req) {
19672
- return new Promise((resolve23, reject) => {
19753
+ return new Promise((resolve24, reject) => {
19673
19754
  let size = 0;
19674
19755
  const chunks = [];
19675
19756
  req.on("data", (chunk) => {
@@ -19677,7 +19758,7 @@ function readBody(req) {
19677
19758
  if (size > MAX_TRIGGER_BYTES) req.destroy(new Error("too large"));
19678
19759
  else chunks.push(chunk);
19679
19760
  });
19680
- req.on("end", () => resolve23(Buffer.concat(chunks).toString("utf8")));
19761
+ req.on("end", () => resolve24(Buffer.concat(chunks).toString("utf8")));
19681
19762
  req.on("error", reject);
19682
19763
  });
19683
19764
  }
@@ -19766,7 +19847,7 @@ var init_listen = __esm({
19766
19847
  reply(res, 200, { forward: result ?? null });
19767
19848
  }).catch(() => reply(res, 400, { error: "invalid_event" }));
19768
19849
  });
19769
- await new Promise((resolve23) => server.listen(0, "127.0.0.1", resolve23));
19850
+ await new Promise((resolve24) => server.listen(0, "127.0.0.1", resolve24));
19770
19851
  const url = `http://127.0.0.1:${server.address().port}/events`;
19771
19852
  writeListenerState(ctx.env, workspaceId, { pid: process.pid, url, token, forwardTo: target2, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
19772
19853
  try {
@@ -19915,7 +19996,7 @@ var init_status3 = __esm({
19915
19996
  "use strict";
19916
19997
  init_exit_codes();
19917
19998
  init_http();
19918
- init_common2();
19999
+ init_common3();
19919
20000
  command73 = {
19920
20001
  resource: "work",
19921
20002
  action: "status",
@@ -20082,7 +20163,7 @@ var init_files = __esm({
20082
20163
  // src/work/agent-user.ts
20083
20164
  import { execFile, spawnSync as spawnSync2 } from "node:child_process";
20084
20165
  import { readFileSync as readFileSync19 } from "node:fs";
20085
- import { isAbsolute as isAbsolute2 } from "node:path";
20166
+ import { isAbsolute as isAbsolute3 } from "node:path";
20086
20167
  function sudoArgs(user, command90, args, keep = [], set2 = {}) {
20087
20168
  const assignments = Object.entries(set2).map(([name, value]) => `${name}=${value}`);
20088
20169
  return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command90, ...args];
@@ -20097,14 +20178,14 @@ function agentKensoEnv(opts) {
20097
20178
  }
20098
20179
  function sudoExec(user, command90, args, opts = {}) {
20099
20180
  const [sudo = "/usr/bin/sudo", ...lead] = user.sudo;
20100
- return new Promise((resolve23) => {
20181
+ return new Promise((resolve24) => {
20101
20182
  execFile(
20102
20183
  sudo,
20103
20184
  [...lead, ...sudoArgs(user.name, command90, args)],
20104
20185
  { env: { PATH: SUDO_PATH }, cwd: "/", timeout: opts.timeoutMs ?? PROBE_TIMEOUT_MS, maxBuffer: opts.maxBuffer ?? 1024 * 1024, encoding: "utf8", windowsHide: true, shell: false },
20105
20186
  (err, stdout, stderr) => {
20106
20187
  const code = err ? err.code : 0;
20107
- resolve23({ exitCode: typeof code === "number" ? code : null, stdout, stderr });
20188
+ resolve24({ exitCode: typeof code === "number" ? code : null, stdout, stderr });
20108
20189
  }
20109
20190
  );
20110
20191
  });
@@ -20174,7 +20255,7 @@ async function checkAgentUser(name) {
20174
20255
  }
20175
20256
  const environ = await sudoExec(user, CAT, [`${AGENT_USER_TOOLS.proc}/environ`]);
20176
20257
  const home2 = environ.exitCode === 0 ? environ.stdout.split("\0").find((v) => v.startsWith("HOME="))?.slice(5) : void 0;
20177
- if (home2 === void 0 || !isAbsolute2(home2) || home2 === "/") throw refusal(name, "has no home folder of its own");
20258
+ if (home2 === void 0 || !isAbsolute3(home2) || home2 === "/") throw refusal(name, "has no home folder of its own");
20178
20259
  return { ...user, home: home2 };
20179
20260
  }
20180
20261
  var KILL, CAT, SUDO_PATH, SHARED_DIR_MODE, JOB_DIR_MODE, WORK_FILE_MODE, AGENT_USER_TOOLS, USER_NAME, SUDO_GROUPS, PROBE_TIMEOUT_MS, KILL_TIMEOUT_MS;
@@ -20333,7 +20414,7 @@ var init_pull2 = __esm({
20333
20414
  "use strict";
20334
20415
  init_exit_codes();
20335
20416
  init_files();
20336
- init_common2();
20417
+ init_common3();
20337
20418
  init_folder3();
20338
20419
  MAX_FILES = 100;
20339
20420
  command74 = {
@@ -20544,7 +20625,7 @@ var init_answers = __esm({
20544
20625
  init_errors();
20545
20626
  init_http();
20546
20627
  init_files();
20547
- init_common2();
20628
+ init_common3();
20548
20629
  MAX_ANSWERS_PER_CALL = 50;
20549
20630
  SUBMIT_ROUNDS = 3;
20550
20631
  STATUSES3 = /* @__PURE__ */ new Set(["accepted", "rejected", "expired", "duplicate"]);
@@ -20565,7 +20646,7 @@ var init_submit = __esm({
20565
20646
  init_exit_codes();
20566
20647
  init_files();
20567
20648
  init_answers();
20568
- init_common2();
20649
+ init_common3();
20569
20650
  command75 = {
20570
20651
  resource: "work",
20571
20652
  action: "submit",
@@ -20627,7 +20708,7 @@ var init_release = __esm({
20627
20708
  init_errors();
20628
20709
  init_exit_codes();
20629
20710
  init_files();
20630
- init_common2();
20711
+ init_common3();
20631
20712
  CLAIM_ID = /^[A-Za-z0-9_-]{1,64}$/;
20632
20713
  command76 = {
20633
20714
  resource: "work",
@@ -20655,7 +20736,7 @@ var init_release = __esm({
20655
20736
 
20656
20737
  // src/work/job.ts
20657
20738
  import { spawn as nodeSpawn3 } from "node:child_process";
20658
- import { rmSync as rmSync5, statSync as statSync3 } from "node:fs";
20739
+ import { rmSync as rmSync5, statSync as statSync4 } from "node:fs";
20659
20740
  import { access, constants as constants2 } from "node:fs/promises";
20660
20741
  import { delimiter as delimiter2, join as join26 } from "node:path";
20661
20742
  import { setTimeout as delay12 } from "node:timers/promises";
@@ -20674,7 +20755,7 @@ function childEnv(parent, adapter, extra) {
20674
20755
  async function isExecutableFile(path) {
20675
20756
  try {
20676
20757
  await access(path, constants2.X_OK);
20677
- return statSync3(path).isFile();
20758
+ return statSync4(path).isFile();
20678
20759
  } catch {
20679
20760
  return false;
20680
20761
  }
@@ -20763,7 +20844,7 @@ async function groupGone(pid, runAs) {
20763
20844
  }
20764
20845
  }
20765
20846
  function runChild(spawnFn, bin, built, job, env, signal, runAs) {
20766
- return new Promise((resolve23) => {
20847
+ return new Promise((resolve24) => {
20767
20848
  const stdout = new Tail(OUTPUT_CAP_BYTES);
20768
20849
  const stderr = new Tail(OUTPUT_CAP_BYTES);
20769
20850
  let child;
@@ -20778,7 +20859,7 @@ function runChild(spawnFn, bin, built, job, env, signal, runAs) {
20778
20859
  shell: false
20779
20860
  });
20780
20861
  } catch (err) {
20781
- resolve23({ exitCode: null, stdout: "", stderr: "", spawnError: err });
20862
+ resolve24({ exitCode: null, stdout: "", stderr: "", spawnError: err });
20782
20863
  return;
20783
20864
  }
20784
20865
  let stopped;
@@ -20796,7 +20877,7 @@ function runChild(spawnFn, bin, built, job, env, signal, runAs) {
20796
20877
  signal?.removeEventListener("abort", onAbort);
20797
20878
  void groupGone(pid, runAs).then(() => {
20798
20879
  if (pid !== void 0) liveGroups.delete(pid);
20799
- resolve23({ exitCode, stdout: stdout.text(), stderr: stderr.text(), stopped, spawnError });
20880
+ resolve24({ exitCode, stdout: stdout.text(), stderr: stderr.text(), stopped, spawnError });
20800
20881
  });
20801
20882
  };
20802
20883
  const stop = (why) => {
@@ -20991,22 +21072,22 @@ function runStatus(bin, args, env, adapter, runAs) {
20991
21072
  const command90 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
20992
21073
  const commandArgs2 = runAs ? [...runAs.sudo.slice(1), ...sudoArgs(runAs.name, bin, args)] : args;
20993
21074
  const options = runAs ? { env: { PATH: SUDO_PATH }, cwd: "/" } : { env: childEnv(env, adapter) };
20994
- return new Promise((resolve23) => {
21075
+ return new Promise((resolve24) => {
20995
21076
  execFile2(
20996
21077
  command90,
20997
21078
  commandArgs2,
20998
21079
  { ...options, timeout: STATUS_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
20999
21080
  (err, stdout, stderr) => {
21000
21081
  if (err && typeof err.code === "string") {
21001
- resolve23(void 0);
21082
+ resolve24(void 0);
21002
21083
  return;
21003
21084
  }
21004
21085
  if (err && err.killed) {
21005
- resolve23(void 0);
21086
+ resolve24(void 0);
21006
21087
  return;
21007
21088
  }
21008
21089
  const exitCode = err ? err.code ?? null : 0;
21009
- resolve23({ exitCode: typeof exitCode === "number" ? exitCode : null, stdout: plain(String(stdout)), stderr: plain(String(stderr)) });
21090
+ resolve24({ exitCode: typeof exitCode === "number" ? exitCode : null, stdout: plain(String(stdout)), stderr: plain(String(stderr)) });
21010
21091
  }
21011
21092
  );
21012
21093
  });
@@ -21788,7 +21869,7 @@ var init_instruction = __esm({
21788
21869
  // src/work/pool.ts
21789
21870
  function runPool(opts) {
21790
21871
  const limit = Math.min(MAX_PARALLEL, Math.max(1, Math.floor(Number.isFinite(opts.parallel) ? opts.parallel : 1)));
21791
- return new Promise((resolve23, reject) => {
21872
+ return new Promise((resolve24, reject) => {
21792
21873
  let running = 0;
21793
21874
  let filling = false;
21794
21875
  let again = false;
@@ -21828,7 +21909,7 @@ function runPool(opts) {
21828
21909
  const stopping = empty || failure !== void 0 || opts.signal?.aborted === true;
21829
21910
  if (stopping && running === 0 && !again) {
21830
21911
  if (failure) reject(failure.error);
21831
- else resolve23();
21912
+ else resolve24();
21832
21913
  return;
21833
21914
  }
21834
21915
  } while (again);
@@ -21907,7 +21988,7 @@ var init_agent3 = __esm({
21907
21988
  init_exit_codes();
21908
21989
  init_adapters();
21909
21990
  init_job();
21910
- init_common2();
21991
+ init_common3();
21911
21992
  AGENT_NAMES = {
21912
21993
  claude: "Claude Code",
21913
21994
  codex: "Codex",
@@ -21928,7 +22009,7 @@ var init_agent3 = __esm({
21928
22009
  });
21929
22010
 
21930
22011
  // src/commands/work/box.ts
21931
- import { resolve as resolve18, sep as sep2 } from "node:path";
22012
+ import { resolve as resolve18, sep as sep3 } from "node:path";
21932
22013
  function invalidToken(message) {
21933
22014
  return new KensoError({ code: "invalid_token_format", message, exitCode: ExitCode.Usage, field: "token-stdin" });
21934
22015
  }
@@ -21955,7 +22036,7 @@ function requireSharedRunsDir(ctx, out) {
21955
22036
  if (!root3) {
21956
22037
  throw usageError("--agent-user needs KENSO_RUNS_DIR: the job folders go there, where the agent user's group can reach them.", { field: "agent-user" });
21957
22038
  }
21958
- if (out !== void 0 && !resolve18(out).startsWith(resolve18(root3) + sep2)) {
22039
+ if (out !== void 0 && !resolve18(out).startsWith(resolve18(root3) + sep3)) {
21959
22040
  throw usageError(`--out must be inside KENSO_RUNS_DIR (${root3}) with --agent-user.`, { field: "out" });
21960
22041
  }
21961
22042
  }
@@ -22013,7 +22094,7 @@ var init_box = __esm({
22013
22094
  init_input();
22014
22095
  init_agent_user();
22015
22096
  init_guide();
22016
- init_common2();
22097
+ init_common3();
22017
22098
  BOX_FLAGS = {
22018
22099
  "token-stdin": {
22019
22100
  type: "boolean",
@@ -22092,7 +22173,7 @@ var init_run3 = __esm({
22092
22173
  init_agent3();
22093
22174
  init_answers();
22094
22175
  init_box();
22095
- init_common2();
22176
+ init_common3();
22096
22177
  init_folder3();
22097
22178
  init_stop();
22098
22179
  FAILURES_IN_A_ROW = 3;
@@ -22443,9 +22524,9 @@ var init_work2 = __esm({
22443
22524
 
22444
22525
  // src/commands/workflows/files.ts
22445
22526
  import { mkdirSync as mkdirSync7, readFileSync as readFileSync20, writeFileSync as writeFileSync11 } from "node:fs";
22446
- import { basename as basename7, dirname as dirname6, join as join30, relative as relative2, resolve as resolve19, sep as sep3 } from "node:path";
22527
+ import { basename as basename7, dirname as dirname6, join as join30, relative as relative3, resolve as resolve19, sep as sep4 } from "node:path";
22447
22528
  function shownPath(path) {
22448
- return relative2(process.cwd(), path).split(sep3).join("/");
22529
+ return relative3(process.cwd(), path).split(sep4).join("/");
22449
22530
  }
22450
22531
  function readWorkflowFile(file) {
22451
22532
  const path = resolve19(file);
@@ -22490,7 +22571,10 @@ function writeWorkflowFile(file, definition, opts = {}) {
22490
22571
  function findBinding(file, auth) {
22491
22572
  const path = resolve19(file);
22492
22573
  const folder = findFolderFile(dirname6(path));
22493
- if (!folder) return { path };
22574
+ if (!folder) {
22575
+ refuseUntrusted(join30(dirname6(path), FOLDER_FILE));
22576
+ return { path };
22577
+ }
22494
22578
  if (folder.workspaceId && auth.workspaceId && folder.workspaceId !== auth.workspaceId) {
22495
22579
  throw new KensoError({
22496
22580
  code: "workspace_mismatch",
@@ -22500,7 +22584,7 @@ function findBinding(file, auth) {
22500
22584
  hint: `Its workflow ids belong to workspace ${folder.workspaceId}: run the command with --workspace ${folder.workspaceId}, or from a folder of workspace ${auth.workspaceId}.`
22501
22585
  });
22502
22586
  }
22503
- const key = relative2(dirname6(folder.path), path).split(sep3).join("/");
22587
+ const key = relative3(dirname6(folder.path), path).split(sep4).join("/");
22504
22588
  return { path, folder, key, workflowId: folder.workflows[key] };
22505
22589
  }
22506
22590
  function keyBoundTo(folder, workflowId, exceptKey) {
@@ -22688,7 +22772,7 @@ var init_logs2 = __esm({
22688
22772
  action: "logs",
22689
22773
  summary: "Print a workflow run's steps: status, attempt, time, credits and error",
22690
22774
  brief: "a run's steps",
22691
- description: "Reads GET /v1/workflow-runs/{runId} and prints one row per step run in start order: nodeId, stepType, status, attempt, startedAt, endedAt, ms, credits and error (errorClass: errorMessage). A header line on stderr names the run's status, workflow, record and the credits it charged, and its needs-attention reason when it has one. --step keeps one step; --full adds each step's input, output and attempts. A failed run ends with the retry command to try first. A succeeded run's step outputs are dropped 7 days after it ends unless the workflow keeps success details.",
22775
+ description: "Reads GET /v1/workflow-runs/{runId} and prints one row per step run in start order: nodeId, stepType, status, attempt, startedAt, endedAt, ms, credits and error (errorClass: errorMessage). A header line on stderr names the run's status, workflow, record and the credits it charged, and its needs-attention reason when it has one. --step keeps one step; --full adds each step's input, output and attempts. A failed run ends with the restart command to try first. A succeeded run's step outputs are dropped 7 days after it ends unless the workflow keeps success details.",
22692
22776
  effect: "read",
22693
22777
  flags: {
22694
22778
  step: { type: "string", description: "Keep one step: its id in the workflow definition" },
@@ -22725,7 +22809,7 @@ var init_logs2 = __esm({
22725
22809
  ctx.output.info(header(run));
22726
22810
  if (run.needsAttentionReason) ctx.output.info(`needs attention: ${run.needsAttentionReason}`);
22727
22811
  await ctx.output.list(steps.map((s) => stepRow(s, flags.full === true)));
22728
- if (run.status === "failed") ctx.output.info(`next: kenso workflow-runs retry --run-id ${runId} --dry-run`);
22812
+ if (run.status === "failed") ctx.output.info(`next: kenso workflow-runs restart --run-id ${runId} --dry-run`);
22729
22813
  return ExitCode.Ok;
22730
22814
  }
22731
22815
  };
@@ -22787,6 +22871,7 @@ var init_init = __esm({
22787
22871
  const path = join31(dir3, `${stem2}${WORKFLOW_FILE_SUFFIX}`);
22788
22872
  if (existsSync13(path)) throw fileExists(shownPath(path), "Pick another name, or edit the file you have.");
22789
22873
  const found = findFolderFile(dir3);
22874
+ if (!found) refuseUntrusted(join31(dir3, FOLDER_FILE));
22790
22875
  let definition;
22791
22876
  if (template2) {
22792
22877
  const res = await ctx.client.request({ method: "GET", path: `/v1/workflow-templates/${encodeURIComponent(template2)}`, signal: ctx.signal });
@@ -23092,14 +23177,14 @@ var init_push2 = __esm({
23092
23177
  }
23093
23178
  const { definition } = readWorkflowFile(file);
23094
23179
  const binding = findBinding(file, ctx.auth);
23095
- const boundId = binding.workflowId;
23096
- const before = boundId === void 0 ? void 0 : await getWorkflow(ctx, boundId);
23180
+ const boundId2 = binding.workflowId;
23181
+ const before = boundId2 === void 0 ? void 0 : await getWorkflow(ctx, boundId2);
23097
23182
  const changed = before === void 0 || !sameDefinition(definition, before.definition ?? {});
23098
23183
  if (ctx.flags.dryRun) {
23099
23184
  const save = before === void 0 ? ["workflows.create"] : changed ? ["workflows.update"] : [];
23100
23185
  ctx.output.object({
23101
23186
  dryRun: true,
23102
- workflowId: boundId ?? null,
23187
+ workflowId: boundId2 ?? null,
23103
23188
  wouldSend: [...save, ...publish ? ["workflows.publish"] : []],
23104
23189
  next: commandLine2(ctx, "workflows push", args)
23105
23190
  });
@@ -23113,7 +23198,7 @@ var init_push2 = __esm({
23113
23198
  } catch (err) {
23114
23199
  const refused = refusal2(ctx, file, err, false);
23115
23200
  if (refused instanceof KensoError && refused.code === "invalid_definition") {
23116
- ctx.output.object({ workflowId: boundId ?? null, saved: false, published: false, issues: issuesOf(err) });
23201
+ ctx.output.object({ workflowId: boundId2 ?? null, saved: false, published: false, issues: issuesOf(err) });
23117
23202
  }
23118
23203
  throw refused;
23119
23204
  }
@@ -23615,7 +23700,7 @@ var init_run_input = __esm({
23615
23700
  init_exit_codes();
23616
23701
  init_http();
23617
23702
  init_input();
23618
- init_common();
23703
+ init_common2();
23619
23704
  init_columns();
23620
23705
  init_import5();
23621
23706
  RECORD_TYPES3 = ["account", "person", "lead", "place"];
@@ -23627,7 +23712,7 @@ var init_run_input = __esm({
23627
23712
  // src/commands/workflows/run-start.ts
23628
23713
  import { readFileSync as readFileSync22 } from "node:fs";
23629
23714
  import { unlink as unlink4 } from "node:fs/promises";
23630
- import { join as join32 } from "node:path";
23715
+ import { dirname as dirname7, join as join32, relative as relative4, resolve as resolve22, sep as sep5 } from "node:path";
23631
23716
  function readJournal(file) {
23632
23717
  try {
23633
23718
  return JSON.parse(readFileSync22(file, "utf8"));
@@ -23656,27 +23741,42 @@ function answeredJournals(run, workflowId) {
23656
23741
  }
23657
23742
  return journals;
23658
23743
  }
23744
+ function runIdentity(args, anyCap = false) {
23745
+ return argsIdentity({ ...args, ids: void 0, file: void 0, ...anyCap ? { "max-credits": void 0 } : {} });
23746
+ }
23747
+ function boundId(path) {
23748
+ try {
23749
+ const folder = findFolderFile(dirname7(path));
23750
+ return folder?.workflows[relative4(dirname7(folder.path), path).split(sep5).join("/")];
23751
+ } catch {
23752
+ return void 0;
23753
+ }
23754
+ }
23755
+ function argsOf(run, current) {
23756
+ const target2 = Array.isArray(run.args.positionals) ? run.args.positionals[0] : void 0;
23757
+ const id = typeof target2 === "string" && !/^[1-9]\d*$/.test(target2) ? boundId(resolve22(run.cwd ?? process.cwd(), target2)) : void 0;
23758
+ return { ...run.args, "record-type": run.args["record-type"] ?? current["record-type"], ...id !== void 0 ? { positionals: [String(id)] } : {} };
23759
+ }
23760
+ async function runsOnInput(ctx, sha2566) {
23761
+ const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
23762
+ return (await listRuns(ctx.env)).filter(
23763
+ (run) => run.command === COMMAND7 && run.status !== "planned" && run.inputSha256 === sha2566 && (run.workspaceId || void 0) === (workspaceId || void 0)
23764
+ );
23765
+ }
23659
23766
  async function earlierRun(ctx, args, sha2566, workflowId) {
23660
- const earlier = (await findIdentical(COMMAND7, args, sha2566, ctx.env, ctx.client.workspaceId ?? ctx.auth.workspaceId)).filter((run) => run.status !== "planned");
23767
+ const identity = runIdentity(args);
23768
+ const earlier = (await runsOnInput(ctx, sha2566)).filter((run) => runIdentity(argsOf(run, args)) === identity);
23661
23769
  const open2 = earlier.find((run) => run.status !== "done");
23662
23770
  if (open2) {
23663
23771
  answeredJournals(open2, workflowId);
23664
23772
  return void 0;
23665
23773
  }
23666
- const done2 = earlier[0];
23667
- if (!done2) return void 0;
23668
- const summary = readSummary(filesOf(done2.dir).summaryJson) ?? { run: done2.runId };
23669
- ctx.output.info(`Run ${done2.runId} already finished on this input, so nothing was started again. To run the same records again, pass a changed input file.`);
23670
- ctx.output.summary({ ...summary, alreadyDone: true });
23671
- return Number(summary.notStarted ?? 0) + Number(summary.failed ?? 0) > 0 ? ExitCode.Partial : ExitCode.Ok;
23774
+ return earlier[0];
23672
23775
  }
23673
23776
  async function refuseRestart(ctx, run) {
23674
- const loose = (args) => argsIdentity({ ...args, "max-credits": void 0 });
23675
- const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
23676
23777
  const itemsSha256 = hashItems(run.items);
23677
- for (const earlier of await listRuns(ctx.env)) {
23678
- if (earlier.command !== COMMAND7 || earlier.status === "planned" || earlier.inputSha256 !== run.sha256 || loose(earlier.args) !== loose(run.args)) continue;
23679
- if ((earlier.workspaceId || void 0) !== (workspaceId || void 0)) continue;
23778
+ for (const earlier of await runsOnInput(ctx, run.sha256)) {
23779
+ if (runIdentity(argsOf(earlier, run.args), true) !== runIdentity(run.args, true)) continue;
23680
23780
  if (earlier.status !== "done" && argsIdentity(earlier.args) === argsIdentity(run.args) && (earlier.itemsSha256 ?? itemsSha256) === itemsSha256) continue;
23681
23781
  const sent = /* @__PURE__ */ new Set();
23682
23782
  for (const journal of answeredJournals(earlier, run.workflowId)) for (const item of run.items) if (item.row >= journal.firstRow && item.row <= journal.lastRow) sent.add(item.row);
@@ -23754,6 +23854,7 @@ var init_run_start = __esm({
23754
23854
  init_runs();
23755
23855
  init_errors();
23756
23856
  init_exit_codes();
23857
+ init_folder();
23757
23858
  init_http();
23758
23859
  init_columns();
23759
23860
  COMMAND7 = "workflows run";
@@ -23766,7 +23867,22 @@ var init_run_start = __esm({
23766
23867
  import { createHash as createHash13 } from "node:crypto";
23767
23868
  import { existsSync as existsSync16, readFileSync as readFileSync23 } from "node:fs";
23768
23869
  import { readFile as readFile13 } from "node:fs/promises";
23769
- import { dirname as dirname7, join as join33, resolve as resolve22 } from "node:path";
23870
+ import { dirname as dirname8, join as join33, resolve as resolve23 } from "node:path";
23871
+ function startKeys(results, workflowId) {
23872
+ const count = (...statuses) => results.filter((result) => statuses.includes(result.status)).length;
23873
+ return {
23874
+ started: count("started"),
23875
+ deduplicated: count("deduplicated"),
23876
+ notStarted: count("not_started", "over_limit", "not_live", "not_found"),
23877
+ succeeded: 0,
23878
+ failed: count("failed", "invalid"),
23879
+ waiting: 0,
23880
+ missed: {},
23881
+ creditsCharged: "pending",
23882
+ resultsCsv: null,
23883
+ next: `kenso workflow-runs list --workflow-id ${workflowId}`
23884
+ };
23885
+ }
23770
23886
  function sha2565(content) {
23771
23887
  return createHash13("sha256").update(content).digest("hex");
23772
23888
  }
@@ -23800,8 +23916,8 @@ async function readResultFlags(ctx, flags) {
23800
23916
  if (timeoutMs2 === void 0) {
23801
23917
  throw usageError(`--timeout "${timeoutText}" is not a duration.`, { field: "timeout", hint: "Use 90s, 10m, 1h or a number of seconds." });
23802
23918
  }
23803
- const out = outText === void 0 ? void 0 : resolve22(outText);
23804
- if (out !== void 0 && !existsSync16(dirname7(out))) throw usageError(`--out: the folder ${dirname7(out)} does not exist.`, { field: "out" });
23919
+ const out = outText === void 0 ? void 0 : resolve23(outText);
23920
+ if (out !== void 0 && !existsSync16(dirname8(out))) throw usageError(`--out: the folder ${dirname8(out)} does not exist.`, { field: "out" });
23805
23921
  if (out !== void 0 && existsSync16(out) && !await isOwnResultsFile(out, ctx.env)) {
23806
23922
  throw new KensoError({
23807
23923
  code: "file_exists",
@@ -23935,7 +24051,7 @@ async function finishRun(ctx, input) {
23935
24051
  waitedLine = `; ${counts2.succeeded} succeeded, ${counts2.waiting} waiting, ${String(counts2.creditsCharged)} credits charged`;
23936
24052
  }
23937
24053
  await writeJsonAtomic(join33(outcome.dir, "summary.json"), summary);
23938
- ctx.output.summary(summary);
24054
+ ctx.output.summary(input.alreadyDone ? { ...summary, alreadyDone: true } : summary);
23939
24055
  const n = (key) => Number(summary[key] ?? 0);
23940
24056
  ctx.output.info(
23941
24057
  `workflow ${workflowId}: ${n("started")} started, ${n("deduplicated")} deduplicated, ${n("notStarted")} not started, ${n("failed")} failed of ${n("records")} records${waitedLine}`
@@ -23944,6 +24060,18 @@ async function finishRun(ctx, input) {
23944
24060
  if (outcome.exitCode !== ExitCode.Ok) return outcome.exitCode;
23945
24061
  return n("notStarted") + n("failed") > 0 ? ExitCode.Partial : ExitCode.Ok;
23946
24062
  }
24063
+ async function answerDone(ctx, done2, input) {
24064
+ const files = filesOf(done2.dir);
24065
+ const summary = readSummary(files.summaryJson) ?? { run: done2.runId };
24066
+ ctx.output.info(`Run ${done2.runId} already finished on this input, so nothing was started again. To run the same records again, pass a changed input file.`);
24067
+ if (!input.flags.wait) {
24068
+ ctx.output.summary({ ...summary, alreadyDone: true });
24069
+ return Number(summary.notStarted ?? 0) + Number(summary.failed ?? 0) > 0 ? ExitCode.Partial : ExitCode.Ok;
24070
+ }
24071
+ const rows = [...(await readResults(files.resultsNdjson)).values()];
24072
+ const engineSummary = { ...summary, ...startKeys(rows, input.workflowId) };
24073
+ return finishRun(ctx, { outcome: { dir: done2.dir, resultsNdjson: files.resultsNdjson, exitCode: ExitCode.Ok }, engineSummary, ...input, alreadyDone: true });
24074
+ }
23947
24075
  var RESULT_COLUMNS2, OUT_MARKER, DEFAULT_TIMEOUT4, SUCCESS_VALUES, ENDED_UNSUCCESSFUL, isOwnRun;
23948
24076
  var init_run_results = __esm({
23949
24077
  "src/commands/workflows/run-results.ts"() {
@@ -24058,26 +24186,11 @@ async function estimate(ctx, target2, type, records, peopleRows) {
24058
24186
  }
24059
24187
  return total;
24060
24188
  }
24061
- function summarize4(workflowId, records, cap) {
24062
- return (results) => {
24063
- const count = (...statuses) => results.filter((result) => statuses.includes(result.status)).length;
24064
- return {
24065
- workflowId,
24066
- records,
24067
- started: count("started"),
24068
- deduplicated: count("deduplicated"),
24069
- notStarted: count("not_started", "over_limit", "not_live", "not_found"),
24070
- succeeded: 0,
24071
- failed: count("failed", "invalid"),
24072
- waiting: 0,
24073
- missed: {},
24074
- creditsCharged: "pending",
24075
- cap: cap(),
24076
- resultsCsv: null,
24077
- appUrl: `${APP_URL}/workflows/${workflowId}`,
24078
- next: `kenso workflow-runs list --workflow-id ${workflowId}`
24079
- };
24080
- };
24189
+ function appUrl(workflowId, workspaceId) {
24190
+ return workspaceId ? `${APP_URL}/${workspaceId}/workflows/${workflowId}` : `${APP_URL}/workflows/${workflowId}`;
24191
+ }
24192
+ function summarize4(workflowId, records, cap, url) {
24193
+ return (results) => ({ workflowId, records, ...startKeys(results, workflowId), cap: cap(), appUrl: url });
24081
24194
  }
24082
24195
  var NAME2, CHUNK_SIZE7, APP_URL, LIST_HINT, command86, run_default3;
24083
24196
  var init_run4 = __esm({
@@ -24152,34 +24265,45 @@ var init_run4 = __esm({
24152
24265
  const input = await readRunInput(ctx, { ids: ids2, file: csv, recordType: type });
24153
24266
  const rows = input.records.length + input.invalid.length;
24154
24267
  const basis = input.people ? rows : input.records.length;
24268
+ const unread = (err) => {
24269
+ if (apply || !(err instanceof KensoError) || err.exitCode === ExitCode.Auth || err.exitCode === ExitCode.Interrupted) throw err;
24270
+ return { code: err.code, message: err.message };
24271
+ };
24155
24272
  let totals;
24156
- let check;
24157
24273
  let estimateError;
24158
24274
  try {
24159
24275
  totals = await estimate(ctx, target2, type, input.records, input.people ? rows : void 0);
24276
+ } catch (err) {
24277
+ estimateError = unread(err);
24278
+ }
24279
+ let available;
24280
+ let balanceError;
24281
+ try {
24160
24282
  const balance = await ctx.client.request({ method: "GET", path: "/v1/credits", signal: ctx.signal });
24161
- check = creditsCheck(totals.max, unwrap(balance.body)?.availableMillicredits);
24283
+ const value = unwrap(balance.body)?.availableMillicredits;
24284
+ available = typeof value === "number" ? value : void 0;
24162
24285
  } catch (err) {
24163
- if (apply || !(err instanceof KensoError) || err.exitCode === ExitCode.Auth || err.exitCode === ExitCode.Interrupted) throw err;
24164
- estimateError = { code: err.code, message: err.message };
24286
+ balanceError = unread(err);
24165
24287
  }
24288
+ const check = creditsCheck(totals?.max, available);
24166
24289
  const hard = hardCeiling(target2.definition);
24167
24290
  const ceiling = hard ?? (totals && basis > 0 ? totals.max / basis / 1e3 : void 0);
24168
24291
  const retry = (cap2) => commandLine2(ctx, COMMAND7, { flags: { ...flags, "max-credits": String(cap2) }, positionals });
24169
24292
  const capFor = (count) => maxCredits !== void 0 && ceiling !== void 0 ? planCap(maxCredits, count, hard !== void 0 ? "hard" : "estimate", ceiling, retry) : null;
24170
24293
  let cap = capFor(input.records.length);
24171
24294
  const { timeout: _timeout, out: _out, ...identity } = flags;
24172
- const args = { ...identity, positionals };
24295
+ const args = { ...identity, "record-type": type, positionals: [String(workflowId)] };
24173
24296
  const applyCommand = commandLine2(ctx, COMMAND7, { flags, positionals }, ["--yes"]);
24174
24297
  const plan2 = {
24175
24298
  workflowId,
24176
24299
  records: rows,
24177
24300
  recordType: type,
24178
- ...check ? { credits: check } : {},
24301
+ credits: check,
24179
24302
  perRecord: totals && basis > 0 ? { expectedCredits: credits2(totals.expected / basis / 1e3), maxCredits: credits2(totals.max / basis / 1e3) } : null,
24180
24303
  expectedCredits: totals ? credits2(totals.expected / 1e3) : null,
24181
24304
  cap,
24182
- ...estimateError ? { estimateError } : {}
24305
+ ...estimateError ? { estimateError } : {},
24306
+ ...balanceError ? { balanceError } : {}
24183
24307
  };
24184
24308
  let start = /* @__PURE__ */ new Set();
24185
24309
  const spec = (dryRun2, records2, invalid3) => ({
@@ -24195,16 +24319,16 @@ var init_run4 = __esm({
24195
24319
  dryRun: dryRun2,
24196
24320
  dryRunExtra: plan2,
24197
24321
  applyCommand,
24198
- summarize: summarize4(workflowId, records2.length + invalid3.length, () => cap)
24322
+ summarize: summarize4(workflowId, records2.length + invalid3.length, () => cap, appUrl(workflowId, ctx.client.workspaceId ?? ctx.auth.workspaceId))
24199
24323
  });
24200
24324
  if (!apply) {
24201
24325
  const planned = await runBatch(spec(true, input.records, input.invalid), ctx);
24202
- if (ctx.flags.dryRun === true || !canAsk(ctx) || estimateError) return planned.exitCode;
24326
+ if (ctx.flags.dryRun === true || !canAsk(ctx) || estimateError || balanceError) return planned.exitCode;
24203
24327
  await confirmDestructive(ctx, `Start ${cap ? cap.willStart : input.records.length} of ${rows} records on workflow ${workflowId}`, applyCommand);
24204
24328
  }
24205
- const answered = await earlierRun(ctx, args, input.input.sha256, workflowId);
24206
- if (answered !== void 0) return answered;
24207
- if (check?.available != null && check.available <= 0 && (check.needed ?? 0) > 0) {
24329
+ const done2 = await earlierRun(ctx, args, input.input.sha256, workflowId);
24330
+ if (done2 !== void 0) return answerDone(ctx, done2, { workflowId, flags: results });
24331
+ if (check.available !== null && check.available <= 0 && (check.needed ?? 0) > 0) {
24208
24332
  throw new KensoError({ code: "out_of_credits", message: "The workspace is out of credits, so nothing was started.", exitCode: ExitCode.RateLimited });
24209
24333
  }
24210
24334
  let records = input.records;
@@ -25072,6 +25196,7 @@ function readOnlyError(spec, effect, source, argv) {
25072
25196
  });
25073
25197
  }
25074
25198
  async function beforeRun(ctx, spec, args, argv) {
25199
+ if (ctx.auth.folderFileSkipped) ctx.output.warn(`kenso.json skipped, another user could have written it: ${ctx.auth.folderFileSkipped}.`);
25075
25200
  const source = readOnlySource(ctx);
25076
25201
  if (!source && !ctx.agent) return;
25077
25202
  const effect = effectOf2(spec, args);
@@ -25095,14 +25220,14 @@ var init_pre_run = __esm({
25095
25220
 
25096
25221
  // src/core/update-notice.ts
25097
25222
  import { mkdirSync as mkdirSync8, readFileSync as readFileSync24, realpathSync as realpathSync2, renameSync as renameSync8, writeFileSync as writeFileSync13 } from "node:fs";
25098
- import { dirname as dirname8, join as join35, sep as sep4 } from "node:path";
25223
+ import { dirname as dirname9, join as join35, sep as sep6 } from "node:path";
25099
25224
  function installKind(script = process.argv[1], execPath = process.execPath, platform = process.platform) {
25100
25225
  try {
25101
25226
  if (!script) return "npm";
25102
25227
  const bundle = realpathSync2(script);
25103
- const lib = dirname8(dirname8(dirname8(bundle)));
25228
+ const lib = dirname9(dirname9(dirname9(bundle)));
25104
25229
  if (execPath !== join35(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
25105
- return bundle.includes(`${sep4}Cellar${sep4}kenso${sep4}`) ? "homebrew" : "standalone";
25230
+ return bundle.includes(`${sep6}Cellar${sep6}kenso${sep6}`) ? "homebrew" : "standalone";
25106
25231
  } catch {
25107
25232
  return "npm";
25108
25233
  }
@@ -25123,7 +25248,7 @@ function readCheck(file) {
25123
25248
  }
25124
25249
  function writeCheck(file, check) {
25125
25250
  try {
25126
- mkdirSync8(dirname8(file), { recursive: true, mode: 448 });
25251
+ mkdirSync8(dirname9(file), { recursive: true, mode: 448 });
25127
25252
  const temp = `${file}.${process.pid}.tmp`;
25128
25253
  writeFileSync13(temp, `${JSON.stringify(check)}
25129
25254
  `, { mode: 384 });