kenso 0.1.154 → 0.1.156

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
@@ -3389,7 +3389,7 @@ var VERSION;
3389
3389
  var init_version = __esm({
3390
3390
  "src/core/version.ts"() {
3391
3391
  "use strict";
3392
- VERSION = true ? "0.1.154" : "0.0.0-dev";
3392
+ VERSION = true ? "0.1.156" : "0.0.0-dev";
3393
3393
  }
3394
3394
  });
3395
3395
 
@@ -3684,9 +3684,9 @@ async function readAnswer(ctx) {
3684
3684
  const lines = createInterface({ input: ctx.stdin ?? process.stdin, terminal: false });
3685
3685
  let onAbort;
3686
3686
  try {
3687
- return await new Promise((resolve22, reject) => {
3688
- lines.once("line", resolve22);
3689
- lines.once("close", () => resolve22(""));
3687
+ return await new Promise((resolve23, reject) => {
3688
+ lines.once("line", resolve23);
3689
+ lines.once("close", () => resolve23(""));
3690
3690
  onAbort = () => reject(interrupted());
3691
3691
  ctx.signal.addEventListener("abort", onAbort, { once: true });
3692
3692
  });
@@ -3966,8 +3966,8 @@ async function saveFile(out, bytes) {
3966
3966
  return path;
3967
3967
  }
3968
3968
  function suggestedFileName(res) {
3969
- const header = res.headers.get("content-disposition") ?? "";
3970
- const encoded = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header)?.[1];
3969
+ const header2 = res.headers.get("content-disposition") ?? "";
3970
+ const encoded = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header2)?.[1];
3971
3971
  let name;
3972
3972
  if (encoded) {
3973
3973
  try {
@@ -3976,7 +3976,7 @@ function suggestedFileName(res) {
3976
3976
  name = void 0;
3977
3977
  }
3978
3978
  }
3979
- name ??= /filename\s*=\s*"?([^";]+)"?/.exec(header)?.[1]?.trim();
3979
+ name ??= /filename\s*=\s*"?([^";]+)"?/.exec(header2)?.[1]?.trim();
3980
3980
  const safe = basename(name ?? "").replace(/[^\w.-]+/g, "_").replace(/^\.+/, "");
3981
3981
  return safe === "" ? "download" : safe;
3982
3982
  }
@@ -4765,9 +4765,9 @@ async function readRun(dir3) {
4765
4765
  return null;
4766
4766
  }
4767
4767
  if (!raw) return null;
4768
- const { runId, command: command89, createdAt, status } = raw;
4768
+ const { runId, command: command90, createdAt, status } = raw;
4769
4769
  if (typeof runId !== "string" || !RUN_ID_PATTERN.test(runId)) return null;
4770
- if (typeof command89 !== "string" || typeof createdAt !== "string") return null;
4770
+ if (typeof command90 !== "string" || typeof createdAt !== "string") return null;
4771
4771
  if (typeof status !== "string" || !STATUSES.includes(status)) return null;
4772
4772
  let chunksDone = chunkList(raw.chunksDone) ?? [];
4773
4773
  try {
@@ -4778,7 +4778,7 @@ async function readRun(dir3) {
4778
4778
  const record3 = {
4779
4779
  ...raw,
4780
4780
  runId,
4781
- command: command89,
4781
+ command: command90,
4782
4782
  args: asRecord3(raw.args) ?? {},
4783
4783
  createdAt,
4784
4784
  status,
@@ -4838,11 +4838,11 @@ async function loadRun(runId, env = process.env) {
4838
4838
  }
4839
4839
  return run;
4840
4840
  }
4841
- async function findIdentical(command89, args, inputSha256, env, workspaceId, anyWorkspace = false) {
4841
+ async function findIdentical(command90, args, inputSha256, env, workspaceId, anyWorkspace = false) {
4842
4842
  const identity = argsIdentity(args);
4843
4843
  const runs = await listRuns(env);
4844
4844
  return runs.filter(
4845
- (run) => run.command === command89 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
4845
+ (run) => run.command === command90 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
4846
4846
  );
4847
4847
  }
4848
4848
  function isOtherLiveProcess(pid) {
@@ -7119,8 +7119,8 @@ function parseCsv(text4, source) {
7119
7119
  let records;
7120
7120
  try {
7121
7121
  records = parse(text4, {
7122
- columns: (header) => {
7123
- headers = header.map((h) => String(h));
7122
+ columns: (header2) => {
7123
+ headers = header2.map((h) => String(h));
7124
7124
  return headers;
7125
7125
  },
7126
7126
  bom: true,
@@ -7136,7 +7136,7 @@ function parseCsv(text4, source) {
7136
7136
  }
7137
7137
  const rows = records.map((record3) => {
7138
7138
  const row = {};
7139
- for (const header of headers) row[header] = record3[header] ?? "";
7139
+ for (const header2 of headers) row[header2] = record3[header2] ?? "";
7140
7140
  return row;
7141
7141
  });
7142
7142
  return { headers, rows };
@@ -7170,12 +7170,12 @@ function parseJsonl(text4, source) {
7170
7170
  }
7171
7171
  async function readInput(pathOrDash, opts) {
7172
7172
  const { path, bytes } = await readRaw(pathOrDash, opts?.stdin);
7173
- const sha2565 = createHash2("sha256").update(bytes).digest("hex");
7173
+ const sha2566 = createHash2("sha256").update(bytes).digest("hex");
7174
7174
  const text4 = bytes.toString("utf8");
7175
7175
  const source = path === "-" ? "stdin" : pathOrDash;
7176
7176
  const format = detectFormat(path, text4);
7177
7177
  const parsed2 = format === "csv" ? parseCsv(text4, source) : parseJsonl(text4, source);
7178
- return { path, format, sha256: sha2565, ...parsed2 };
7178
+ return { path, format, sha256: sha2566, ...parsed2 };
7179
7179
  }
7180
7180
  function idText(value) {
7181
7181
  if (typeof value === "number" && Number.isFinite(value)) return String(value);
@@ -8263,22 +8263,22 @@ var init_help_effect = __esm({
8263
8263
  });
8264
8264
 
8265
8265
  // src/commands/people/columns.ts
8266
- function normalizeHeader(header) {
8267
- return header.toLowerCase().replace(/[^a-z0-9]/g, "");
8266
+ function normalizeHeader(header2) {
8267
+ return header2.toLowerCase().replace(/[^a-z0-9]/g, "");
8268
8268
  }
8269
8269
  function mapColumns(headers, aliases) {
8270
8270
  const sources = /* @__PURE__ */ new Map();
8271
8271
  const mapping = {};
8272
8272
  const ignored = [];
8273
- for (const header of headers) {
8274
- const field = aliases[normalizeHeader(header)];
8273
+ for (const header2 of headers) {
8274
+ const field = aliases[normalizeHeader(header2)];
8275
8275
  if (field === void 0) {
8276
- ignored.push(header);
8276
+ ignored.push(header2);
8277
8277
  continue;
8278
8278
  }
8279
- mapping[header] = field;
8279
+ mapping[header2] = field;
8280
8280
  const list2 = sources.get(field) ?? [];
8281
- list2.push(header);
8281
+ list2.push(header2);
8282
8282
  sources.set(field, list2);
8283
8283
  }
8284
8284
  return { sources, mapping, ignored };
@@ -8321,8 +8321,8 @@ function idValue(value, field) {
8321
8321
  function shellQuote3(arg) {
8322
8322
  return /^[A-Za-z0-9_./:=@%+,-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
8323
8323
  }
8324
- function commandLine2(ctx, command89, args, extra = []) {
8325
- const parts2 = ["kenso", ...command89.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
8324
+ function commandLine2(ctx, command90, args, extra = []) {
8325
+ const parts2 = ["kenso", ...command90.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
8326
8326
  for (const [name, value] of Object.entries(args.flags)) {
8327
8327
  if (value === void 0 || value === false) continue;
8328
8328
  if (value === true) parts2.push(`--${name}`);
@@ -8596,7 +8596,7 @@ var init_import = __esm({
8596
8596
  }
8597
8597
  });
8598
8598
  const dryRun2 = ctx.flags.dryRun === true || ctx.flags.yes !== true;
8599
- const mapping = Object.fromEntries(Object.entries(columns2.mapping).map(([header, field]) => [header, field === "domain" ? "domains" : field]));
8599
+ const mapping = Object.fromEntries(Object.entries(columns2.mapping).map(([header2, field]) => [header2, field === "domain" ? "domains" : field]));
8600
8600
  const estimate2 = dryRun2 ? await estimateAccounts(ctx, items.length) : null;
8601
8601
  const credits3 = estimate2 ? { ...creditsCheck(estimate2.totalMillicredits, estimate2.availableMillicredits), sufficient: estimate2.sufficient } : creditsCheck(0, void 0);
8602
8602
  const outcome = await runBatch(
@@ -8635,9 +8635,9 @@ function stringFlag2(flags, name) {
8635
8635
  const text4 = value.trim();
8636
8636
  return text4 === "" ? void 0 : text4;
8637
8637
  }
8638
- function requireFlag(flags, name, command89, hint) {
8638
+ function requireFlag(flags, name, command90, hint) {
8639
8639
  const value = stringFlag2(flags, name);
8640
- if (value === void 0) throw usageError(`--${name} is required for ${command89}.`, { field: name, next: `${command89} --help`, ...hint ? { hint } : {} });
8640
+ if (value === void 0) throw usageError(`--${name} is required for ${command90}.`, { field: name, next: `${command90} --help`, ...hint ? { hint } : {} });
8641
8641
  return value;
8642
8642
  }
8643
8643
  function positiveId(value) {
@@ -8646,8 +8646,8 @@ function positiveId(value) {
8646
8646
  const id = Number(text4);
8647
8647
  return Number.isSafeInteger(id) && id > 0 ? id : void 0;
8648
8648
  }
8649
- function idFlag(flags, name, command89) {
8650
- const raw = requireFlag(flags, name, command89);
8649
+ function idFlag(flags, name, command90) {
8650
+ const raw = requireFlag(flags, name, command90);
8651
8651
  const id = positiveId(raw);
8652
8652
  if (id === void 0) throw usageError(`--${name} must be a positive whole number (got "${raw}").`, { field: name });
8653
8653
  return id;
@@ -8667,8 +8667,8 @@ function isDryRun(ctx) {
8667
8667
  function shellQuote4(value) {
8668
8668
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8669
8669
  }
8670
- function sameCommand2(command89, flags, ctx, extra = []) {
8671
- const parts2 = [command89];
8670
+ function sameCommand2(command90, flags, ctx, extra = []) {
8671
+ const parts2 = [command90];
8672
8672
  for (const [name, value] of Object.entries(flags)) {
8673
8673
  if (value === void 0 || value === false) continue;
8674
8674
  if (value === true) parts2.push(`--${name}`);
@@ -8708,7 +8708,7 @@ function isRecord5(value) {
8708
8708
  function warnDropped(ctx, mapping) {
8709
8709
  const dropped = Object.entries(mapping.dropped).filter(([, reason]) => reason !== "mapped_to_null");
8710
8710
  if (dropped.length === 0) return;
8711
- const list2 = dropped.map(([header, reason]) => `"${header}" (${reason})`).join(", ");
8711
+ const list2 = dropped.map(([header2, reason]) => `"${header2}" (${reason})`).join(", ");
8712
8712
  ctx.output.warn(`Not sent: ${list2}. Rename a column with --map '{"<column>": "customVariables.<name>"}'.`);
8713
8713
  }
8714
8714
  var OUT_FLAG2, CONCURRENCY_FLAG;
@@ -8900,12 +8900,12 @@ function filterBody(flags) {
8900
8900
  }
8901
8901
  return parsed2;
8902
8902
  }
8903
- function targetBody(flags, target2, command89) {
8903
+ function targetBody(flags, target2, command90) {
8904
8904
  const ids2 = idList(flags, "ids");
8905
8905
  const filter = filterBody(flags);
8906
8906
  const everything = flags.all === true;
8907
8907
  if (ids2 !== void 0 === (filter !== void 0 || everything)) {
8908
- throw usageError(`Name the ${target2.plural} one way: --ids, --filter, or --all for every ${target2.noun} in the workspace.`, { field: "ids", next: `${command89} --help` });
8908
+ throw usageError(`Name the ${target2.plural} one way: --ids, --filter, or --all for every ${target2.noun} in the workspace.`, { field: "ids", next: `${command90} --help` });
8909
8909
  }
8910
8910
  const exclude = idList(flags, "exclude-ids");
8911
8911
  if (exclude !== void 0 && ids2 !== void 0) throw usageError("--exclude-ids goes with --filter or --all.", { field: "exclude-ids" });
@@ -8926,14 +8926,14 @@ function tagSet(flags) {
8926
8926
  return set2;
8927
8927
  }
8928
8928
  function requestBody(flags, target2, dryRun2) {
8929
- const command89 = `kenso ${target2.resource} bulk-update`;
8929
+ const command90 = `kenso ${target2.resource} bulk-update`;
8930
8930
  const pairs = Array.isArray(flags.set) ? flags.set : typeof flags.set === "string" ? [flags.set] : [];
8931
8931
  const tags = target2.tags ? tagSet(flags) : {};
8932
8932
  if (pairs.length === 0 && Object.keys(tags).length === 0) {
8933
- throw usageError(`--set${target2.tags ? " or --add-tag" : ""} is required for ${command89}.`, { field: "set", hint: "For example --set stage=engaged.", next: `${command89} --help` });
8933
+ throw usageError(`--set${target2.tags ? " or --add-tag" : ""} is required for ${command90}.`, { field: "set", hint: "For example --set stage=engaged.", next: `${command90} --help` });
8934
8934
  }
8935
8935
  return {
8936
- ...targetBody(flags, target2, command89),
8936
+ ...targetBody(flags, target2, command90),
8937
8937
  set: { ...parseSet(pairs, target2.aliases, target2.textFields), ...tags },
8938
8938
  ...dryRun2 ? { dryRun: true } : {},
8939
8939
  ...flags["overwrite-pinned"] === true ? { overwritePinned: true } : {}
@@ -8999,7 +8999,7 @@ function bulkUpdateCommand(target2) {
8999
8999
  };
9000
9000
  }
9001
9001
  function bulkDeleteCommand(target2) {
9002
- const command89 = `kenso ${target2.resource} bulk-delete`;
9002
+ const command90 = `kenso ${target2.resource} bulk-delete`;
9003
9003
  return {
9004
9004
  resource: target2.resource,
9005
9005
  action: "bulk-delete",
@@ -9023,7 +9023,7 @@ function bulkDeleteCommand(target2) {
9023
9023
  beta: { featureGates: { all: target2.featureGates } },
9024
9024
  operationIds: [`${target2.resource}.bulk-delete`, "changes.get"],
9025
9025
  dryRun: true,
9026
- run: (ctx, { flags }) => runChange(ctx, flags, `/v1/${target2.resource}/bulk-delete`, (dryRun2) => ({ ...targetBody(flags, target2, command89), dryRun: dryRun2 }))
9026
+ run: (ctx, { flags }) => runChange(ctx, flags, `/v1/${target2.resource}/bulk-delete`, (dryRun2) => ({ ...targetBody(flags, target2, command90), dryRun: dryRun2 }))
9027
9027
  };
9028
9028
  }
9029
9029
  async function runChange(ctx, flags, path, body2) {
@@ -9789,7 +9789,7 @@ var init_output_and_errors = __esm({
9789
9789
  var README_default;
9790
9790
  var init_README = __esm({
9791
9791
  "docs/README.md"() {
9792
- README_default = '# Kenso CLI\n\nThe Kenso CLI (`kenso`) is the command line for Kenso. It does bulk work in your Kenso workspace from files: add thousands of leads to a campaign, update or clean them up, import accounts and people, and build Studio templates. It is made for coding agents (Claude Code, Codex, Cursor) and the people who drive them: JSON on stdout, fixed exit codes, a dry run before every bulk write, and runs you can resume.\n\nEvery canonical API operation a workspace member can call is also a command, such as `kenso campaigns list` or `kenso tags create`. So the CLI reaches what the Kenso MCP reaches, straight against `https://api.ken.so`. The legacy routes with no canonical successor, such as sequence images, AI variables or thread opens, have no command: reach them with `kenso api <METHOD> <path>`.\n\n## Install\n\nOn macOS or Linux, with or without Node, run the [install script](https://ken.so/install.sh): fetch it with `curl -fsSL` and pipe it to `sh`. It installs a standalone build that brings its own Node.js, checks the download against the release\'s `SHA256SUMS`, puts the CLI in `~/.local/share/kenso` and links `~/.local/bin/kenso`. Run it again to update.\n\nWith Homebrew, on macOS or Linux, the same standalone build:\n\n```bash\nbrew install ken-technology/tap/kenso\n```\n\n`brew upgrade kenso` updates it.\n\nWith Node 22 or newer, on any system, Windows included:\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`. On an older Node, kenso stops with one line that says so.\n\nEvery way to install:\n\n| Way | Systems | Needs |\n|---|---|---|\n| Install script, above | macOS, Linux (glibc) | Nothing |\n| Homebrew, above | macOS, Linux | Homebrew |\n| npm, above | Any | Node 22 or newer |\n| Standalone build: unpack it and put its `bin` folder on your PATH | macOS, Linux, Windows | Nothing |\n\nThe standalone builds are at `https://downloads.ken.so/desktop/cli/<version>/`, one per system: `kenso-<version>-darwin-arm64.tar.gz`, `darwin-x64`, `linux-arm64`, `linux-x64` and `kenso-<version>-windows-x64.zip`, with their `SHA256SUMS`. `https://downloads.ken.so/desktop/cli/latest.yml` names the newest version. The builds come out nightly and Homebrew follows them, so a command added that day reaches npm first.\n\n### Tab completion\n\nTab completes resources, actions and flags once you install the script for your shell. The script asks `kenso` for the candidates on each Tab, so it stays right as the CLI updates: install it once.\n\n```bash\n# zsh: add this line to ~/.zshrc\nsource <(kenso completion zsh)\n# bash: add this line to ~/.bashrc (on bash 3.2, the macOS default, use: eval "$(kenso completion bash)")\nsource <(kenso completion bash)\n# fish: save the script once\nkenso completion fish > ~/.config/fish/completions/kenso.fish\n```\n\n### Update notice\n\nWhen a newer version is out, `kenso` says so on stderr after the command\'s own output, at most once a week: `kenso 0.1.40 is out (you have 0.1.35): npm i -g kenso@latest`. It checks `registry.npmjs.org` at most once every 7 days and never delays a command by more than about a second. A standalone build checks `latest.yml` on `downloads.ken.so` instead and names its own update: the install script, or `brew upgrade kenso` when Homebrew installed it. It stays quiet in CI (`CI` set) and when stderr is not a terminal. Under a coding agent it asks nothing: it prints the line once per agent session, from the last check. Set `KENSO_NO_UPDATE_NOTIFIER=1` to turn it off.\n\n## 60-second quickstart\n\n1. Create an API key in app.ken.so at Settings > Integrations > API keys.\n2. Save the key, pick a workspace, then plan and apply a CSV import:\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --limit 5\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`workspace list` and `workspace use` are only needed when your key reaches more than one workspace.\n\nThe dry run reads the file, maps the columns, checks every row, asks Kenso for a credit estimate, and writes nothing. It prints the plan, with the exact apply command in `next`:\n\n```json\n{"run":"r_tdi5cdnx","dryRun":true,"command":"contacts import","rows":4,"valid":2,"invalid":2,"chunks":1,"chunkSize":1000,"campaignId":812,"mapping":{"Email":"email","First Name":"firstName","Last Name":"lastName","Company":"companyName","Pain Point":"customVariables.pain_point"},"customVariableKeys":["pain_point"],"estimate":{"kind":"leads","totalMillicredits":2000,"availableMillicredits":500000,"sufficient":true},"credits":{"needed":2,"available":500,"sufficient":true},"next":"kenso contacts import --campaign 812 --file leads.csv --yes","plan":"/home/you/.kenso/runs/r_tdi5cdnx/plan.json","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv"}\n```\n\nThe apply sends the rows and prints one summary. Every input row has one line in `results.csv`:\n\n```json\n{"run":"r_tdi5cdnx","rows":4,"ok":0,"created":1,"updated":0,"skipped":{"duplicate":1},"failed":0,"notFound":0,"invalid":2,"changed":1,"results":"/home/you/.kenso/runs/r_tdi5cdnx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_tdi5cdnx/results.ndjson","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv","resumed":false,"durationMs":1840,"campaignId":812,"notSendable":0}\n```\n\nThis run exits 5 because two rows were invalid: open `invalid.csv` to see why, fix those rows, and import them again. Running the same command again is safe: an email that is already in the campaign comes back `updated` or `skipped`, never as a second lead.\n\n## CLI or MCP\n\n- **Use the CLI for volume:** anything that starts from a file, anything over about 50 records, anything you may need to rerun or resume. Records never pass through the model\'s context: the agent passes a file path and reads a short summary.\n- **Use the MCP for conversation and single records:** look up a campaign, draft a reply, read a report. The MCP is at `https://mcp.ken.so/mcp`, signs in with OAuth and needs no install ([connection guide](https://ken.so/mcp)).\n- **Both use the same API and the same permissions.** `kenso mcp call` reaches MCP-only tools, such as skills, from the shell.\n\n## Docs\n\nEvery page is in the package and prints offline with `kenso docs <topic>`.\n\n| Page | Topic | What it covers |\n|---|---|---|\n| [Authentication](auth.md) | `auth` | API keys, browser login, profiles, workspaces, `doctor` |\n| [Leads](leads.md) | `leads` | Import, update, remove, pause, tag and export leads, with recipes |\n| [Batch runs](batch.md) | `batch` | Dry run and apply, run folders, results files, resume, rate limits, `--each` |\n| [Output and errors](output-and-errors.md) | `output-and-errors` | The output contract, error JSON, error codes, exit codes, live streams |\n| [CRM (beta)](crm.md) | `crm` | Accounts, people, opportunities and CRM sync |\n| [Studio (beta)](studio.md) | `studio` | Pull, push, validate, preview and fill templates |\n| [Agent work (beta)](work.md) | `work` | My agent: your own coding agent writes Kenso\'s AI work with `kenso work run`, or pull and submit |\n| [Webhooks](webhooks.md) | `webhooks` | Build a webhook handler locally: `kenso webhooks listen --forward-to`, `trigger`, the signature |\n| [Developer sandbox](sandbox.md) | `sandbox` | `kenso sandbox`: a workspace of your own where sends are simulated, its test key, the reserved test leads |\n| [Connect accounts](connect.md) | `connect` | `kenso connect`: an inbox, calendar, CRM, GitHub or other OAuth account, signed in by the person in a browser |\n| [Coding agents](agents.md) | `agents` | Claude Code, Codex, Cursor, the Agent Skill, environment variables, sandboxes |\n| Command reference | `reference` | Every command with its flags, generated from the CLI at build time: `kenso docs reference`, or `docs/reference.md` in the installed package |\n\n```bash\nkenso docs\nkenso docs leads\n```\n\nFor machine-readable help, run `kenso describe`: it prints every command, its flags and its body schema as JSON.\n';
9792
+ README_default = '# Kenso CLI\n\nThe Kenso CLI (`kenso`) is the command line for Kenso. It does bulk work in your Kenso workspace from files: add thousands of leads to a campaign, update or clean them up, import accounts and people, and build Studio templates. It is made for coding agents (Claude Code, Codex, Cursor) and the people who drive them: JSON on stdout, fixed exit codes, a dry run before every bulk write, and runs you can resume.\n\nEvery canonical API operation a workspace member can call is also a command, such as `kenso campaigns list` or `kenso tags create`. So the CLI reaches what the Kenso MCP reaches, straight against `https://api.ken.so`. The legacy routes with no canonical successor, such as sequence images, AI variables or thread opens, have no command: reach them with `kenso api <METHOD> <path>`.\n\n## Install\n\nOn macOS or Linux, with or without Node, run the [install script](https://ken.so/install.sh): fetch it with `curl -fsSL` and pipe it to `sh`. It installs a standalone build that brings its own Node.js, checks the download against the release\'s `SHA256SUMS`, puts the CLI in `~/.local/share/kenso` and links `~/.local/bin/kenso`. Run it again to update.\n\nWith Homebrew, on macOS or Linux, the same standalone build:\n\n```bash\nbrew install ken-technology/tap/kenso\n```\n\n`brew upgrade kenso` updates it.\n\nWith Node 22 or newer, on any system, Windows included:\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`. On an older Node, kenso stops with one line that says so.\n\nEvery way to install:\n\n| Way | Systems | Needs |\n|---|---|---|\n| Install script, above | macOS, Linux (glibc) | Nothing |\n| Homebrew, above | macOS, Linux | Homebrew |\n| npm, above | Any | Node 22 or newer |\n| Standalone build: unpack it and put its `bin` folder on your PATH | macOS, Linux, Windows | Nothing |\n\nThe standalone builds are at `https://downloads.ken.so/desktop/cli/<version>/`, one per system: `kenso-<version>-darwin-arm64.tar.gz`, `darwin-x64`, `linux-arm64`, `linux-x64` and `kenso-<version>-windows-x64.zip`, with their `SHA256SUMS`. `https://downloads.ken.so/desktop/cli/latest.yml` names the newest version. The builds come out nightly and Homebrew follows them, so a command added that day reaches npm first.\n\n### Tab completion\n\nTab completes resources, actions and flags once you install the script for your shell. The script asks `kenso` for the candidates on each Tab, so it stays right as the CLI updates: install it once.\n\n```bash\n# zsh: add this line to ~/.zshrc\nsource <(kenso completion zsh)\n# bash: add this line to ~/.bashrc (on bash 3.2, the macOS default, use: eval "$(kenso completion bash)")\nsource <(kenso completion bash)\n# fish: save the script once\nkenso completion fish > ~/.config/fish/completions/kenso.fish\n```\n\n### Update notice\n\nWhen a newer version is out, `kenso` says so on stderr after the command\'s own output, at most once a week: `kenso 0.1.40 is out (you have 0.1.35): npm i -g kenso@latest`. It checks `registry.npmjs.org` at most once every 7 days and never delays a command by more than about a second. A standalone build checks `latest.yml` on `downloads.ken.so` instead and names its own update: the install script, or `brew upgrade kenso` when Homebrew installed it. It stays quiet in CI (`CI` set) and when stderr is not a terminal. Under a coding agent it asks nothing: it prints the line once per agent session, from the last check. Set `KENSO_NO_UPDATE_NOTIFIER=1` to turn it off.\n\n## 60-second quickstart\n\n1. Create an API key in app.ken.so at Settings > Integrations > API keys.\n2. Save the key, pick a workspace, then plan and apply a CSV import:\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --limit 5\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`workspace list` and `workspace use` are only needed when your key reaches more than one workspace.\n\nThe dry run reads the file, maps the columns, checks every row, asks Kenso for a credit estimate, and writes nothing. It prints the plan, with the exact apply command in `next`:\n\n```json\n{"run":"r_tdi5cdnx","dryRun":true,"command":"contacts import","rows":4,"valid":2,"invalid":2,"chunks":1,"chunkSize":1000,"campaignId":812,"mapping":{"Email":"email","First Name":"firstName","Last Name":"lastName","Company":"companyName","Pain Point":"customVariables.pain_point"},"customVariableKeys":["pain_point"],"estimate":{"kind":"leads","totalMillicredits":2000,"availableMillicredits":500000,"sufficient":true},"credits":{"needed":2,"available":500,"sufficient":true},"next":"kenso contacts import --campaign 812 --file leads.csv --yes","plan":"/home/you/.kenso/runs/r_tdi5cdnx/plan.json","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv"}\n```\n\nThe apply sends the rows and prints one summary. Every input row has one line in `results.csv`:\n\n```json\n{"run":"r_tdi5cdnx","rows":4,"ok":0,"created":1,"updated":0,"skipped":{"duplicate":1},"failed":0,"notFound":0,"invalid":2,"changed":1,"results":"/home/you/.kenso/runs/r_tdi5cdnx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_tdi5cdnx/results.ndjson","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv","resumed":false,"durationMs":1840,"campaignId":812,"notSendable":0}\n```\n\nThis run exits 5 because two rows were invalid: open `invalid.csv` to see why, fix those rows, and import them again. Running the same command again is safe: an email that is already in the campaign comes back `updated` or `skipped`, never as a second lead.\n\n## CLI or MCP\n\n- **Use the CLI for volume:** anything that starts from a file, anything over about 50 records, anything you may need to rerun or resume. Records never pass through the model\'s context: the agent passes a file path and reads a short summary.\n- **Use the MCP for conversation and single records:** look up a campaign, draft a reply, read a report. The MCP is at `https://mcp.ken.so/mcp`, signs in with OAuth and needs no install ([connection guide](https://ken.so/mcp)).\n- **Both use the same API and the same permissions.** `kenso mcp call` reaches MCP-only tools, such as skills, from the shell.\n\n## Docs\n\nEvery page is in the package and prints offline with `kenso docs <topic>`.\n\n| Page | Topic | What it covers |\n|---|---|---|\n| [Authentication](auth.md) | `auth` | API keys, browser login, profiles, workspaces, `doctor` |\n| [Leads](leads.md) | `leads` | Import, update, remove, pause, tag and export leads, with recipes |\n| [Batch runs](batch.md) | `batch` | Dry run and apply, run folders, results files, resume, rate limits, `--each` |\n| [Output and errors](output-and-errors.md) | `output-and-errors` | The output contract, error JSON, error codes, exit codes, live streams |\n| [CRM (beta)](crm.md) | `crm` | Accounts, people, opportunities and CRM sync |\n| [Studio (beta)](studio.md) | `studio` | Pull, push, validate, preview and fill templates |\n| [Workflows (beta)](workflows.md) | `workflows` | Keep a workflow as a file: `kenso.json`, init, pull, check, push, test, publish, and run it on ids or a CSV with a credit cap |\n| [Agent work (beta)](work.md) | `work` | My agent: your own coding agent writes Kenso\'s AI work with `kenso work run`, or pull and submit |\n| [Webhooks](webhooks.md) | `webhooks` | Build a webhook handler locally: `kenso webhooks listen --forward-to`, `trigger`, the signature |\n| [Developer sandbox](sandbox.md) | `sandbox` | `kenso sandbox`: a workspace of your own where sends are simulated, its test key, the reserved test leads |\n| [Connect accounts](connect.md) | `connect` | `kenso connect`: an inbox, calendar, CRM, GitHub or other OAuth account, signed in by the person in a browser |\n| [Coding agents](agents.md) | `agents` | Claude Code, Codex, Cursor, the Agent Skill, environment variables, sandboxes |\n| Command reference | `reference` | Every command with its flags, generated from the CLI at build time: `kenso docs reference`, or `docs/reference.md` in the installed package |\n\n```bash\nkenso docs\nkenso docs leads\n```\n\nFor machine-readable help, run `kenso describe`: it prints every command, its flags and its body schema as JSON.\n';
9793
9793
  }
9794
9794
  });
9795
9795
 
@@ -9825,6 +9825,14 @@ var init_work = __esm({
9825
9825
  }
9826
9826
  });
9827
9827
 
9828
+ // docs/workflows.md
9829
+ var workflows_default;
9830
+ var init_workflows = __esm({
9831
+ "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';
9833
+ }
9834
+ });
9835
+
9828
9836
  // skill/kenso-cli/SKILL.md
9829
9837
  var SKILL_default;
9830
9838
  var init_SKILL = __esm({
@@ -9855,6 +9863,7 @@ var init_embedded = __esm({
9855
9863
  init_studio();
9856
9864
  init_webhooks();
9857
9865
  init_work();
9866
+ init_workflows();
9858
9867
  init_SKILL();
9859
9868
  DOCS = {
9860
9869
  "README.md": README_default,
@@ -9864,6 +9873,7 @@ var init_embedded = __esm({
9864
9873
  "output-and-errors.md": output_and_errors_default,
9865
9874
  "crm.md": crm_default,
9866
9875
  "studio.md": studio_default,
9876
+ "workflows.md": workflows_default,
9867
9877
  "work.md": work_default,
9868
9878
  "webhooks.md": webhooks_default,
9869
9879
  "sandbox.md": sandbox_default,
@@ -9903,6 +9913,7 @@ var init_content = __esm({
9903
9913
  { topic: "output-and-errors", file: "output-and-errors.md", title: "Output and errors", description: "The output contract, error JSON, error codes, exit codes, live streams" },
9904
9914
  { topic: "crm", file: "crm.md", title: "CRM (beta)", description: "Accounts, people, opportunities and CRM sync" },
9905
9915
  { topic: "studio", file: "studio.md", title: "Studio (beta)", description: "Pull, push, validate, preview and fill templates" },
9916
+ { topic: "workflows", file: "workflows.md", title: "Workflows (beta)", description: "Keep a workflow as a file: kenso.json, init, pull, check, push, test, publish, and run it on ids or a CSV with a credit cap" },
9906
9917
  { topic: "work", file: "work.md", title: "Agent work (beta)", description: "My agent: your own coding agent writes Kenso AI work with kenso work run, or pull and submit" },
9907
9918
  { topic: "webhooks", file: "webhooks.md", title: "Webhooks", description: "Build a webhook handler locally: kenso webhooks listen --forward-to, trigger, the signature" },
9908
9919
  { topic: "sandbox", file: "sandbox.md", title: "Developer sandbox", description: "kenso sandbox: a workspace of your own where sends are simulated, its test key, the reserved test leads" },
@@ -10246,9 +10257,9 @@ function tomlServers(text4) {
10246
10257
  const entries2 = [];
10247
10258
  let name;
10248
10259
  for (const line of text4.split(/\r?\n/)) {
10249
- const header = /^\s*\[([^\]]+)\]\s*(#.*)?$/.exec(line);
10250
- if (header) {
10251
- const m = /^mcp_servers\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))$/.exec(header[1].trim());
10260
+ const header2 = /^\s*\[([^\]]+)\]\s*(#.*)?$/.exec(line);
10261
+ if (header2) {
10262
+ const m = /^mcp_servers\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))$/.exec(header2[1].trim());
10252
10263
  name = m ? m[1] ?? m[2] ?? m[3] : void 0;
10253
10264
  continue;
10254
10265
  }
@@ -11059,8 +11070,8 @@ var init_browser_login = __esm({
11059
11070
  defaultDeps = {
11060
11071
  sleep: (ms, signal) => delay5(ms, void 0, signal ? { signal } : void 0),
11061
11072
  now: () => Date.now(),
11062
- spawn: (command89, args) => {
11063
- const child = nodeSpawn(command89, args, { detached: true, stdio: "ignore" });
11073
+ spawn: (command90, args) => {
11074
+ const child = nodeSpawn(command90, args, { detached: true, stdio: "ignore" });
11064
11075
  child.on("error", () => {
11065
11076
  });
11066
11077
  child.unref();
@@ -12451,8 +12462,8 @@ var init_run = __esm({
12451
12462
  defaultDeps2 = {
12452
12463
  sleep: (ms, signal) => delay6(ms, void 0, signal ? { signal } : void 0),
12453
12464
  now: () => Date.now(),
12454
- spawn: (command89, args) => {
12455
- const child = nodeSpawn2(command89, args, { detached: true, stdio: "ignore" });
12465
+ spawn: (command90, args) => {
12466
+ const child = nodeSpawn2(command90, args, { detached: true, stdio: "ignore" });
12456
12467
  child.on("error", () => {
12457
12468
  });
12458
12469
  child.unref();
@@ -12579,37 +12590,37 @@ var init_normalize = __esm({
12579
12590
  });
12580
12591
 
12581
12592
  // src/commands/contacts/mapping.ts
12582
- function headerKey(header) {
12583
- return header.toLowerCase().replace(/[^a-z0-9]/g, "");
12593
+ function headerKey(header2) {
12594
+ return header2.toLowerCase().replace(/[^a-z0-9]/g, "");
12584
12595
  }
12585
12596
  function isObject(value) {
12586
12597
  return value !== null && typeof value === "object" && !Array.isArray(value);
12587
12598
  }
12588
- function isBagHeader(header) {
12589
- return header.trim().toLowerCase() === "customvariables";
12599
+ function isBagHeader(header2) {
12600
+ return header2.trim().toLowerCase() === "customvariables";
12590
12601
  }
12591
12602
  function flattenCustomVariables(headers, rows) {
12592
12603
  const out = [];
12593
- for (const header of headers) {
12594
- if (!isBagHeader(header) || !rows.some((row) => isObject(row[header]))) {
12595
- if (!out.includes(header)) out.push(header);
12604
+ for (const header2 of headers) {
12605
+ if (!isBagHeader(header2) || !rows.some((row) => isObject(row[header2]))) {
12606
+ if (!out.includes(header2)) out.push(header2);
12596
12607
  continue;
12597
12608
  }
12598
12609
  let keepColumn = false;
12599
12610
  for (const row of rows) {
12600
- const bag = row[header];
12611
+ const bag = row[header2];
12601
12612
  if (!isObject(bag)) {
12602
12613
  keepColumn ||= bag !== void 0 && bag !== null && String(bag).trim() !== "";
12603
12614
  continue;
12604
12615
  }
12605
- delete row[header];
12616
+ delete row[header2];
12606
12617
  for (const [key, value] of Object.entries(bag)) {
12607
- const name = `${header}.${key}`;
12618
+ const name = `${header2}.${key}`;
12608
12619
  if (!Object.hasOwn(row, name)) row[name] = value;
12609
12620
  if (!out.includes(name) && !headers.includes(name)) out.push(name);
12610
12621
  }
12611
12622
  }
12612
- if (keepColumn && !out.includes(header)) out.push(header);
12623
+ if (keepColumn && !out.includes(header2)) out.push(header2);
12613
12624
  }
12614
12625
  return out;
12615
12626
  }
@@ -12655,9 +12666,9 @@ function overrideTarget(column, value, mode) {
12655
12666
  }
12656
12667
  return { field };
12657
12668
  }
12658
- function overrideFor(header, overrides2) {
12659
- if (Object.hasOwn(overrides2, header)) return { found: true, value: overrides2[header] ?? null };
12660
- const wanted = header.trim().toLowerCase();
12669
+ function overrideFor(header2, overrides2) {
12670
+ if (Object.hasOwn(overrides2, header2)) return { found: true, value: overrides2[header2] ?? null };
12671
+ const wanted = header2.trim().toLowerCase();
12661
12672
  for (const [key, value] of Object.entries(overrides2)) if (key.trim().toLowerCase() === wanted) return { found: true, value };
12662
12673
  return { found: false, value: null };
12663
12674
  }
@@ -12670,49 +12681,49 @@ function buildMapping(headers, overrides2, mode) {
12670
12681
  });
12671
12682
  }
12672
12683
  const result = { columns: [], mapping: {}, dropped: {}, customVariableKeys: [], fields: /* @__PURE__ */ new Set() };
12673
- const drop = (header, reason) => {
12674
- result.mapping[header] = null;
12675
- result.dropped[header] = reason;
12684
+ const drop = (header2, reason) => {
12685
+ result.mapping[header2] = null;
12686
+ result.dropped[header2] = reason;
12676
12687
  };
12677
- for (const header of headers) {
12678
- const override2 = overrideFor(header, overrides2);
12688
+ for (const header2 of headers) {
12689
+ const override2 = overrideFor(header2, overrides2);
12679
12690
  let target2;
12680
12691
  if (override2.found) {
12681
12692
  if (override2.value === null) {
12682
- drop(header, "mapped_to_null");
12693
+ drop(header2, "mapped_to_null");
12683
12694
  continue;
12684
12695
  }
12685
- target2 = overrideTarget(header, override2.value, mode);
12696
+ target2 = overrideTarget(header2, override2.value, mode);
12686
12697
  } else {
12687
- const field = fieldOf(header);
12688
- const custom = CUSTOM_HEADER.exec(header)?.[1];
12698
+ const field = fieldOf(header2);
12699
+ const custom = CUSTOM_HEADER.exec(header2)?.[1];
12689
12700
  if (custom !== void 0) {
12690
12701
  const problem = customVariableKeyProblem(custom);
12691
12702
  if (problem) {
12692
- drop(header, problem);
12703
+ drop(header2, problem);
12693
12704
  continue;
12694
12705
  }
12695
12706
  target2 = { customKey: normalizeVariableName(custom) };
12696
- } else if (isBagHeader(header)) {
12697
- drop(header, "not_an_object");
12707
+ } else if (isBagHeader(header2)) {
12708
+ drop(header2, "not_an_object");
12698
12709
  continue;
12699
12710
  } else if (field && !(field === "id" && mode === "import")) {
12700
12711
  if (mode === "update" && NOT_UPDATABLE.has(field)) {
12701
- drop(header, "not_updatable");
12712
+ drop(header2, "not_updatable");
12702
12713
  continue;
12703
12714
  }
12704
12715
  target2 = { field };
12705
12716
  } else {
12706
- const problem = customVariableKeyProblem(header);
12717
+ const problem = customVariableKeyProblem(header2);
12707
12718
  if (problem) {
12708
- drop(header, problem);
12719
+ drop(header2, problem);
12709
12720
  continue;
12710
12721
  }
12711
- target2 = { customKey: normalizeVariableName(header) };
12722
+ target2 = { customKey: normalizeVariableName(header2) };
12712
12723
  }
12713
12724
  }
12714
- result.columns.push({ header, target: target2 });
12715
- result.mapping[header] = targetName(target2);
12725
+ result.columns.push({ header: header2, target: target2 });
12726
+ result.mapping[header2] = targetName(target2);
12716
12727
  if ("field" in target2) result.fields.add(target2.field);
12717
12728
  else if (!result.customVariableKeys.includes(target2.customKey)) result.customVariableKeys.push(target2.customKey);
12718
12729
  }
@@ -12728,8 +12739,8 @@ function readCell(value) {
12728
12739
  }
12729
12740
  function rowValues(row, mapping, mode) {
12730
12741
  const out = { fields: {}, customVariables: {} };
12731
- for (const { header, target: target2 } of mapping.columns) {
12732
- const cell2 = readCell(row[header]);
12742
+ for (const { header: header2, target: target2 } of mapping.columns) {
12743
+ const cell2 = readCell(row[header2]);
12733
12744
  if (cell2.kind === "blank") continue;
12734
12745
  const value = cell2.kind === "null" ? null : cell2.text;
12735
12746
  if ("field" in target2) {
@@ -12954,25 +12965,25 @@ var init_import_send = __esm({
12954
12965
  // src/commands/contacts/server-import.ts
12955
12966
  import { readFile as readFile6 } from "node:fs/promises";
12956
12967
  import { basename as basename3, extname as extname3, resolve as resolve8 } from "node:path";
12957
- function csvTargetOf(header, mapping) {
12958
- if (mapping.dropped[header] !== "reserved_name") return void 0;
12959
- const key = normalizeVariableName(header);
12968
+ function csvTargetOf(header2, mapping) {
12969
+ if (mapping.dropped[header2] !== "reserved_name") return void 0;
12970
+ const key = normalizeVariableName(header2);
12960
12971
  return CSV_IMPORT_TARGET_FIELDS.has(key) ? key : void 0;
12961
12972
  }
12962
12973
  function columnMappings(mapping) {
12963
12974
  const sent = new Map(mapping.columns.map((column) => [column.header, column.target]));
12964
12975
  const out = [];
12965
- for (const header of Object.keys(mapping.mapping)) {
12966
- const target2 = sent.get(header);
12967
- const csvTarget = target2 ? void 0 : csvTargetOf(header, mapping);
12968
- if (target2 && "field" in target2) out.push({ csvColumn: header, targetField: TARGET_FIELDS[target2.field] ?? target2.field });
12969
- else if (target2) out.push({ csvColumn: header, targetField: "custom_variable", customVariableName: target2.customKey });
12970
- else if (csvTarget) out.push({ csvColumn: header, targetField: csvTarget });
12976
+ for (const header2 of Object.keys(mapping.mapping)) {
12977
+ const target2 = sent.get(header2);
12978
+ const csvTarget = target2 ? void 0 : csvTargetOf(header2, mapping);
12979
+ if (target2 && "field" in target2) out.push({ csvColumn: header2, targetField: TARGET_FIELDS[target2.field] ?? target2.field });
12980
+ else if (target2) out.push({ csvColumn: header2, targetField: "custom_variable", customVariableName: target2.customKey });
12981
+ else if (csvTarget) out.push({ csvColumn: header2, targetField: csvTarget });
12971
12982
  }
12972
12983
  return out;
12973
12984
  }
12974
12985
  function notUploaded(mapping) {
12975
- return Object.fromEntries(Object.entries(mapping.dropped).filter(([header]) => csvTargetOf(header, mapping) === void 0));
12986
+ return Object.fromEntries(Object.entries(mapping.dropped).filter(([header2]) => csvTargetOf(header2, mapping) === void 0));
12976
12987
  }
12977
12988
  async function readUpload2(file) {
12978
12989
  if (file === "-") throw usageError("--server-import uploads a file: name the CSV file instead of - (stdin).", { field: "file" });
@@ -13430,12 +13441,12 @@ import { join as join17 } from "node:path";
13430
13441
  function whereDir(env) {
13431
13442
  return join17(runsRoot(env), WHERE_DIR);
13432
13443
  }
13433
- async function unfinishedWhereIds(ctx, command89, args) {
13444
+ async function unfinishedWhereIds(ctx, command90, args) {
13434
13445
  const dir3 = whereDir(ctx.env);
13435
13446
  const identity = argsIdentity(args);
13436
13447
  const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
13437
13448
  for (const run of await listRuns(ctx.env)) {
13438
- if (run.command !== command89 || run.status === "done" || run.status === "planned") continue;
13449
+ if (run.command !== command90 || run.status === "done" || run.status === "planned") continue;
13439
13450
  if ((run.workspaceId || void 0) !== (workspaceId || void 0) || argsIdentity(run.args) !== identity) continue;
13440
13451
  if (run.inputPath?.startsWith(`${dir3}/`) && existsSync7(run.inputPath)) return run.inputPath;
13441
13452
  }
@@ -13581,14 +13592,14 @@ async function idsFromRun(ctx, runId) {
13581
13592
  return { ...idItems(ids2), source: "run" };
13582
13593
  }
13583
13594
  async function collectIds(ctx, flags, kind, dryRun2) {
13584
- const command89 = `kenso contacts ${kind}`;
13595
+ const command90 = `kenso contacts ${kind}`;
13585
13596
  const ids2 = stringFlag2(flags, "ids");
13586
13597
  const where = kind === "restore" ? void 0 : stringFlag2(flags, "where");
13587
13598
  const run = kind === "restore" ? stringFlag2(flags, "run") : void 0;
13588
13599
  const given = [ids2, where, run].filter((v) => v !== void 0).length;
13589
13600
  if (given !== 1) {
13590
13601
  const choices = kind === "restore" ? "--ids <file|-> or --run <runId>" : "--ids <file|-> or --where '<json>'";
13591
- throw usageError(`${command89} needs exactly one of ${choices}.`, { field: "ids", next: `${command89} --help` });
13602
+ throw usageError(`${command90} needs exactly one of ${choices}.`, { field: "ids", next: `${command90} --help` });
13592
13603
  }
13593
13604
  if (ids2 !== void 0) return idsFromFile(ctx, ids2);
13594
13605
  if (where !== void 0) return idsFromWhere(ctx, kind, flags, where, dryRun2);
@@ -14691,7 +14702,7 @@ var init_describe = __esm({
14691
14702
  const [resourceArg, action] = positionals;
14692
14703
  const resource = resourceArg === void 0 ? void 0 : resourceAliases[resourceArg] ?? resourceArg;
14693
14704
  const all = await entries();
14694
- const header = { version: VERSION, contractsHash: loadManifest().contractsHash || null };
14705
+ const header2 = { version: VERSION, contractsHash: loadManifest().contractsHash || null };
14695
14706
  if (resource !== void 0 && action !== void 0) {
14696
14707
  const entry = all.find((e) => e.resource === resource && e.action === action);
14697
14708
  if (!entry) throw unknown([resourceArg, action]);
@@ -14705,7 +14716,7 @@ var init_describe = __esm({
14705
14716
  const features = gated && !ctx.flags.allCommands ? await workspaceFeatures(ctx) : [];
14706
14717
  const visible = ctx.flags.allCommands ? scoped : scoped.filter((e) => gateSatisfied(e.gates, features));
14707
14718
  printJson(ctx, {
14708
- ...header,
14719
+ ...header2,
14709
14720
  commands: visible.map(
14710
14721
  (e) => flags.full === true ? { ...detailOf(e), handWritten: e.spec !== void 0 } : summaryOf(e, resource !== void 0)
14711
14722
  ),
@@ -15464,11 +15475,11 @@ function columnChanges(maps, columns2) {
15464
15475
  return maps.map((entry) => {
15465
15476
  const at = entry.lastIndexOf("=");
15466
15477
  if (at < 1) throw usageError(`--map takes "Header=field" (got "${entry}").`, { field: "map", hint: 'Skip a column with "Header=".' });
15467
- const header = entry.slice(0, at).trim();
15478
+ const header2 = entry.slice(0, at).trim();
15468
15479
  const field = entry.slice(at + 1).trim();
15469
- const column = byHeader.get(header.toLowerCase());
15480
+ const column = byHeader.get(header2.toLowerCase());
15470
15481
  if (!column) {
15471
- throw usageError(`The file has no column "${header}".`, { field: "map", hint: `Columns: ${columns2.map((c) => c.header).join(", ")}.` });
15482
+ throw usageError(`The file has no column "${header2}".`, { field: "map", hint: `Columns: ${columns2.map((c) => c.header).join(", ")}.` });
15472
15483
  }
15473
15484
  if (field === "new" || field.startsWith("new:")) {
15474
15485
  const type = field.slice(4).trim();
@@ -15710,12 +15721,12 @@ function bodyOf(layout) {
15710
15721
  sections: layout.sections?.map((s) => ({ key: s.key, hidden: s.hidden ?? false }))
15711
15722
  };
15712
15723
  }
15713
- function withHeader(layout, header) {
15714
- const pinned = new Set(header.map((key) => key.toLowerCase()));
15724
+ function withHeader(layout, header2) {
15725
+ const pinned = new Set(header2.map((key) => key.toLowerCase()));
15715
15726
  const unpinned = (layout.headerFields ?? []).filter((f) => !pinned.has(f.toLowerCase()));
15716
15727
  return bodyOf({
15717
15728
  version: layout.version,
15718
- headerFields: header,
15729
+ headerFields: header2,
15719
15730
  railSections: (layout.railSections ?? []).map((s, index2) => ({
15720
15731
  name: s.name,
15721
15732
  fields: [...index2 === 0 ? unpinned : [], ...s.fields.filter((f) => !pinned.has(f.toLowerCase()))]
@@ -15774,14 +15785,14 @@ var init_layouts = __esm({
15774
15785
  dryRun: true,
15775
15786
  async run(ctx, { flags, positionals }) {
15776
15787
  const object = objectOf(positionals, "set");
15777
- const header = typeof flags.header === "string" ? flags.header : void 0;
15788
+ const header2 = typeof flags.header === "string" ? flags.header : void 0;
15778
15789
  const data = typeof flags.data === "string" ? flags.data : void 0;
15779
- if (header === void 0 === (data === void 0)) {
15790
+ if (header2 === void 0 === (data === void 0)) {
15780
15791
  throw usageError("Pass one of --header or --data.", { next: `kenso layouts set ${object} --header tier,ownerMemberId` });
15781
15792
  }
15782
15793
  let body2;
15783
- if (header !== void 0) {
15784
- const keys = header.split(",").map((k) => k.trim()).filter(Boolean);
15794
+ if (header2 !== void 0) {
15795
+ const keys = header2.split(",").map((k) => k.trim()).filter(Boolean);
15785
15796
  body2 = withHeader(await call(ctx, "GET", object), keys);
15786
15797
  } else {
15787
15798
  const parsed2 = await readDataArg(data, ctx.stdin);
@@ -17356,8 +17367,8 @@ import { resolve as resolve11 } from "node:path";
17356
17367
  function kebab(key) {
17357
17368
  return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
17358
17369
  }
17359
- function commandWords(command89) {
17360
- return command89.trim().split(/\s+/).filter((t) => t !== "");
17370
+ function commandWords(command90) {
17371
+ return command90.trim().split(/\s+/).filter((t) => t !== "");
17361
17372
  }
17362
17373
  function flagValue(value) {
17363
17374
  return typeof value === "string" ? value : typeof value === "object" ? JSON.stringify(value) : String(value);
@@ -18378,10 +18389,10 @@ async function bundleFiles(ctx, templateId, files) {
18378
18389
  }
18379
18390
  return out;
18380
18391
  }
18381
- async function download2(url, path, sha2565, signal) {
18392
+ async function download2(url, path, sha2566, signal) {
18382
18393
  const res = await presigned(url, { method: "GET" }, `Downloading ${path}`, "download_failed", signal);
18383
18394
  const bytes = Buffer.from(await res.arrayBuffer());
18384
- if (sha2565 && createHash8("sha256").update(bytes).digest("hex") !== sha2565.toLowerCase()) {
18395
+ if (sha2566 && createHash8("sha256").update(bytes).digest("hex") !== sha2566.toLowerCase()) {
18385
18396
  throw new KensoError({
18386
18397
  code: "download_failed",
18387
18398
  message: `${path} did not download intact (its SHA-256 does not match).`,
@@ -19643,7 +19654,7 @@ async function poll2(ctx, types, cursor2) {
19643
19654
  return unwrap(res.body) ?? {};
19644
19655
  }
19645
19656
  function readBody(req) {
19646
- return new Promise((resolve22, reject) => {
19657
+ return new Promise((resolve23, reject) => {
19647
19658
  let size = 0;
19648
19659
  const chunks = [];
19649
19660
  req.on("data", (chunk) => {
@@ -19651,7 +19662,7 @@ function readBody(req) {
19651
19662
  if (size > MAX_TRIGGER_BYTES) req.destroy(new Error("too large"));
19652
19663
  else chunks.push(chunk);
19653
19664
  });
19654
- req.on("end", () => resolve22(Buffer.concat(chunks).toString("utf8")));
19665
+ req.on("end", () => resolve23(Buffer.concat(chunks).toString("utf8")));
19655
19666
  req.on("error", reject);
19656
19667
  });
19657
19668
  }
@@ -19740,7 +19751,7 @@ var init_listen = __esm({
19740
19751
  reply(res, 200, { forward: result ?? null });
19741
19752
  }).catch(() => reply(res, 400, { error: "invalid_event" }));
19742
19753
  });
19743
- await new Promise((resolve22) => server.listen(0, "127.0.0.1", resolve22));
19754
+ await new Promise((resolve23) => server.listen(0, "127.0.0.1", resolve23));
19744
19755
  const url = `http://127.0.0.1:${server.address().port}/events`;
19745
19756
  writeListenerState(ctx.env, workspaceId, { pid: process.pid, url, token, forwardTo: target2, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
19746
19757
  try {
@@ -20057,9 +20068,9 @@ var init_files = __esm({
20057
20068
  import { execFile, spawnSync as spawnSync2 } from "node:child_process";
20058
20069
  import { readFileSync as readFileSync18 } from "node:fs";
20059
20070
  import { isAbsolute as isAbsolute2 } from "node:path";
20060
- function sudoArgs(user, command89, args, keep = [], set2 = {}) {
20071
+ function sudoArgs(user, command90, args, keep = [], set2 = {}) {
20061
20072
  const assignments = Object.entries(set2).map(([name, value]) => `${name}=${value}`);
20062
- return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command89, ...args];
20073
+ return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command90, ...args];
20063
20074
  }
20064
20075
  function agentKensoEnv(opts) {
20065
20076
  return {
@@ -20069,16 +20080,16 @@ function agentKensoEnv(opts) {
20069
20080
  AI_AGENT: opts.agentName
20070
20081
  };
20071
20082
  }
20072
- function sudoExec(user, command89, args, opts = {}) {
20083
+ function sudoExec(user, command90, args, opts = {}) {
20073
20084
  const [sudo = "/usr/bin/sudo", ...lead] = user.sudo;
20074
- return new Promise((resolve22) => {
20085
+ return new Promise((resolve23) => {
20075
20086
  execFile(
20076
20087
  sudo,
20077
- [...lead, ...sudoArgs(user.name, command89, args)],
20088
+ [...lead, ...sudoArgs(user.name, command90, args)],
20078
20089
  { env: { PATH: SUDO_PATH }, cwd: "/", timeout: opts.timeoutMs ?? PROBE_TIMEOUT_MS, maxBuffer: opts.maxBuffer ?? 1024 * 1024, encoding: "utf8", windowsHide: true, shell: false },
20079
20090
  (err, stdout, stderr) => {
20080
20091
  const code = err ? err.code : 0;
20081
- resolve22({ exitCode: typeof code === "number" ? code : null, stdout, stderr });
20092
+ resolve23({ exitCode: typeof code === "number" ? code : null, stdout, stderr });
20082
20093
  }
20083
20094
  );
20084
20095
  });
@@ -20184,9 +20195,9 @@ var init_folder3 = __esm({
20184
20195
  init_redact();
20185
20196
  init_agent_user();
20186
20197
  WorkRunFolder = class {
20187
- constructor(ctx, command89, args, outDir, shared = false) {
20198
+ constructor(ctx, command90, args, outDir, shared = false) {
20188
20199
  this.ctx = ctx;
20189
- this.command = command89;
20200
+ this.command = command90;
20190
20201
  this.args = args;
20191
20202
  this.outDir = outDir;
20192
20203
  this.shared = shared;
@@ -20737,7 +20748,7 @@ async function groupGone(pid, runAs) {
20737
20748
  }
20738
20749
  }
20739
20750
  function runChild(spawnFn, bin, built, job, env, signal, runAs) {
20740
- return new Promise((resolve22) => {
20751
+ return new Promise((resolve23) => {
20741
20752
  const stdout = new Tail(OUTPUT_CAP_BYTES);
20742
20753
  const stderr = new Tail(OUTPUT_CAP_BYTES);
20743
20754
  let child;
@@ -20752,7 +20763,7 @@ function runChild(spawnFn, bin, built, job, env, signal, runAs) {
20752
20763
  shell: false
20753
20764
  });
20754
20765
  } catch (err) {
20755
- resolve22({ exitCode: null, stdout: "", stderr: "", spawnError: err });
20766
+ resolve23({ exitCode: null, stdout: "", stderr: "", spawnError: err });
20756
20767
  return;
20757
20768
  }
20758
20769
  let stopped;
@@ -20770,7 +20781,7 @@ function runChild(spawnFn, bin, built, job, env, signal, runAs) {
20770
20781
  signal?.removeEventListener("abort", onAbort);
20771
20782
  void groupGone(pid, runAs).then(() => {
20772
20783
  if (pid !== void 0) liveGroups.delete(pid);
20773
- resolve22({ exitCode, stdout: stdout.text(), stderr: stderr.text(), stopped, spawnError });
20784
+ resolve23({ exitCode, stdout: stdout.text(), stderr: stderr.text(), stopped, spawnError });
20774
20785
  });
20775
20786
  };
20776
20787
  const stop = (why) => {
@@ -20962,25 +20973,25 @@ function plain(text4) {
20962
20973
  return text4.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
20963
20974
  }
20964
20975
  function runStatus(bin, args, env, adapter, runAs) {
20965
- const command89 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
20976
+ const command90 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
20966
20977
  const commandArgs2 = runAs ? [...runAs.sudo.slice(1), ...sudoArgs(runAs.name, bin, args)] : args;
20967
20978
  const options = runAs ? { env: { PATH: SUDO_PATH }, cwd: "/" } : { env: childEnv(env, adapter) };
20968
- return new Promise((resolve22) => {
20979
+ return new Promise((resolve23) => {
20969
20980
  execFile2(
20970
- command89,
20981
+ command90,
20971
20982
  commandArgs2,
20972
20983
  { ...options, timeout: STATUS_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
20973
20984
  (err, stdout, stderr) => {
20974
20985
  if (err && typeof err.code === "string") {
20975
- resolve22(void 0);
20986
+ resolve23(void 0);
20976
20987
  return;
20977
20988
  }
20978
20989
  if (err && err.killed) {
20979
- resolve22(void 0);
20990
+ resolve23(void 0);
20980
20991
  return;
20981
20992
  }
20982
20993
  const exitCode = err ? err.code ?? null : 0;
20983
- resolve22({ exitCode: typeof exitCode === "number" ? exitCode : null, stdout: plain(String(stdout)), stderr: plain(String(stderr)) });
20994
+ resolve23({ exitCode: typeof exitCode === "number" ? exitCode : null, stdout: plain(String(stdout)), stderr: plain(String(stderr)) });
20984
20995
  }
20985
20996
  );
20986
20997
  });
@@ -21762,7 +21773,7 @@ var init_instruction = __esm({
21762
21773
  // src/work/pool.ts
21763
21774
  function runPool(opts) {
21764
21775
  const limit = Math.min(MAX_PARALLEL, Math.max(1, Math.floor(Number.isFinite(opts.parallel) ? opts.parallel : 1)));
21765
- return new Promise((resolve22, reject) => {
21776
+ return new Promise((resolve23, reject) => {
21766
21777
  let running = 0;
21767
21778
  let filling = false;
21768
21779
  let again = false;
@@ -21802,7 +21813,7 @@ function runPool(opts) {
21802
21813
  const stopping = empty || failure !== void 0 || opts.signal?.aborted === true;
21803
21814
  if (stopping && running === 0 && !again) {
21804
21815
  if (failure) reject(failure.error);
21805
- else resolve22();
21816
+ else resolve23();
21806
21817
  return;
21807
21818
  }
21808
21819
  } while (again);
@@ -22415,15 +22426,6 @@ var init_work2 = __esm({
22415
22426
  }
22416
22427
  });
22417
22428
 
22418
- // src/commands/workflow-runs/index.ts
22419
- var actions35;
22420
- var init_workflow_runs = __esm({
22421
- "src/commands/workflow-runs/index.ts"() {
22422
- "use strict";
22423
- actions35 = {};
22424
- }
22425
- });
22426
-
22427
22429
  // src/commands/workflows/files.ts
22428
22430
  import { mkdirSync as mkdirSync7, readFileSync as readFileSync19, writeFileSync as writeFileSync11 } from "node:fs";
22429
22431
  import { basename as basename7, dirname as dirname6, join as join30, relative as relative2, resolve as resolve19, sep as sep3 } from "node:path";
@@ -22555,6 +22557,178 @@ var init_files2 = __esm({
22555
22557
  }
22556
22558
  });
22557
22559
 
22560
+ // src/commands/workflows/run-wait.ts
22561
+ import { setTimeout as delay13 } from "node:timers/promises";
22562
+ function roundCredits(value) {
22563
+ return Math.round(value * 1e3) / 1e3;
22564
+ }
22565
+ function runCredits(run) {
22566
+ if (typeof run.creditsCharged === "number") return roundCredits(run.creditsCharged);
22567
+ if (typeof run.creditsChargedMillicredits === "number") return roundCredits(run.creditsChargedMillicredits / 1e3);
22568
+ return void 0;
22569
+ }
22570
+ function stepErrorText(step) {
22571
+ const text4 = [step.errorClass, step.errorMessage].filter((part) => typeof part === "string" && part !== "").join(": ");
22572
+ return text4 === "" ? void 0 : text4;
22573
+ }
22574
+ async function readRun2(client, runId, signal) {
22575
+ const res = await client.request({ method: "GET", path: `/v1/workflow-runs/${runId}`, signal });
22576
+ const data = unwrap(res.body);
22577
+ return data !== null && typeof data === "object" ? { ...data, id: typeof data.id === "number" ? data.id : runId } : { id: runId };
22578
+ }
22579
+ async function waitForRuns(client, runIds, opts) {
22580
+ const now = opts.now ?? Date.now;
22581
+ const sleep = opts.sleep ?? ((ms) => delay13(ms, void 0, { signal: opts.signal }));
22582
+ const runs = /* @__PURE__ */ new Map();
22583
+ let open2 = [...new Set(runIds)];
22584
+ const total = open2.length;
22585
+ const started = now();
22586
+ try {
22587
+ for (; ; ) {
22588
+ let next = 0;
22589
+ const failures = [];
22590
+ const reader = async () => {
22591
+ while (next < open2.length && failures.length === 0) {
22592
+ const id = open2[next++];
22593
+ try {
22594
+ runs.set(id, await readRun2(client, id, opts.signal));
22595
+ } catch (err) {
22596
+ failures.push(err);
22597
+ }
22598
+ }
22599
+ };
22600
+ await Promise.all(Array.from({ length: Math.min(MAX_PARALLEL_READS, open2.length) }, reader));
22601
+ if (failures.length > 0) throw failures[0];
22602
+ open2 = open2.filter((id) => OPEN_RUN_STATUSES.has(runs.get(id)?.status ?? "queued"));
22603
+ opts.onProgress?.(open2.length, total);
22604
+ const elapsed = now() - started;
22605
+ if (open2.length === 0 || elapsed >= opts.timeoutMs) return { runs, interrupted: false };
22606
+ await sleep(Math.min(elapsed >= FAST_PHASE_MS2 ? SLOW_INTERVAL_MS2 : FAST_INTERVAL_MS, opts.timeoutMs - elapsed));
22607
+ }
22608
+ } catch (err) {
22609
+ if (opts.signal.aborted || err instanceof KensoError && err.exitCode === ExitCode.Interrupted) return { runs, interrupted: true };
22610
+ return { runs, interrupted: false, stopped: err instanceof Error ? err.message : String(err) };
22611
+ }
22612
+ }
22613
+ var OPEN_RUN_STATUSES, MAX_PARALLEL_READS, FAST_INTERVAL_MS, SLOW_INTERVAL_MS2, FAST_PHASE_MS2;
22614
+ var init_run_wait = __esm({
22615
+ "src/commands/workflows/run-wait.ts"() {
22616
+ "use strict";
22617
+ init_errors();
22618
+ init_exit_codes();
22619
+ init_http();
22620
+ OPEN_RUN_STATUSES = /* @__PURE__ */ new Set(["queued", "running", "waiting"]);
22621
+ MAX_PARALLEL_READS = 8;
22622
+ FAST_INTERVAL_MS = 2e3;
22623
+ SLOW_INTERVAL_MS2 = 1e4;
22624
+ FAST_PHASE_MS2 = 6e4;
22625
+ }
22626
+ });
22627
+
22628
+ // src/commands/workflow-runs/logs.ts
22629
+ var logs_exports = {};
22630
+ __export(logs_exports, {
22631
+ default: () => logs_default
22632
+ });
22633
+ function msBetween(start, end) {
22634
+ if (!start || !end) return null;
22635
+ const ms = Date.parse(end) - Date.parse(start);
22636
+ return Number.isFinite(ms) ? ms : null;
22637
+ }
22638
+ function inStartOrder(steps) {
22639
+ const at = (step) => {
22640
+ const time = step.startedAt ? Date.parse(step.startedAt) : Number.NaN;
22641
+ return Number.isFinite(time) ? time : Number.POSITIVE_INFINITY;
22642
+ };
22643
+ return steps.map((step, index2) => ({ step, index: index2, time: at(step) })).sort((a, b) => a.time === b.time ? a.index - b.index : a.time < b.time ? -1 : 1).map((entry) => entry.step);
22644
+ }
22645
+ function stepRow(step, full) {
22646
+ return {
22647
+ nodeId: step.nodeId ?? null,
22648
+ stepType: step.stepType ?? null,
22649
+ status: step.status ?? null,
22650
+ attempt: step.attempt ?? null,
22651
+ startedAt: step.startedAt ?? null,
22652
+ endedAt: step.endedAt ?? null,
22653
+ ms: msBetween(step.startedAt, step.endedAt),
22654
+ credits: typeof step.creditsMillicredits === "number" ? roundCredits(step.creditsMillicredits / 1e3) : null,
22655
+ error: stepErrorText(step) ?? null,
22656
+ ...full ? { input: step.input ?? null, output: step.output ?? null, attempts: step.attempts ?? [] } : {}
22657
+ };
22658
+ }
22659
+ function header(run) {
22660
+ const record3 = run.recordType && run.recordType !== "none" ? `${run.recordType} ${run.recordId ?? "?"}` : "no record";
22661
+ return `run ${run.id}: ${run.status ?? "unknown"}, workflow ${run.workflowId ?? "?"}, ${record3}, charged ${runCredits(run) ?? 0} credits`;
22662
+ }
22663
+ var command78, logs_default;
22664
+ var init_logs2 = __esm({
22665
+ "src/commands/workflow-runs/logs.ts"() {
22666
+ "use strict";
22667
+ init_errors();
22668
+ init_exit_codes();
22669
+ init_files2();
22670
+ init_run_wait();
22671
+ command78 = {
22672
+ resource: "workflow-runs",
22673
+ action: "logs",
22674
+ summary: "Print a workflow run's steps: status, attempt, time, credits and error",
22675
+ brief: "a run's steps",
22676
+ 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.",
22677
+ effect: "read",
22678
+ flags: {
22679
+ step: { type: "string", description: "Keep one step: its id in the workflow definition" },
22680
+ full: { type: "boolean", description: "Add each step's input, output and attempts" }
22681
+ },
22682
+ positionals: [{ name: "runId", required: true, description: "The run id (kenso workflow-runs list, or the runId column of a results file)" }],
22683
+ examples: ["kenso workflow-runs logs 9001", "kenso workflow-runs logs 9001 --step qualify --full -o json"],
22684
+ beta: { featureGates: WORKFLOWS_GATES },
22685
+ operationIds: ["workflow-runs.get"],
22686
+ async run(ctx, { flags, positionals }) {
22687
+ const text4 = (positionals[0] ?? "").trim();
22688
+ const runId = Number(text4);
22689
+ if (!/^\d+$/.test(text4) || !Number.isSafeInteger(runId) || runId < 1) {
22690
+ throw usageError(`"${text4}" is not a run id: a run id is a positive whole number.`, {
22691
+ field: "runId",
22692
+ next: "kenso workflow-runs list --workflow-id <workflowId>"
22693
+ });
22694
+ }
22695
+ const run = await readRun2(ctx.client, runId, ctx.signal);
22696
+ let steps = inStartOrder(run.steps ?? []);
22697
+ const step = typeof flags.step === "string" ? flags.step.trim() : void 0;
22698
+ if (step !== void 0) {
22699
+ steps = steps.filter((s) => s.nodeId === step);
22700
+ if (steps.length === 0) {
22701
+ throw new KensoError({
22702
+ code: "not_found",
22703
+ message: `Run ${runId} has no step ${step}.`,
22704
+ exitCode: ExitCode.NotFound,
22705
+ field: "step",
22706
+ next: `kenso workflow-runs logs ${runId}`
22707
+ });
22708
+ }
22709
+ }
22710
+ ctx.output.info(header(run));
22711
+ if (run.needsAttentionReason) ctx.output.info(`needs attention: ${run.needsAttentionReason}`);
22712
+ await ctx.output.list(steps.map((s) => stepRow(s, flags.full === true)));
22713
+ if (run.status === "failed") ctx.output.info(`next: kenso workflow-runs retry --run-id ${runId} --dry-run`);
22714
+ return ExitCode.Ok;
22715
+ }
22716
+ };
22717
+ logs_default = command78;
22718
+ }
22719
+ });
22720
+
22721
+ // src/commands/workflow-runs/index.ts
22722
+ var actions35;
22723
+ var init_workflow_runs = __esm({
22724
+ "src/commands/workflow-runs/index.ts"() {
22725
+ "use strict";
22726
+ actions35 = {
22727
+ logs: () => Promise.resolve().then(() => (init_logs2(), logs_exports)).then((m) => m.default)
22728
+ };
22729
+ }
22730
+ });
22731
+
22558
22732
  // src/commands/workflows/init.ts
22559
22733
  var init_exports = {};
22560
22734
  __export(init_exports, {
@@ -22562,7 +22736,7 @@ __export(init_exports, {
22562
22736
  });
22563
22737
  import { existsSync as existsSync13 } from "node:fs";
22564
22738
  import { join as join31, resolve as resolve20 } from "node:path";
22565
- var STEM, command78, init_default;
22739
+ var STEM, command79, init_default;
22566
22740
  var init_init = __esm({
22567
22741
  "src/commands/workflows/init.ts"() {
22568
22742
  "use strict";
@@ -22572,7 +22746,7 @@ var init_init = __esm({
22572
22746
  init_http();
22573
22747
  init_files2();
22574
22748
  STEM = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
22575
- command78 = {
22749
+ command79 = {
22576
22750
  resource: "workflows",
22577
22751
  action: "init",
22578
22752
  summary: "Start a workflow file in this folder",
@@ -22628,7 +22802,7 @@ var init_init = __esm({
22628
22802
  return ExitCode.Ok;
22629
22803
  }
22630
22804
  };
22631
- init_default = command78;
22805
+ init_default = command79;
22632
22806
  }
22633
22807
  });
22634
22808
 
@@ -22641,7 +22815,7 @@ import { existsSync as existsSync14 } from "node:fs";
22641
22815
  function slugOf(name) {
22642
22816
  return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "");
22643
22817
  }
22644
- var command79, pull_default3;
22818
+ var command80, pull_default3;
22645
22819
  var init_pull3 = __esm({
22646
22820
  "src/commands/workflows/pull.ts"() {
22647
22821
  "use strict";
@@ -22649,7 +22823,7 @@ var init_pull3 = __esm({
22649
22823
  init_exit_codes();
22650
22824
  init_common4();
22651
22825
  init_files2();
22652
- command79 = {
22826
+ command80 = {
22653
22827
  resource: "workflows",
22654
22828
  action: "pull",
22655
22829
  summary: "Write a workflow's definition to a file and bind it",
@@ -22708,7 +22882,7 @@ var init_pull3 = __esm({
22708
22882
  return ExitCode.Ok;
22709
22883
  }
22710
22884
  };
22711
- pull_default3 = command79;
22885
+ pull_default3 = command80;
22712
22886
  }
22713
22887
  });
22714
22888
 
@@ -22741,7 +22915,7 @@ function perRecord(estimate2) {
22741
22915
  const max = bulk ? totals.bulkMaxMillicredits : totals.maxMillicredits;
22742
22916
  return typeof expected === "number" && typeof max === "number" ? { expectedCredits: expected / 1e3, maxCredits: max / 1e3 } : null;
22743
22917
  }
22744
- var FILE3, command80, check_default;
22918
+ var FILE3, command81, check_default;
22745
22919
  var init_check = __esm({
22746
22920
  "src/commands/workflows/check.ts"() {
22747
22921
  "use strict";
@@ -22752,7 +22926,7 @@ var init_check = __esm({
22752
22926
  init_columns();
22753
22927
  init_files2();
22754
22928
  FILE3 = { name: "file", required: true, description: "The workflow file (<name>.workflow.json)" };
22755
- command80 = {
22929
+ command81 = {
22756
22930
  resource: "workflows",
22757
22931
  action: "check",
22758
22932
  summary: "Validate a workflow file on the server and print one record's credit estimate",
@@ -22793,7 +22967,7 @@ var init_check = __esm({
22793
22967
  return valid ? ExitCode.Ok : ExitCode.Partial;
22794
22968
  }
22795
22969
  };
22796
- check_default = command80;
22970
+ check_default = command81;
22797
22971
  }
22798
22972
  });
22799
22973
 
@@ -22857,7 +23031,7 @@ function state(workflow, saved, published, extra = {}) {
22857
23031
  ...extra
22858
23032
  };
22859
23033
  }
22860
- var command81, push_default2;
23034
+ var command82, push_default2;
22861
23035
  var init_push2 = __esm({
22862
23036
  "src/commands/workflows/push.ts"() {
22863
23037
  "use strict";
@@ -22867,7 +23041,7 @@ var init_push2 = __esm({
22867
23041
  init_columns();
22868
23042
  init_check();
22869
23043
  init_files2();
22870
- command81 = {
23044
+ command82 = {
22871
23045
  resource: "workflows",
22872
23046
  action: "push",
22873
23047
  summary: "Save a workflow file as the workflow's draft, and publish it with --publish",
@@ -22971,7 +23145,7 @@ var init_push2 = __esm({
22971
23145
  return ExitCode.Ok;
22972
23146
  }
22973
23147
  };
22974
- push_default2 = command81;
23148
+ push_default2 = command82;
22975
23149
  }
22976
23150
  });
22977
23151
 
@@ -23004,7 +23178,7 @@ async function startTest(ctx, workflowId, body2) {
23004
23178
  });
23005
23179
  }
23006
23180
  }
23007
- var RECORD_TYPES2, MAX_WAIT_SECONDS, command82, test_default;
23181
+ var RECORD_TYPES2, MAX_WAIT_SECONDS, command83, test_default;
23008
23182
  var init_test = __esm({
23009
23183
  "src/commands/workflows/test.ts"() {
23010
23184
  "use strict";
@@ -23016,7 +23190,7 @@ var init_test = __esm({
23016
23190
  init_files2();
23017
23191
  RECORD_TYPES2 = ["account", "person", "lead", "place"];
23018
23192
  MAX_WAIT_SECONDS = 50;
23019
- command82 = {
23193
+ command83 = {
23020
23194
  resource: "workflows",
23021
23195
  action: "test",
23022
23196
  summary: "Run the saved draft of a workflow file on one record and print the hash to publish with",
@@ -23072,7 +23246,7 @@ var init_test = __esm({
23072
23246
  return passed ? ExitCode.Ok : ExitCode.Error;
23073
23247
  }
23074
23248
  };
23075
- test_default = command82;
23249
+ test_default = command83;
23076
23250
  }
23077
23251
  });
23078
23252
 
@@ -23106,7 +23280,7 @@ function diffDefinitions(from, to) {
23106
23280
  stepsChanged: [...after.keys()].filter((id) => before.has(id) && differs(before.get(id), after.get(id)))
23107
23281
  };
23108
23282
  }
23109
- var command83, diff_default;
23283
+ var command84, diff_default;
23110
23284
  var init_diff = __esm({
23111
23285
  "src/commands/workflows/diff.ts"() {
23112
23286
  "use strict";
@@ -23115,7 +23289,7 @@ var init_diff = __esm({
23115
23289
  init_columns();
23116
23290
  init_check();
23117
23291
  init_files2();
23118
- command83 = {
23292
+ command84 = {
23119
23293
  resource: "workflows",
23120
23294
  action: "diff",
23121
23295
  summary: "Compare a workflow file with the published version or the draft",
@@ -23143,7 +23317,7 @@ var init_diff = __esm({
23143
23317
  return ExitCode.Ok;
23144
23318
  }
23145
23319
  };
23146
- diff_default = command83;
23320
+ diff_default = command84;
23147
23321
  }
23148
23322
  });
23149
23323
 
@@ -23227,7 +23401,7 @@ function workflowFileSchema(stepTypes) {
23227
23401
  }
23228
23402
  };
23229
23403
  }
23230
- var SCHEMA_ID, STEP_ID, MORE_THAN_ZERO, command84, schema_default;
23404
+ var SCHEMA_ID, STEP_ID, MORE_THAN_ZERO, command85, schema_default;
23231
23405
  var init_schema = __esm({
23232
23406
  "src/commands/workflows/schema.ts"() {
23233
23407
  "use strict";
@@ -23238,7 +23412,7 @@ var init_schema = __esm({
23238
23412
  SCHEMA_ID = "https://ken.so/schemas/workflow-file.json";
23239
23413
  STEP_ID = "^[a-z][a-z0-9_]{0,39}$";
23240
23414
  MORE_THAN_ZERO = { type: "number", exclusiveMinimum: 0 };
23241
- command84 = {
23415
+ command85 = {
23242
23416
  resource: "workflows",
23243
23417
  action: "schema",
23244
23418
  summary: "Print a JSON Schema for workflow files, for editors",
@@ -23264,7 +23438,7 @@ var init_schema = __esm({
23264
23438
  return ExitCode.Ok;
23265
23439
  }
23266
23440
  };
23267
- schema_default = command84;
23441
+ schema_default = command85;
23268
23442
  }
23269
23443
  });
23270
23444
 
@@ -23362,7 +23536,7 @@ async function readRunInput(ctx, opts) {
23362
23536
  const name = opts.file ?? "";
23363
23537
  const file = await readInput(name, { stdin: ctx.stdin });
23364
23538
  const input = { path: file.path, sha256: file.sha256 };
23365
- const idColumn = file.headers.find((header) => header.trim().toLowerCase() === "id");
23539
+ const idColumn = file.headers.find((header2) => header2.trim().toLowerCase() === "id");
23366
23540
  if (idColumn !== void 0) {
23367
23541
  return { input, ...fromIds(ctx, file.rows.map((row) => String(row[idColumn] ?? "").trim()), type) };
23368
23542
  }
@@ -23467,8 +23641,8 @@ function answeredJournals(run, workflowId) {
23467
23641
  }
23468
23642
  return journals;
23469
23643
  }
23470
- async function earlierRun(ctx, args, sha2565, workflowId) {
23471
- const earlier = (await findIdentical(COMMAND7, args, sha2565, ctx.env, ctx.client.workspaceId ?? ctx.auth.workspaceId)).filter((run) => run.status !== "planned");
23644
+ async function earlierRun(ctx, args, sha2566, workflowId) {
23645
+ const earlier = (await findIdentical(COMMAND7, args, sha2566, ctx.env, ctx.client.workspaceId ?? ctx.auth.workspaceId)).filter((run) => run.status !== "planned");
23472
23646
  const open2 = earlier.find((run) => run.status !== "done");
23473
23647
  if (open2) {
23474
23648
  answeredJournals(open2, workflowId);
@@ -23573,12 +23747,233 @@ var init_run_start = __esm({
23573
23747
  }
23574
23748
  });
23575
23749
 
23750
+ // src/commands/workflows/run-results.ts
23751
+ import { createHash as createHash13 } from "node:crypto";
23752
+ import { existsSync as existsSync16, readFileSync as readFileSync22 } from "node:fs";
23753
+ import { readFile as readFile13 } from "node:fs/promises";
23754
+ import { dirname as dirname7, join as join33, resolve as resolve22 } from "node:path";
23755
+ function sha2565(content) {
23756
+ return createHash13("sha256").update(content).digest("hex");
23757
+ }
23758
+ async function isOwnResultsFile(path, env) {
23759
+ let hash;
23760
+ try {
23761
+ hash = sha2565(readFileSync22(path));
23762
+ } catch {
23763
+ return false;
23764
+ }
23765
+ for (const record3 of await listRuns(env)) {
23766
+ if (record3.command !== COMMAND7) continue;
23767
+ try {
23768
+ const marker = JSON.parse(await readFile13(join33(record3.dir, OUT_MARKER), "utf8"));
23769
+ if (marker.path === path && marker.sha256 === hash) return true;
23770
+ } catch {
23771
+ }
23772
+ }
23773
+ return false;
23774
+ }
23775
+ async function readResultFlags(ctx, flags) {
23776
+ const wait3 = flags.wait === true;
23777
+ const timeoutText = typeof flags.timeout === "string" ? flags.timeout : void 0;
23778
+ const outText = typeof flags.out === "string" ? flags.out.trim() : void 0;
23779
+ if (timeoutText !== void 0 && !wait3) throw usageError("--timeout goes with --wait.", { field: "timeout" });
23780
+ if (outText !== void 0 && !wait3) {
23781
+ throw usageError("--out needs --wait: the results file is written when the runs end.", { field: "out" });
23782
+ }
23783
+ if (outText === "") throw usageError("--out needs a file path.", { field: "out" });
23784
+ const timeoutMs2 = parseDuration(timeoutText ?? DEFAULT_TIMEOUT4);
23785
+ if (timeoutMs2 === void 0) {
23786
+ throw usageError(`--timeout "${timeoutText}" is not a duration.`, { field: "timeout", hint: "Use 90s, 10m, 1h or a number of seconds." });
23787
+ }
23788
+ const out = outText === void 0 ? void 0 : resolve22(outText);
23789
+ if (out !== void 0 && !existsSync16(dirname7(out))) throw usageError(`--out: the folder ${dirname7(out)} does not exist.`, { field: "out" });
23790
+ if (out !== void 0 && existsSync16(out) && !await isOwnResultsFile(out, ctx.env)) {
23791
+ throw new KensoError({
23792
+ code: "file_exists",
23793
+ message: `${out} already exists and is not a results file of kenso workflows run.`,
23794
+ exitCode: ExitCode.Conflict,
23795
+ field: "out",
23796
+ hint: "Pick another --out path, or delete the file first."
23797
+ });
23798
+ }
23799
+ return { wait: wait3, timeoutMs: timeoutMs2, out };
23800
+ }
23801
+ function holdSummary(ctx) {
23802
+ let held = {};
23803
+ const output = Object.create(ctx.output);
23804
+ output.summary = (value) => {
23805
+ held = value;
23806
+ };
23807
+ return { ctx: { ...ctx, output }, held: () => held };
23808
+ }
23809
+ function lastByNode(steps = []) {
23810
+ const byNode = /* @__PURE__ */ new Map();
23811
+ for (const step of steps) if (step.nodeId) byNode.set(step.nodeId, step);
23812
+ return byNode;
23813
+ }
23814
+ function missReason(run, isDataStep) {
23815
+ for (const step of lastByNode(run.steps).values()) {
23816
+ if (!step.stepType || !isDataStep(step.stepType)) continue;
23817
+ const output = step.output;
23818
+ if (output === null || typeof output !== "object" || Array.isArray(output)) continue;
23819
+ for (const key of ["status", "reason"]) {
23820
+ const value = output[key];
23821
+ if (typeof value === "string" && value.trim() !== "" && !SUCCESS_VALUES.has(value.trim().toLowerCase())) return value.trim();
23822
+ }
23823
+ }
23824
+ return void 0;
23825
+ }
23826
+ function rowRunId(row) {
23827
+ if (row.runId === void 0 || row.runId === null || row.runId === "") return void 0;
23828
+ const id = Number(row.runId);
23829
+ return Number.isSafeInteger(id) ? id : void 0;
23830
+ }
23831
+ function outRows(rows, runs, isDataStep) {
23832
+ return rows.map((row) => {
23833
+ const runId = rowRunId(row);
23834
+ const run = runId === void 0 ? void 0 : runs.get(runId);
23835
+ const steps = {};
23836
+ if (run) for (const [nodeId, step] of lastByNode(run.steps)) steps[nodeId] = step.output;
23837
+ const charged = run ? runCredits(run) : void 0;
23838
+ const missed = run ? missReason(run, isDataStep) : void 0;
23839
+ const failed = run?.steps?.find((step) => step.status === "failed");
23840
+ const error = failed ? stepErrorText(failed) : void 0;
23841
+ return {
23842
+ row: row.row,
23843
+ id: String(row.id ?? ""),
23844
+ status: String(row.status),
23845
+ ...runId !== void 0 ? { runId } : {},
23846
+ ...run?.status ? { runStatus: run.status } : {},
23847
+ ...charged !== void 0 ? { creditsCharged: charged } : {},
23848
+ ...missed ? { missReason: missed } : {},
23849
+ ...error ? { error } : {},
23850
+ steps
23851
+ };
23852
+ });
23853
+ }
23854
+ function outCsv(rows) {
23855
+ const stepIds = [];
23856
+ for (const row of rows) for (const id of Object.keys(row.steps)) if (!stepIds.includes(id)) stepIds.push(id);
23857
+ const json = (value) => value === void 0 || value === null ? "" : JSON.stringify(value);
23858
+ const lines = rows.map((row) => [...RESULT_COLUMNS2.map((column) => String(row[column] ?? "")), ...stepIds.map((id) => json(row.steps[id]))]);
23859
+ return stringify([[...RESULT_COLUMNS2, ...stepIds], ...lines]);
23860
+ }
23861
+ function isDataStepCheck() {
23862
+ let dataTypes = /* @__PURE__ */ new Set();
23863
+ try {
23864
+ dataTypes = new Set(loadStepTypes().filter((type) => type.kind === "data").map((type) => type.type));
23865
+ } catch {
23866
+ }
23867
+ return (stepType) => dataTypes.has(stepType) || stepType.startsWith("data.");
23868
+ }
23869
+ function waitedCounts(table) {
23870
+ let succeeded = 0;
23871
+ let runsFailed = 0;
23872
+ let waiting = 0;
23873
+ let charged = 0;
23874
+ const missed = {};
23875
+ for (const row of table) {
23876
+ if (row.missReason) missed[row.missReason] = (missed[row.missReason] ?? 0) + 1;
23877
+ if (!isOwnRun(row)) continue;
23878
+ if (row.runStatus === "succeeded") succeeded++;
23879
+ else if (row.runStatus !== void 0 && ENDED_UNSUCCESSFUL.has(row.runStatus)) runsFailed++;
23880
+ else waiting++;
23881
+ if (row.creditsCharged !== void 0) charged += row.creditsCharged;
23882
+ }
23883
+ return { succeeded, runsFailed, waiting, missed, creditsCharged: waiting > 0 ? "pending" : roundCredits(charged) };
23884
+ }
23885
+ async function finishRun(ctx, input) {
23886
+ const { outcome, engineSummary, workflowId, flags } = input;
23887
+ const summary = { ...engineSummary };
23888
+ const engineStopped = engineSummary.stopped !== void 0 || engineSummary.interrupted === true;
23889
+ let interrupted7 = false;
23890
+ let waitedLine = "";
23891
+ if (flags.wait) {
23892
+ const rows = [...(await readResults(outcome.resultsNdjson)).values()].sort((a, b) => a.row - b.row);
23893
+ const runIds = rows.flatMap((row) => rowRunId(row) ?? []);
23894
+ let runs = /* @__PURE__ */ new Map();
23895
+ if (!engineStopped && runIds.length > 0) {
23896
+ const waited = await waitForRuns(ctx.client, runIds, {
23897
+ timeoutMs: flags.timeoutMs,
23898
+ signal: ctx.signal,
23899
+ onProgress: (open2, total) => ctx.output.progress(`runs: ${total - open2}/${total} ended`)
23900
+ });
23901
+ runs = waited.runs;
23902
+ interrupted7 = waited.interrupted;
23903
+ if (waited.stopped) ctx.output.warn(`Stopped reading the runs (${waited.stopped}). They keep going: kenso workflow-runs list --workflow-id ${workflowId}`);
23904
+ }
23905
+ const table = outRows(rows, runs, isDataStepCheck());
23906
+ if (flags.out) {
23907
+ const text4 = outCsv(table);
23908
+ await writeFileAtomic(flags.out, text4);
23909
+ await writeJsonAtomic(join33(outcome.dir, OUT_MARKER), { path: flags.out, sha256: sha2565(text4) });
23910
+ summary.resultsCsv = flags.out;
23911
+ }
23912
+ const counts2 = waitedCounts(table);
23913
+ summary.succeeded = counts2.succeeded;
23914
+ summary.failed = Number(engineSummary.failed ?? 0) + counts2.runsFailed;
23915
+ summary.waiting = counts2.waiting;
23916
+ summary.missed = counts2.missed;
23917
+ summary.creditsCharged = counts2.creditsCharged;
23918
+ const firstFailed = table.find((row) => isOwnRun(row) && row.runStatus !== void 0 && ENDED_UNSUCCESSFUL.has(row.runStatus));
23919
+ if (!engineStopped && firstFailed?.runId !== void 0) summary.next = `kenso workflow-runs logs ${firstFailed.runId}`;
23920
+ waitedLine = `; ${counts2.succeeded} succeeded, ${counts2.waiting} waiting, ${String(counts2.creditsCharged)} credits charged`;
23921
+ }
23922
+ await writeJsonAtomic(join33(outcome.dir, "summary.json"), summary);
23923
+ ctx.output.summary(summary);
23924
+ const n = (key) => Number(summary[key] ?? 0);
23925
+ ctx.output.info(
23926
+ `workflow ${workflowId}: ${n("started")} started, ${n("deduplicated")} deduplicated, ${n("notStarted")} not started, ${n("failed")} failed of ${n("records")} records${waitedLine}`
23927
+ );
23928
+ if (interrupted7) return ExitCode.Interrupted;
23929
+ if (outcome.exitCode !== ExitCode.Ok) return outcome.exitCode;
23930
+ return n("notStarted") + n("failed") > 0 ? ExitCode.Partial : ExitCode.Ok;
23931
+ }
23932
+ var RESULT_COLUMNS2, OUT_MARKER, DEFAULT_TIMEOUT4, SUCCESS_VALUES, ENDED_UNSUCCESSFUL, isOwnRun;
23933
+ var init_run_results = __esm({
23934
+ "src/commands/workflows/run-results.ts"() {
23935
+ "use strict";
23936
+ init_sync();
23937
+ init_results();
23938
+ init_runs();
23939
+ init_errors();
23940
+ init_exit_codes();
23941
+ init_step_types();
23942
+ init_wait();
23943
+ init_run_start();
23944
+ init_run_wait();
23945
+ RESULT_COLUMNS2 = ["row", "id", "status", "runId", "runStatus", "creditsCharged", "missReason", "error"];
23946
+ OUT_MARKER = "results-out.json";
23947
+ DEFAULT_TIMEOUT4 = "30m";
23948
+ SUCCESS_VALUES = /* @__PURE__ */ new Set([
23949
+ "done",
23950
+ "fresh",
23951
+ "succeeded",
23952
+ "found",
23953
+ "verified",
23954
+ "valid",
23955
+ "catch_all",
23956
+ "unverified",
23957
+ "already_has_email",
23958
+ "already_has_phone",
23959
+ "already_queued",
23960
+ "already_accepted",
23961
+ "queued",
23962
+ "running",
23963
+ "cached",
23964
+ "checked"
23965
+ ]);
23966
+ ENDED_UNSUCCESSFUL = /* @__PURE__ */ new Set(["failed", "cancelled", "needs_attention", "over_limit"]);
23967
+ isOwnRun = (row) => row.status === "started" && row.runId !== void 0;
23968
+ }
23969
+ });
23970
+
23576
23971
  // src/commands/workflows/run.ts
23577
23972
  var run_exports4 = {};
23578
23973
  __export(run_exports4, {
23579
23974
  default: () => run_default3
23580
23975
  });
23581
- import { join as join33 } from "node:path";
23976
+ import { join as join34 } from "node:path";
23582
23977
  async function resolveTarget(ctx, target2) {
23583
23978
  const isId = /^[1-9]\d*$/.test(target2);
23584
23979
  const file = isId ? void 0 : readWorkflowFile(target2).definition;
@@ -23669,7 +24064,7 @@ function summarize4(workflowId, records, cap) {
23669
24064
  };
23670
24065
  };
23671
24066
  }
23672
- var NAME2, CHUNK_SIZE7, APP_URL, LIST_HINT, command85, run_default3;
24067
+ var NAME2, CHUNK_SIZE7, APP_URL, LIST_HINT, command86, run_default3;
23673
24068
  var init_run4 = __esm({
23674
24069
  "src/commands/workflows/run.ts"() {
23675
24070
  "use strict";
@@ -23685,17 +24080,18 @@ var init_run4 = __esm({
23685
24080
  init_files2();
23686
24081
  init_run_cap();
23687
24082
  init_run_input();
24083
+ init_run_results();
23688
24084
  init_run_start();
23689
24085
  NAME2 = `kenso ${COMMAND7}`;
23690
24086
  CHUNK_SIZE7 = 1e3;
23691
24087
  APP_URL = "https://app.ken.so";
23692
24088
  LIST_HINT = "A saved list runs through a workflow whose trigger is trigger.saved_list@1 or trigger.csv@1; kenso workflows run takes --ids or --file.";
23693
- command85 = {
24089
+ command86 = {
23694
24090
  resource: "workflows",
23695
24091
  action: "run",
23696
24092
  summary: "Run a published workflow on records from an ids file or a CSV",
23697
24093
  brief: "on ids or a CSV",
23698
- description: "Starts one run per record on the workflow's published version. The target is a workflow id, or a workflow file bound in kenso.json that equals the published version. --ids is one id per line; --file is a CSV with an id column, or for a workflow that runs on people a CSV of people (the columns of kenso people import), matched or created first. Without --yes it prints the plan with the credit estimate and starts nothing. --max-credits starts only as many records as the cap covers and reports the rest as not_started. The same command on the same input never starts its records twice; another --max-credits on that input is refused with an ids file of the records not started yet. Exit 5 when some records failed, were not found or were not started, 6 when the cap starts nothing or the workspace is out of credits, 7 when the file differs from the published version or the workflow is not live.",
24094
+ description: "Starts one run per record on the workflow's published version. The target is a workflow id, or a workflow file bound in kenso.json that equals the published version. --ids is one id per line; --file is a CSV with an id column, or for a workflow that runs on people a CSV of people (the columns of kenso people import), matched or created first. Without --yes it prints the plan with the credit estimate and starts nothing. --max-credits starts only as many records as the cap covers and reports the rest as not_started. The same command on the same input never starts its records twice; another --max-credits on that input is refused with an ids file of the records not started yet. Exit 5 when some records failed, were not found or were not started, 6 when the cap starts nothing or the workspace is out of credits, 7 when the file differs from the published version or the workflow is not live. --wait reads each started run until it ends (--timeout, default 30m); --out writes one row per record with each step's output, because a succeeded run's step outputs are dropped 7 days after it ends unless the workflow keeps success details.",
23699
24095
  effect: "send",
23700
24096
  doc: {
23701
24097
  when: "You have a published workflow and the records to run it on.",
@@ -23707,6 +24103,9 @@ var init_run4 = __esm({
23707
24103
  file: { type: "string", description: "A CSV with an id column, or a CSV of people for a workflow that runs on people" },
23708
24104
  "record-type": { type: "string", description: "account, person, lead or place (default: the type the trigger runs on)" },
23709
24105
  "max-credits": { type: "string", description: "Start only as many records as this many credits cover" },
24106
+ wait: { type: "boolean", description: "Wait for every started run to end, reading up to 8 runs at a time" },
24107
+ timeout: { type: "string", description: "With --wait: how long to wait, 90s, 10m or 1h (default 30m)" },
24108
+ out: { type: "string", description: "With --wait: write one row per input record, with each step's output, to this CSV" },
23710
24109
  // Declared only so the refusal can carry its hint: main refuses an undeclared flag before the command runs.
23711
24110
  list: { type: "string", helpHidden: true, description: "Not a flag: a saved list runs through its own trigger" }
23712
24111
  },
@@ -23714,7 +24113,8 @@ var init_run4 = __esm({
23714
24113
  examples: [
23715
24114
  "kenso workflows run qualify.workflow.json --ids ids.txt --dry-run",
23716
24115
  "kenso workflows run qualify.workflow.json --ids ids.txt --max-credits 50 --yes",
23717
- "kenso workflows run 412 --file people.csv --record-type person --dry-run"
24116
+ "kenso workflows run 412 --file people.csv --record-type person --dry-run",
24117
+ "kenso workflows run qualify.workflow.json --ids ids.txt --max-credits 10 --wait --out results.csv --yes"
23718
24118
  ],
23719
24119
  beta: { featureGates: WORKFLOWS_GATES },
23720
24120
  // workflow-runs.get is read by --wait.
@@ -23730,6 +24130,7 @@ var init_run4 = __esm({
23730
24130
  if (ids2 === void 0 === (csv === void 0)) throw usageError("Pass one of --ids and --file.", { field: "ids", next: `${NAME2} --help` });
23731
24131
  const maxCredits = maxCreditsOf(flags["max-credits"]);
23732
24132
  const apply = ctx.flags.yes === true;
24133
+ const results = await readResultFlags(ctx, flags);
23733
24134
  const target2 = await resolveTarget(ctx, positionals[0] ?? "");
23734
24135
  const { workflowId } = target2;
23735
24136
  const type = recordTypeOf(target2.definition, stringFlag(flags["record-type"]));
@@ -23752,7 +24153,8 @@ var init_run4 = __esm({
23752
24153
  const retry = (cap2) => commandLine2(ctx, COMMAND7, { flags: { ...flags, "max-credits": String(cap2) }, positionals });
23753
24154
  const capFor = (count) => maxCredits !== void 0 && ceiling !== void 0 ? planCap(maxCredits, count, hard !== void 0 ? "hard" : "estimate", ceiling, retry) : null;
23754
24155
  let cap = capFor(input.records.length);
23755
- const args = { ...flags, positionals };
24156
+ const { timeout: _timeout, out: _out, ...identity } = flags;
24157
+ const args = { ...identity, positionals };
23756
24158
  const applyCommand = commandLine2(ctx, COMMAND7, { flags, positionals }, ["--yes"]);
23757
24159
  const plan2 = {
23758
24160
  workflowId,
@@ -23773,7 +24175,7 @@ var init_run4 = __esm({
23773
24175
  rowOf: (item) => item.row,
23774
24176
  chunkSize: CHUNK_SIZE7,
23775
24177
  concurrency: 1,
23776
- execChunk: (chunk, cc) => startChunk(chunk, cc, { dirOf: (runId) => join33(runsRoot(ctx.env), runId), workflowId, start }),
24178
+ execChunk: (chunk, cc) => startChunk(chunk, cc, { dirOf: (runId) => join34(runsRoot(ctx.env), runId), workflowId, start }),
23777
24179
  invalid: invalid3,
23778
24180
  dryRun: dryRun2,
23779
24181
  dryRunExtra: plan2,
@@ -23802,14 +24204,12 @@ var init_run4 = __esm({
23802
24204
  const applied = spec(false, records, invalid2);
23803
24205
  const rerun = (ids3) => commandLine2(ctx, COMMAND7, { flags: { ...flags, ids: ids3, file: void 0 }, positionals }, ["--yes"]);
23804
24206
  await refuseRestart(ctx, { args, sha256: input.input.sha256, workflowId, items: applied.items, rerun });
23805
- const outcome = await runBatch(applied, ctx);
23806
- const s = outcome.summary;
23807
- ctx.output.info(`workflow ${workflowId}: ${s.started} started, ${s.deduplicated} deduplicated, ${s.notStarted} not started, ${s.failed} failed of ${s.records} records`);
23808
- if (outcome.exitCode !== ExitCode.Ok) return outcome.exitCode;
23809
- return Number(s.notStarted ?? 0) + Number(s.failed ?? 0) > 0 ? ExitCode.Partial : ExitCode.Ok;
24207
+ const hold = holdSummary(ctx);
24208
+ const outcome = await runBatch(applied, hold.ctx);
24209
+ return finishRun(ctx, { outcome, engineSummary: hold.held(), workflowId, flags: results });
23810
24210
  }
23811
24211
  };
23812
- run_default3 = command85;
24212
+ run_default3 = command86;
23813
24213
  }
23814
24214
  });
23815
24215
 
@@ -23826,7 +24226,7 @@ var init_run_actions = __esm({
23826
24226
 
23827
24227
  // src/commands/workflows/index.ts
23828
24228
  var actions36;
23829
- var init_workflows = __esm({
24229
+ var init_workflows2 = __esm({
23830
24230
  "src/commands/workflows/index.ts"() {
23831
24231
  "use strict";
23832
24232
  init_file_actions();
@@ -23856,7 +24256,7 @@ function rewrap(err, overrides2) {
23856
24256
  details: err.details
23857
24257
  });
23858
24258
  }
23859
- var TEMPLATES, APP_NEXT_STEP, NOT_AVAILABLE, command86, keys_default;
24259
+ var TEMPLATES, APP_NEXT_STEP, NOT_AVAILABLE, command87, keys_default;
23860
24260
  var init_keys = __esm({
23861
24261
  "src/commands/workspace/keys.ts"() {
23862
24262
  "use strict";
@@ -23866,7 +24266,7 @@ var init_keys = __esm({
23866
24266
  TEMPLATES = ["admin", "editor", "viewer"];
23867
24267
  APP_NEXT_STEP = "A workspace admin can create it in the app: Settings > API keys > Workspace keys";
23868
24268
  NOT_AVAILABLE = "Workspace keys are not available for this workspace yet.";
23869
- command86 = {
24269
+ command87 = {
23870
24270
  resource: "workspace",
23871
24271
  action: "keys",
23872
24272
  summary: "Create an API key the workspace owns",
@@ -23928,7 +24328,7 @@ var init_keys = __esm({
23928
24328
  return ExitCode.Ok;
23929
24329
  }
23930
24330
  };
23931
- keys_default = command86;
24331
+ keys_default = command87;
23932
24332
  }
23933
24333
  });
23934
24334
 
@@ -23946,14 +24346,14 @@ function parseLimit2(value) {
23946
24346
  }
23947
24347
  return limit;
23948
24348
  }
23949
- var MAX_LIMIT2, command87, list_default5;
24349
+ var MAX_LIMIT2, command88, list_default5;
23950
24350
  var init_list5 = __esm({
23951
24351
  "src/commands/workspace/list.ts"() {
23952
24352
  "use strict";
23953
24353
  init_errors();
23954
24354
  init_exit_codes();
23955
24355
  MAX_LIMIT2 = 200;
23956
- command87 = {
24356
+ command88 = {
23957
24357
  resource: "workspace",
23958
24358
  action: "list",
23959
24359
  summary: "List the workspaces your key can use",
@@ -23982,7 +24382,7 @@ var init_list5 = __esm({
23982
24382
  return ExitCode.Ok;
23983
24383
  }
23984
24384
  };
23985
- list_default5 = command87;
24385
+ list_default5 = command88;
23986
24386
  }
23987
24387
  });
23988
24388
 
@@ -23991,7 +24391,7 @@ var use_exports = {};
23991
24391
  __export(use_exports, {
23992
24392
  default: () => use_default
23993
24393
  });
23994
- var command88, use_default;
24394
+ var command89, use_default;
23995
24395
  var init_use = __esm({
23996
24396
  "src/commands/workspace/use.ts"() {
23997
24397
  "use strict";
@@ -23999,7 +24399,7 @@ var init_use = __esm({
23999
24399
  init_errors();
24000
24400
  init_exit_codes();
24001
24401
  init_http();
24002
- command88 = {
24402
+ command89 = {
24003
24403
  resource: "workspace",
24004
24404
  action: "use",
24005
24405
  summary: "Set the profile's default workspace",
@@ -24061,7 +24461,7 @@ var init_use = __esm({
24061
24461
  return ExitCode.Ok;
24062
24462
  }
24063
24463
  };
24064
- use_default = command88;
24464
+ use_default = command89;
24065
24465
  }
24066
24466
  });
24067
24467
 
@@ -24141,7 +24541,7 @@ var init_registry = __esm({
24141
24541
  init_webhooks2();
24142
24542
  init_work2();
24143
24543
  init_workflow_runs();
24144
- init_workflows();
24544
+ init_workflows2();
24145
24545
  init_workspace();
24146
24546
  handWritten = {
24147
24547
  accounts: actions,
@@ -24679,14 +25079,14 @@ var init_pre_run = __esm({
24679
25079
  });
24680
25080
 
24681
25081
  // src/core/update-notice.ts
24682
- import { mkdirSync as mkdirSync8, readFileSync as readFileSync22, realpathSync as realpathSync2, renameSync as renameSync8, writeFileSync as writeFileSync13 } from "node:fs";
24683
- import { dirname as dirname7, join as join34, sep as sep4 } from "node:path";
25082
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync23, realpathSync as realpathSync2, renameSync as renameSync8, writeFileSync as writeFileSync13 } from "node:fs";
25083
+ import { dirname as dirname8, join as join35, sep as sep4 } from "node:path";
24684
25084
  function installKind(script = process.argv[1], execPath = process.execPath, platform = process.platform) {
24685
25085
  try {
24686
25086
  if (!script) return "npm";
24687
25087
  const bundle = realpathSync2(script);
24688
- const lib = dirname7(dirname7(dirname7(bundle)));
24689
- if (execPath !== join34(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
25088
+ const lib = dirname8(dirname8(dirname8(bundle)));
25089
+ if (execPath !== join35(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
24690
25090
  return bundle.includes(`${sep4}Cellar${sep4}kenso${sep4}`) ? "homebrew" : "standalone";
24691
25091
  } catch {
24692
25092
  return "npm";
@@ -24699,7 +25099,7 @@ function updateCommand(install, platform) {
24699
25099
  }
24700
25100
  function readCheck(file) {
24701
25101
  try {
24702
- const parsed2 = JSON.parse(readFileSync22(file, "utf8"));
25102
+ const parsed2 = JSON.parse(readFileSync23(file, "utf8"));
24703
25103
  if (typeof parsed2?.checkedAt !== "string") return void 0;
24704
25104
  return { checkedAt: parsed2.checkedAt, ...typeof parsed2.latest === "string" ? { latest: parsed2.latest } : {} };
24705
25105
  } catch {
@@ -24708,7 +25108,7 @@ function readCheck(file) {
24708
25108
  }
24709
25109
  function writeCheck(file, check) {
24710
25110
  try {
24711
- mkdirSync8(dirname7(file), { recursive: true, mode: 448 });
25111
+ mkdirSync8(dirname8(file), { recursive: true, mode: 448 });
24712
25112
  const temp = `${file}.${process.pid}.tmp`;
24713
25113
  writeFileSync13(temp, `${JSON.stringify(check)}
24714
25114
  `, { mode: 384 });
@@ -24740,13 +25140,13 @@ async function fetchLatest(fetchImpl, signal, install) {
24740
25140
  return typeof body2?.version === "string" && RELEASE.test(body2.version) ? body2.version : void 0;
24741
25141
  }
24742
25142
  function agentNotice(env, agent, version, stderr, opts) {
24743
- const latest = readCheck(join34(configDir(env), UPDATE_CHECK_FILE))?.latest;
25143
+ const latest = readCheck(join35(configDir(env), UPDATE_CHECK_FILE))?.latest;
24744
25144
  if (latest === void 0 || !isNewer(latest, version)) return done;
24745
25145
  return async () => {
24746
25146
  try {
24747
25147
  if (!firstInSession(env, agent, "update")) return;
24748
- const command89 = updateCommand(opts.install ?? installKind(), opts.platform ?? process.platform);
24749
- stderr.write(`kenso ${latest} is out (you have ${version}): ${command89}
25148
+ const command90 = updateCommand(opts.install ?? installKind(), opts.platform ?? process.platform);
25149
+ stderr.write(`kenso ${latest} is out (you have ${version}): ${command90}
24750
25150
  `);
24751
25151
  } catch {
24752
25152
  }
@@ -24762,7 +25162,7 @@ function startUpdateNotice(argv, opts = {}) {
24762
25162
  const agent = detectAgent(env);
24763
25163
  if (agent !== null) return agentNotice(env, agent, version, stderr, opts);
24764
25164
  if (!(opts.stderrIsTTY ?? process.stderr.isTTY === true)) return done;
24765
- const file = join34(configDir(env), UPDATE_CHECK_FILE);
25165
+ const file = join35(configDir(env), UPDATE_CHECK_FILE);
24766
25166
  const now = (opts.now ?? Date.now)();
24767
25167
  const cached = readCheck(file);
24768
25168
  const checkedAt = Date.parse(cached?.checkedAt ?? "");
@@ -24781,8 +25181,8 @@ function startUpdateNotice(argv, opts = {}) {
24781
25181
  if (!found) return;
24782
25182
  writeCheck(file, { checkedAt: new Date(now).toISOString(), latest: found });
24783
25183
  if (isNewer(found, version)) {
24784
- const command89 = updateCommand(install, opts.platform ?? process.platform);
24785
- stderr.write(`kenso ${found} is out (you have ${version}): ${command89}
25184
+ const command90 = updateCommand(install, opts.platform ?? process.platform);
25185
+ stderr.write(`kenso ${found} is out (you have ${version}): ${command90}
24786
25186
  Turn this off with KENSO_NO_UPDATE_NOTIFIER=1.
24787
25187
  `);
24788
25188
  }