kenso 0.1.118 → 0.1.119

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/CHANGELOG.md CHANGED
@@ -4,6 +4,10 @@ What changed in the kenso CLI, newest first, by the day it changed. A new versio
4
4
 
5
5
  ## 2026-11-21
6
6
 
7
+ - tag and untag send 250 ids per bulk call so one call stays far inside the 120 s timeout
8
+ - a permission denial from bulk tag stops the run with exit 3, as the single call's 403 did
9
+ - add jitter to 429 waits so agents sharing a key do not retry in step
10
+ - contacts tag and untag send 1,000 ids per call through the bulk tag routes
7
11
  - studio push skips Markdown files Studio does not store, and a later pull replaces what push sent
8
12
  - studio pull refuses dot paths and symbolic links, and replaces only files an earlier pull wrote unless --force
9
13
  - export --view reports a failed account-views read and refuses a view the old route lists as empty
package/dist/kenso.js CHANGED
@@ -412,6 +412,10 @@ function retryAfterMs(headers) {
412
412
  function headerSafe(value) {
413
413
  return value.replace(/[^\x20-\x7E]/g, "").trim().slice(0, 64);
414
414
  }
415
+ function rateLimitJitterMs(ms, fromRetryAfter) {
416
+ if (fromRetryAfter) return Math.ceil(ms) + Math.floor(ms * 0.2 * Math.random());
417
+ return Math.floor(ms * (0.8 + 0.4 * Math.random()));
418
+ }
415
419
  function transientBackoffMs(retry) {
416
420
  return 500 * 2 ** retry + Math.floor(Math.random() * 250);
417
421
  }
@@ -529,9 +533,9 @@ var init_http = __esm({
529
533
  if (res.status === 429) {
530
534
  const remaining = this.rateLimitBudgetMs - this.rateLimitWaitedMs;
531
535
  if (remaining <= 0) throw errorFromResponse(res.status, parsed2, requestId);
532
- let wanted = retryAfterMs(res.headers);
533
- if (wanted === void 0) wanted = Math.min(MAX_RATE_LIMIT_WAIT_MS, MIN_RATE_LIMIT_WAIT_MS * 2 ** headerlessRateLimits++);
534
- const waitMs = Math.min(wanted, remaining);
536
+ const retryAfter = retryAfterMs(res.headers);
537
+ const base = retryAfter ?? Math.min(MAX_RATE_LIMIT_WAIT_MS, MIN_RATE_LIMIT_WAIT_MS * 2 ** headerlessRateLimits++);
538
+ const waitMs = Math.min(rateLimitJitterMs(base, retryAfter !== void 0), remaining);
535
539
  this.rateLimitWaitedMs += waitMs;
536
540
  this.opts.onRetry?.({ attempt, status: 429, waitMs });
537
541
  await this.wait(waitMs, callerSignal);
@@ -2477,7 +2481,7 @@ var VERSION;
2477
2481
  var init_version = __esm({
2478
2482
  "src/core/version.ts"() {
2479
2483
  "use strict";
2480
- VERSION = true ? "0.1.118" : "0.0.0-dev";
2484
+ VERSION = true ? "0.1.119" : "0.0.0-dev";
2481
2485
  }
2482
2486
  });
2483
2487
 
@@ -8768,7 +8772,7 @@ var init_auth = __esm({
8768
8772
  var batch_default;
8769
8773
  var init_batch = __esm({
8770
8774
  "docs/batch.md"() {
8771
- batch_default = '# Batch runs\n\nA batch command takes a file, sends its rows to Kenso in chunks, and prints one JSON summary. Every input row gets one line in a results file, every run can be resumed, and nothing is written until you pass `--yes`.\n\nThe batch commands:\n\n- `contacts import`, `update`, `remove`, `restore`, `pause`, `resume`, `tag`, `untag` ([Leads](leads.md))\n- `people import` and `accounts import` ([CRM](crm.md), beta)\n- `studio fill` ([Studio](studio.md), beta)\n- any generated command run with `--each <file>`, once per row (see below)\n\n## Plan, then apply\n\nWithout `--yes` a batch command plans and changes nothing. `--dry-run` asks for the plan explicitly. `--yes` applies. Passing both is a usage error. Two exceptions to the plan below: `studio fill` without `--yes` prints its credit estimate and `next`, with no run or `plan.json` ([Studio](studio.md)), and a non-GET `--each` without `--yes` or `--dry-run` is a usage error (exit 2) rather than a plan.\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThe dry run parses and checks every row, may call read-only endpoints (a campaign read, a credit estimate, a contacts search for `--where`), writes `plan.json`, and prints the plan:\n\n```json\n{"run":"r_ubqu7wtx","dryRun":true,"command":"contacts remove","rows":3,"valid":3,"invalid":0,"chunks":1,"chunkSize":1000,"source":"ids","count":3,"firstIds":[11,12,13],"next":"kenso contacts remove --ids ids.txt --yes","plan":"/home/you/.kenso/runs/r_ubqu7wtx/plan.json"}\n```\n\nEvery plan has `run`, `dryRun`, `command`, `rows`, `valid`, `invalid`, `chunks`, `chunkSize`, `next` (the exact command that applies it) and `plan` (the file), plus fields of its own command. It adds `invalidRows` when rows were refused, `chunksDone` when it continues an unfinished run, and `alreadyDone: true` when the apply would change nothing.\n\nA file the CLI cannot read stops the run before anything is planned, with `file_unreadable` (exit 2), the line at fault and a hint: `leads.csv line 3: a quote is not closed.`, `leads.csv does not exist.`, `rows.jsonl line 7 is not valid JSON.`\n\n## The summary\n\nAn applied run prints one JSON object:\n\n```json\n{"run":"r_ubqu7wtx","rows":3,"ok":2,"created":0,"updated":0,"skipped":{},"failed":0,"notFound":1,"invalid":0,"changed":2,"results":"/home/you/.kenso/runs/r_ubqu7wtx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_ubqu7wtx/results.ndjson","resumed":false,"durationMs":412,"undo":"kenso contacts restore --run r_ubqu7wtx"}\n```\n\n| Field | Meaning |\n|---|---|\n| `run` | The run id: `r_` and 8 characters |\n| `rows` | Input rows |\n| `ok`, `created`, `updated` | Rows that succeeded, by kind |\n| `skipped` | Rows Kenso left alone on purpose, counted by reason, for example `{"duplicate":12}` |\n| `failed`, `notFound`, `invalid` | Rows that did not go through: refused or errored, id not found, refused locally |\n| `changed` | Rows this invocation changed. 0 when a rerun had nothing left to do |\n| `results`, `resultsNdjson` | Absolute paths of the results files |\n| `invalidRows` | Path of `invalid.csv`, when rows were refused locally |\n| `resumed` | True when this invocation continued an earlier run |\n| `durationMs` | Wall time of this invocation |\n| `pending` | Rows without a result yet, when the run did not finish |\n| `stopped` | `{code, message, hint}` when a stop condition ended the run (for example `limit_reached`) |\n| `interrupted` | True after Ctrl-C |\n| `next` | `kenso runs resume <runId>` when the run can continue |\n\nCommands add their own fields: `contacts import` adds `campaignId` and `notSendable`, `contacts remove` adds `undo`, `people import` adds `matched`, `addedToAccounts` and `emailFindsQueued`, `accounts import` adds `researchQueued` and `researchWaitingCredits`, `studio fill` adds `templateId`, `runs` and the estimate.\n\nExit codes: 0 when every row succeeded or was skipped, 5 when some rows are `failed`, `not_found` or `invalid`, 6 when a limit stopped the run, 130 after Ctrl-C. The full table is in [Output and errors](output-and-errors.md).\n\n## The run folder\n\nEach run keeps its files in `~/.kenso/runs/<runId>/` (`KENSO_RUNS_DIR` moves the root), or in `--out <dir>` when you pass it. A run in `--out` is also linked under the runs folder, so `kenso runs` finds it. The folder is mode 0700 and its files 0600.\n\n| File | What it holds |\n|---|---|\n| `run.json` | The command, its arguments, the input path and SHA-256, the workspace, the chunk plan and the status (`planned`, `running`, `done`, `failed`, `interrupted`) |\n| `state.json` | The chunks done so far, rewritten after every chunk |\n| `results.csv` | One line per input row: `row,status,id,reason,error`, then extra columns such as `email` or `sendable` |\n| `results.ndjson` | The same rows as JSON lines |\n| `invalid.csv` | Rows refused before sending, with the reason |\n| `plan.json` | The last dry run\'s plan |\n| `summary.json` | The last summary printed |\n\n`row` is the 1-based number of the data row in the input (the CSV header is not counted). `status` is one of `created`, `updated`, `ok`, `skipped`, `failed`, `not_found` or `invalid`.\n\n```bash\nkenso runs list\nkenso runs list --limit 5 -o json\nkenso runs show r_ubqu7wtx\n```\n\n## Rerun and resume\n\nA run is identified by its command, its arguments, the SHA-256 of its input file, the workspace and the chunk size. `--yes`, `--dry-run`, `--wait`, `--concurrency` and the output flags are not part of it. Running the same command again on the same file:\n\n- **continues an unfinished run** (interrupted, stopped or crashed): finished chunks are skipped and the summary says `"resumed":true`.\n- **answers from a finished run where every row succeeded:** it prints that run\'s summary with `"changed":0` and `"alreadyDone":true`, sends no writes and exits 0 (a command may still read first: `contacts import` reads the campaign, and `contacts update --match email` looks up the campaign\'s contacts).\n- **starts a new run** when the last one finished with failed or invalid rows, or when the file changed. Lead, people and account writes match existing records (an email in a campaign, a person by email or LinkedIn URL, an account by domain), so sending a row twice never creates a duplicate.\n\n`kenso runs resume <runId>` does the same from the run id: it rebuilds the command from `run.json` and runs it with `--yes` from the folder it started in. It refuses when the input was stdin, or the file is gone or changed. Two processes cannot work on one run: the second gets `run_in_progress` (exit 7).\n\n```bash\nkenso runs resume r_ubqu7wtx\n```\n\n`studio fill` is the exception: a fill charges for every page it builds, so it never fills the same ids twice. See [Studio](studio.md).\n\n## Ctrl-C\n\nThe first Ctrl-C cancels the requests in flight and starts no new chunks. The CLI writes the state and prints the summary with `"interrupted":true` and `"next":"kenso runs resume <runId>"`, then exits 130. A chunk that did not finish is sent again when you resume, which is safe because the writes match existing records. A second Ctrl-C quits at once.\n\n## Chunks, concurrency and rate limits\n\n| Command | Rows per call | At once |\n|---|---|---|\n| `contacts import` | 1,000 | 1 per campaign |\n| `contacts update`, `remove`, `restore`, `pause`, `resume` | 1,000 | 4 (`--concurrency`) |\n| `contacts tag`, `untag` | 1 per call, 25 per chunk | 4 chunks (`--concurrency`) |\n| `people import` | 200 | 4 (`--concurrency`) |\n| `accounts import` | 100 | 4 (`--concurrency`) |\n| `studio fill` | 500 ids per fill run | 1 |\n| `--each` | 1 | 4 (`--concurrency`) |\n\n`--concurrency` takes 1 to 16. When the API\'s `RateLimit-Remaining` header drops below 10, the CLI sends one chunk at a time until it is back above 30.\n\nRetries:\n\n- **429:** the CLI waits for `Retry-After` (at least 1 second, at most 60 seconds per wait) and tries again, with up to 15 minutes of waiting per command. After that it exits 6 (`rate_limited`).\n- **502, 503, 504 and network errors:** up to 3 retries with backoff, for GET, PUT, PATCH and DELETE, and for the POST routes the CLI knows are safe to repeat.\n- **`contacts import`:** no quick retry. After a 5xx or a dropped connection it waits 130 seconds, longer than the gateway\'s request timeout, and resends the chunk once.\n- **`contacts remove`:** after a 5xx or a dropped connection it waits 2 seconds and resends once. Ids the first call already removed are reported `ok` (reason `already_removed`), so the undo still restores them.\n- **Other 4xx answers:** never retried. The row or chunk is marked `failed` with the API\'s code.\n\nKenso answers a bulk call with 200 even when some items fail, so the CLI reads each item\'s result and never trusts the HTTP status alone.\n\n## Progress\n\nProgress goes to stderr, at most one line every 2 seconds (`chunk 7/20, 7000 rows, 6 failed`), and only when stderr is a terminal or you pass `--progress`. An agent gets only the summary.\n\n## Run any API operation once per row: --each\n\nEvery generated command takes `--each <file>`, a CSV or JSONL file or `-` for stdin. The command runs once per row through the same engine: one results line per row, resume, `--concurrency`. Row keys fill the route, query and body by API name (`accountId`) or flag name (`account-id`). A blank cell is left out and the literal `null` sends null. A GET runs right away; any other method needs `--yes` or `--dry-run`.\n\n```bash\nkenso accounts update --each stages.csv --dry-run\nkenso accounts update --each stages.csv --yes --concurrency 8\n```\n\nWith `stages.csv`:\n\n```csv\naccountId,stage,overwritePinned\n501,engaged,true\n502,customer,true\n```\n\nEach row is `ok` on a 2xx answer (with the created or returned id), `not_found` on 404, `failed` otherwise, or `invalid` when a required value is missing.\n\n## The token-saving pattern for agents\n\n1. Pass a file path, never the rows: `--file leads.csv`.\n2. Run `--dry-run`, read the plan, then run its `next`.\n3. Read the summary. If `failed`, `notFound` and `invalid` are 0, you are done.\n4. Otherwise read only the problem rows, for example `grep -E \'^[0-9]+,(failed|not_found|invalid),\' results.csv | head -50`, or `invalid.csv`.\n';
8775
+ batch_default = '# Batch runs\n\nA batch command takes a file, sends its rows to Kenso in chunks, and prints one JSON summary. Every input row gets one line in a results file, every run can be resumed, and nothing is written until you pass `--yes`.\n\nThe batch commands:\n\n- `contacts import`, `update`, `remove`, `restore`, `pause`, `resume`, `tag`, `untag` ([Leads](leads.md))\n- `people import` and `accounts import` ([CRM](crm.md), beta)\n- `studio fill` ([Studio](studio.md), beta)\n- any generated command run with `--each <file>`, once per row (see below)\n\n## Plan, then apply\n\nWithout `--yes` a batch command plans and changes nothing. `--dry-run` asks for the plan explicitly. `--yes` applies. Passing both is a usage error. Two exceptions to the plan below: `studio fill` without `--yes` prints its credit estimate and `next`, with no run or `plan.json` ([Studio](studio.md)), and a non-GET `--each` without `--yes` or `--dry-run` is a usage error (exit 2) rather than a plan.\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThe dry run parses and checks every row, may call read-only endpoints (a campaign read, a credit estimate, a contacts search for `--where`), writes `plan.json`, and prints the plan:\n\n```json\n{"run":"r_ubqu7wtx","dryRun":true,"command":"contacts remove","rows":3,"valid":3,"invalid":0,"chunks":1,"chunkSize":1000,"source":"ids","count":3,"firstIds":[11,12,13],"next":"kenso contacts remove --ids ids.txt --yes","plan":"/home/you/.kenso/runs/r_ubqu7wtx/plan.json"}\n```\n\nEvery plan has `run`, `dryRun`, `command`, `rows`, `valid`, `invalid`, `chunks`, `chunkSize`, `next` (the exact command that applies it) and `plan` (the file), plus fields of its own command. It adds `invalidRows` when rows were refused, `chunksDone` when it continues an unfinished run, and `alreadyDone: true` when the apply would change nothing.\n\nA file the CLI cannot read stops the run before anything is planned, with `file_unreadable` (exit 2), the line at fault and a hint: `leads.csv line 3: a quote is not closed.`, `leads.csv does not exist.`, `rows.jsonl line 7 is not valid JSON.`\n\n## The summary\n\nAn applied run prints one JSON object:\n\n```json\n{"run":"r_ubqu7wtx","rows":3,"ok":2,"created":0,"updated":0,"skipped":{},"failed":0,"notFound":1,"invalid":0,"changed":2,"results":"/home/you/.kenso/runs/r_ubqu7wtx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_ubqu7wtx/results.ndjson","resumed":false,"durationMs":412,"undo":"kenso contacts restore --run r_ubqu7wtx"}\n```\n\n| Field | Meaning |\n|---|---|\n| `run` | The run id: `r_` and 8 characters |\n| `rows` | Input rows |\n| `ok`, `created`, `updated` | Rows that succeeded, by kind |\n| `skipped` | Rows Kenso left alone on purpose, counted by reason, for example `{"duplicate":12}` |\n| `failed`, `notFound`, `invalid` | Rows that did not go through: refused or errored, id not found, refused locally |\n| `changed` | Rows this invocation changed. 0 when a rerun had nothing left to do |\n| `results`, `resultsNdjson` | Absolute paths of the results files |\n| `invalidRows` | Path of `invalid.csv`, when rows were refused locally |\n| `resumed` | True when this invocation continued an earlier run |\n| `durationMs` | Wall time of this invocation |\n| `pending` | Rows without a result yet, when the run did not finish |\n| `stopped` | `{code, message, hint}` when a stop condition ended the run (for example `limit_reached`) |\n| `interrupted` | True after Ctrl-C |\n| `next` | `kenso runs resume <runId>` when the run can continue |\n\nCommands add their own fields: `contacts import` adds `campaignId` and `notSendable`, `contacts remove` adds `undo`, `people import` adds `matched`, `addedToAccounts` and `emailFindsQueued`, `accounts import` adds `researchQueued` and `researchWaitingCredits`, `studio fill` adds `templateId`, `runs` and the estimate.\n\nExit codes: 0 when every row succeeded or was skipped, 5 when some rows are `failed`, `not_found` or `invalid`, 6 when a limit stopped the run, 130 after Ctrl-C. The full table is in [Output and errors](output-and-errors.md).\n\n## The run folder\n\nEach run keeps its files in `~/.kenso/runs/<runId>/` (`KENSO_RUNS_DIR` moves the root), or in `--out <dir>` when you pass it. A run in `--out` is also linked under the runs folder, so `kenso runs` finds it. The folder is mode 0700 and its files 0600.\n\n| File | What it holds |\n|---|---|\n| `run.json` | The command, its arguments, the input path and SHA-256, the workspace, the chunk plan and the status (`planned`, `running`, `done`, `failed`, `interrupted`) |\n| `state.json` | The chunks done so far, rewritten after every chunk |\n| `results.csv` | One line per input row: `row,status,id,reason,error`, then extra columns such as `email` or `sendable` |\n| `results.ndjson` | The same rows as JSON lines |\n| `invalid.csv` | Rows refused before sending, with the reason |\n| `plan.json` | The last dry run\'s plan |\n| `summary.json` | The last summary printed |\n\n`row` is the 1-based number of the data row in the input (the CSV header is not counted). `status` is one of `created`, `updated`, `ok`, `skipped`, `failed`, `not_found` or `invalid`.\n\n```bash\nkenso runs list\nkenso runs list --limit 5 -o json\nkenso runs show r_ubqu7wtx\n```\n\n## Rerun and resume\n\nA run is identified by its command, its arguments, the SHA-256 of its input file, the workspace and the chunk size. `--yes`, `--dry-run`, `--wait`, `--concurrency` and the output flags are not part of it. Running the same command again on the same file:\n\n- **continues an unfinished run** (interrupted, stopped or crashed): finished chunks are skipped and the summary says `"resumed":true`.\n- **answers from a finished run where every row succeeded:** it prints that run\'s summary with `"changed":0` and `"alreadyDone":true`, sends no writes and exits 0 (a command may still read first: `contacts import` reads the campaign, and `contacts update --match email` looks up the campaign\'s contacts).\n- **starts a new run** when the last one finished with failed or invalid rows, or when the file changed. Lead, people and account writes match existing records (an email in a campaign, a person by email or LinkedIn URL, an account by domain), so sending a row twice never creates a duplicate.\n\n`kenso runs resume <runId>` does the same from the run id: it rebuilds the command from `run.json` and runs it with `--yes` from the folder it started in. It refuses when the input was stdin, or the file is gone or changed. Two processes cannot work on one run: the second gets `run_in_progress` (exit 7).\n\n```bash\nkenso runs resume r_ubqu7wtx\n```\n\n`studio fill` is the exception: a fill charges for every page it builds, so it never fills the same ids twice. See [Studio](studio.md).\n\n## Ctrl-C\n\nThe first Ctrl-C cancels the requests in flight and starts no new chunks. The CLI writes the state and prints the summary with `"interrupted":true` and `"next":"kenso runs resume <runId>"`, then exits 130. A chunk that did not finish is sent again when you resume, which is safe because the writes match existing records. A second Ctrl-C quits at once.\n\n## Chunks, concurrency and rate limits\n\n| Command | Rows per call | At once |\n|---|---|---|\n| `contacts import` | 1,000 | 1 per campaign |\n| `contacts update`, `remove`, `restore`, `pause`, `resume` | 1,000 | 4 (`--concurrency`) |\n| `contacts tag`, `untag` | 250 | 4 (`--concurrency`) |\n| `people import` | 200 | 4 (`--concurrency`) |\n| `accounts import` | 100 | 4 (`--concurrency`) |\n| `studio fill` | 500 ids per fill run | 1 |\n| `--each` | 1 | 4 (`--concurrency`) |\n\n`--concurrency` takes 1 to 16. When the API\'s `RateLimit-Remaining` header drops below 10, the CLI sends one chunk at a time until it is back above 30.\n\nRetries:\n\n- **429:** the CLI waits for `Retry-After` (at least 1 second, at most 60 seconds) plus a random 0 to 20%, so several agents on one key do not all retry at the same moment, and tries again, with up to 15 minutes of waiting per command. After that it exits 6 (`rate_limited`).\n- **502, 503, 504 and network errors:** up to 3 retries with backoff, for GET, PUT, PATCH and DELETE, and for the POST routes the CLI knows are safe to repeat.\n- **`contacts import`:** no quick retry. After a 5xx or a dropped connection it waits 130 seconds, longer than the gateway\'s request timeout, and resends the chunk once.\n- **`contacts remove`:** after a 5xx or a dropped connection it waits 2 seconds and resends once. Ids the first call already removed are reported `ok` (reason `already_removed`), so the undo still restores them.\n- **Other 4xx answers:** never retried. The row or chunk is marked `failed` with the API\'s code.\n\nKenso answers a bulk call with 200 even when some items fail, so the CLI reads each item\'s result and never trusts the HTTP status alone.\n\n## Progress\n\nProgress goes to stderr, at most one line every 2 seconds (`chunk 7/20, 7000 rows, 6 failed`), and only when stderr is a terminal or you pass `--progress`. An agent gets only the summary.\n\n## Run any API operation once per row: --each\n\nEvery generated command takes `--each <file>`, a CSV or JSONL file or `-` for stdin. The command runs once per row through the same engine: one results line per row, resume, `--concurrency`. Row keys fill the route, query and body by API name (`accountId`) or flag name (`account-id`). A blank cell is left out and the literal `null` sends null. A GET runs right away; any other method needs `--yes` or `--dry-run`.\n\n```bash\nkenso accounts update --each stages.csv --dry-run\nkenso accounts update --each stages.csv --yes --concurrency 8\n```\n\nWith `stages.csv`:\n\n```csv\naccountId,stage,overwritePinned\n501,engaged,true\n502,customer,true\n```\n\nEach row is `ok` on a 2xx answer (with the created or returned id), `not_found` on 404, `failed` otherwise, or `invalid` when a required value is missing.\n\n## The token-saving pattern for agents\n\n1. Pass a file path, never the rows: `--file leads.csv`.\n2. Run `--dry-run`, read the plan, then run its `next`.\n3. Read the summary. If `failed`, `notFound` and `invalid` are 0, you are done.\n4. Otherwise read only the problem rows, for example `grep -E \'^[0-9]+,(failed|not_found|invalid),\' results.csv | head -50`, or `invalid.csv`.\n';
8772
8776
  }
8773
8777
  });
8774
8778
 
@@ -8792,7 +8796,7 @@ var init_crm = __esm({
8792
8796
  var leads_default;
8793
8797
  var init_leads = __esm({
8794
8798
  "docs/leads.md"() {
8795
- leads_default = '# Leads\n\nLeads are contacts in a campaign. The lead commands live under `kenso contacts`, and `kenso leads` is the same thing: `kenso leads import` runs `kenso contacts import`.\n\n| Command | What it does |\n|---|---|\n| `contacts import` | Add leads from a CSV or JSONL file to a campaign, with one result per row |\n| `contacts update` | Edit leads in bulk from a file, matched by id or by email |\n| `contacts remove` / `restore` | Remove (soft-delete) leads by id, and undo it |\n| `contacts pause` / `resume` | Pause and resume the campaign sequence of leads (pause is beta, `pause_leads` flag) |\n| `contacts tag` / `untag` | Add or remove a tag on leads by id |\n| `contacts export` | Download a campaign\'s leads as one CSV file |\n\nAll of them except `export` are batch commands: without `--yes` they print a plan and change nothing. [Batch runs](batch.md) explains plans, run folders, results files and resume.\n\n## Import a CSV into a campaign\n\n```bash\nkenso contacts import --template\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`--template` prints the accepted columns. A minimal file:\n\n```csv\nemail,firstName,lastName,companyName,Pain Point\nann@acme.io,Ann,Lee,Acme,Slow onboarding\ncid@globex.com,Cid,Moe,Globex,Churn\n```\n\n### Columns\n\nHeaders are matched without regard to case, spaces or punctuation. The known fields and the other headers each one reads:\n\n| Field | Also read from | Rule |\n|---|---|---|\n| `email` | email address, e-mail, work email | Required, unless the campaign is LinkedIn-only and the row has a linkedin.com/in/ URL |\n| `firstName` | first name, first, given name | Required |\n| `lastName` | last name, last, surname, family name | Required |\n| `title` | job title, position, role | Optional |\n| `linkedInUrl` | linkedin, linkedin url, linkedin profile, profile url | Optional |\n| `companyName` | company, organization, account, account name | `companyName` or `companyDomain` is required |\n| `companyDomain` | website, domain, company website, url | `companyName` or `companyDomain` is required |\n\nEvery other column becomes a custom variable, named like its header in snake_case: a `Pain Point` column fills `{{pain_point}}` in your sequence. Names Kenso keeps for its own fields (`city`, `country`, `phone_number` and others) are not sent: the CLI warns and the plan lists them under `droppedColumns`. Rename them with `--map`.\n\n### Cells\n\n- A blank cell is never sent, so importing a file never erases data on a lead that is already in the campaign.\n- The literal value `null` clears a custom variable.\n\n### Rename or drop columns with --map\n\n`--map` takes a JSON object, `@file` or `-` for stdin. A value names the target field, and `null` drops the column:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --map \'{"Pain": "customVariables.pain_point", "Notes": null}\' --yes\n```\n\n### JSONL\n\nEach line is one lead. Keys work like CSV headers, and a `customVariables` object is spread into custom variables:\n\n```json\n{"email":"ann@acme.io","firstName":"Ann","lastName":"Lee","companyName":"Acme","customVariables":{"pain_point":"Slow onboarding"}}\n```\n\n```bash\nkenso contacts import --campaign 812 --file leads.jsonl --yes\ncat leads.jsonl | kenso contacts import --campaign 812 --file - --yes\n```\n\nA run read from stdin cannot be resumed with `kenso runs resume`, so prefer a file for large imports.\n\n### What the CLI checks before sending\n\nEvery row is checked locally first. A row that fails goes to `invalid.csv` with one of these reasons and is not sent:\n\n| Reason | Meaning |\n|---|---|\n| `missing_email` | The row has no email (and is not a LinkedIn-only lead) |\n| `invalid_email` | The email is not a valid address |\n| `missing_first_name` | The row has no first name |\n| `missing_last_name` | The row has no last name |\n| `missing_company` | The row has neither a company name nor a company domain |\n| `sales_navigator_url` | An email-less row whose LinkedIn URL is a Sales Navigator link: add the email or a linkedin.com/in/ URL |\n| `duplicate_in_file` | An earlier row of the file has the same email |\n\nKenso stays the authority and checks every row again.\n\n### What the dry run shows\n\nThe dry run maps the columns, checks the rows, reads the campaign, and asks for a credit estimate (`credit-estimates create`, kind `leads`). Its plan holds `rows`, `valid`, `invalid`, `mapping`, `customVariableKeys`, `estimate`, `credits` (`needed`, `available`, `sufficient`) and `next`, the exact apply command. If the estimate call fails, the plan still prints with `"estimate":null` and an `estimateError`.\n\n### How rows are sent\n\nThe CLI sends 1,000 rows per call to `POST /v1/campaigns/{campaignId}/contacts`, one call at a time per campaign, because two overlapping upserts of the same email could create duplicates. After a 5xx answer or a dropped connection it does not retry right away: it waits 130 seconds, so the first request has finished on the server, then resends the chunk once. Rows the first request saved come back `updated`.\n\n### Reading the result\n\nEach row in `results.csv` gets one status:\n\n| Status | Meaning |\n|---|---|\n| `created` | A new lead in the campaign |\n| `updated` | The lead was already there and was updated |\n| `skipped` | Kenso kept the lead out on purpose. `reason` is `duplicate`, `blocklisted`, `already_contacted`, `excluded` or another code |\n| `failed` | Kenso refused the row (`reason` such as `invalid_email` or `validation`, and an `error` message), or the call failed |\n| `invalid` | The CLI refused the row before sending it (see the table above) |\n\nA saved lead that cannot be emailed yet has `sendable` false, and the summary counts those leads in `notSendable` with a warning on stderr.\n\nExit codes: 0 when no row failed (skipped rows are not failures), 5 when some rows failed or were invalid, 6 when the plan\'s or campaign\'s lead limit stopped the run (`limit_reached`; raise the limit, then rerun the same command to send the rest).\n\n## Import a very large file on the server\n\nFor up to 100,000 rows, `--server-import` uploads the CSV as one server import job and waits for it (default 30 minutes, `--timeout`). It reports the job\'s counts but no per-row results.\n\n```bash\nkenso contacts import --campaign 812 --file big.csv --server-import --yes\nkenso contacts import --campaign 812 --file big.csv --server-import --timeout 1h --yes\n```\n\n## Update leads in bulk\n\n```bash\nkenso contacts update --file edits.csv --match id\nkenso contacts update --file edits.csv --match id --yes\nkenso contacts update --file edits.csv --match email --campaign 812 --yes\n```\n\n- `--match id` reads the contact id from an `id` or `contactId` column.\n- `--match email` finds each email among the leads of `--campaign`. An email it cannot find is `not_found`. The email column only finds the lead; it is never sent as an edit.\n- A column that is absent, or a blank cell, leaves that field unchanged. The literal `null` clears it.\n- The lead fields you can edit are `firstName`, `lastName`, `title`, `linkedInUrl`, and `email` with `--match id`. `companyName` and `companyDomain` cannot change here and are not sent. Every other column is a custom variable, mapped the same way as in an import, and `--map` works here too.\n- A row with nothing to change is `skipped` with reason `no_changes` and is not sent. Rows go 1,000 per call to `POST /v1/contacts/bulk-update`.\n\nTo edit one lead, use a one-row file from stdin:\n\n```bash\nprintf \'id,title\\n9001,VP Sales\\n\' | kenso contacts update --file - --match id --yes\n```\n\n## Remove, restore, pause and resume\n\nThese four take contact ids from `--ids` (one id per line, or a CSV or JSONL file with an `id` or `contactId` column, or `-` for stdin), or from a search with `--where` (remove, pause and resume). `--where` takes the body of `POST /v1/contacts/search` as JSON, `@file` or `-`, and does the search itself: its plan shows how many contacts match and the first ids, so run no separate search or list first. `q` matches names and email addresses only; a company is a `filters` condition on `ContactCompany.Name` (`operator` 2 is contains; `kenso describe contacts search` lists the fields and operators).\n\n```bash\nkenso contacts remove --ids ids.txt --dry-run\nkenso contacts remove --ids ids.txt --yes\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --dry-run\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --yes\nkenso contacts remove --ids big.csv --confirm 2500 --yes\n```\n\n- Without `--yes`, the plan prints the count and the first ids.\n- Removing more than 1,000 contacts also needs `--confirm <count>`, and the count must match. The plan\'s `next` already carries the right `--confirm`.\n- Each id comes back `ok`, `skipped` when there was nothing to do (for example `not_deleted` when you restore a contact that is not removed), `not_found` or `failed`.\n- The remove summary carries the undo command, `"undo":"kenso contacts restore --run r_ubqu7wtx"`.\n\n```bash\nkenso contacts restore --run r_ubqu7wtx --yes\nkenso contacts restore --ids ids.txt --yes\nkenso contacts pause --where \'{"campaignIds": [812]}\' --yes\nkenso contacts resume --ids ids.txt --yes\n```\n\n`restore` takes `--ids` or `--run <runId>` of an earlier remove, not `--where`: a search cannot find removed contacts. `pause` is a beta command for workspaces with the `pause_leads` flag.\n\n## Tag and untag\n\n```bash\nkenso tags list\nkenso contacts tag --tag 31 --ids ids.txt --yes\nkenso contacts untag --tag 31 --ids ids.txt --yes\n```\n\n`tag` calls `POST /v1/tags/{tagId}/assignments` once per contact. A contact that already has the tag is `skipped` with reason `already_tagged`.\n\n## Export a campaign\'s leads\n\n```bash\nkenso contacts export --campaign 812 --out contacts.csv\nkenso contacts export --campaign 812 --wait\n```\n\nWith `--out`, the CLI creates the export, waits for the job (default 30 minutes, `--timeout`) and writes one CSV file (mode 0600). An audience-based campaign exports one CSV per segment in a ZIP: the CLI saves the ZIP as it came, prints `"format": "zip"` and its size instead of a row count, and warns when `--out` does not end in `.zip`. Without `--out` it prints the export job; `--wait` waits for it, or run the `next` it prints, `kenso jobs wait <jobId> --type contact_export`.\n\n## Recipes\n\n**Tag every lead of a campaign.** List the ids, then tag them:\n\n```bash\nkenso contacts list --campaign-id 812 --all -o ids > ids.txt\nkenso contacts tag --tag 31 --ids ids.txt --yes\n```\n\n**Fix the invalid rows and send them.** `invalid.csv` keeps each refused row\'s number and reason. Fix those rows in a new file and import it. Rerunning the original file also works: rows Kenso already saved come back `updated` or `skipped`.\n\n**Retry only what failed.** Filter `results.csv` to the `failed` rows, take those rows from the input by `row` number, and import that file.\n\n**Pause leads who replied elsewhere.** Plan with the filter (the plan shows the count), then apply:\n\n```bash\nkenso contacts pause --where @replied.json\nkenso contacts pause --where @replied.json --yes\n```\n\n**Edit one field on many leads by email.**\n\n```bash\nkenso contacts update --file titles.csv --match email --campaign 812 --dry-run\nkenso contacts update --file titles.csv --match email --campaign 812 --yes\n```\n';
8799
+ leads_default = '# Leads\n\nLeads are contacts in a campaign. The lead commands live under `kenso contacts`, and `kenso leads` is the same thing: `kenso leads import` runs `kenso contacts import`.\n\n| Command | What it does |\n|---|---|\n| `contacts import` | Add leads from a CSV or JSONL file to a campaign, with one result per row |\n| `contacts update` | Edit leads in bulk from a file, matched by id or by email |\n| `contacts remove` / `restore` | Remove (soft-delete) leads by id, and undo it |\n| `contacts pause` / `resume` | Pause and resume the campaign sequence of leads (pause is beta, `pause_leads` flag) |\n| `contacts tag` / `untag` | Add or remove a tag on leads by id |\n| `contacts export` | Download a campaign\'s leads as one CSV file |\n\nAll of them except `export` are batch commands: without `--yes` they print a plan and change nothing. [Batch runs](batch.md) explains plans, run folders, results files and resume.\n\n## Import a CSV into a campaign\n\n```bash\nkenso contacts import --template\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`--template` prints the accepted columns. A minimal file:\n\n```csv\nemail,firstName,lastName,companyName,Pain Point\nann@acme.io,Ann,Lee,Acme,Slow onboarding\ncid@globex.com,Cid,Moe,Globex,Churn\n```\n\n### Columns\n\nHeaders are matched without regard to case, spaces or punctuation. The known fields and the other headers each one reads:\n\n| Field | Also read from | Rule |\n|---|---|---|\n| `email` | email address, e-mail, work email | Required, unless the campaign is LinkedIn-only and the row has a linkedin.com/in/ URL |\n| `firstName` | first name, first, given name | Required |\n| `lastName` | last name, last, surname, family name | Required |\n| `title` | job title, position, role | Optional |\n| `linkedInUrl` | linkedin, linkedin url, linkedin profile, profile url | Optional |\n| `companyName` | company, organization, account, account name | `companyName` or `companyDomain` is required |\n| `companyDomain` | website, domain, company website, url | `companyName` or `companyDomain` is required |\n\nEvery other column becomes a custom variable, named like its header in snake_case: a `Pain Point` column fills `{{pain_point}}` in your sequence. Names Kenso keeps for its own fields (`city`, `country`, `phone_number` and others) are not sent: the CLI warns and the plan lists them under `droppedColumns`. Rename them with `--map`.\n\n### Cells\n\n- A blank cell is never sent, so importing a file never erases data on a lead that is already in the campaign.\n- The literal value `null` clears a custom variable.\n\n### Rename or drop columns with --map\n\n`--map` takes a JSON object, `@file` or `-` for stdin. A value names the target field, and `null` drops the column:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --map \'{"Pain": "customVariables.pain_point", "Notes": null}\' --yes\n```\n\n### JSONL\n\nEach line is one lead. Keys work like CSV headers, and a `customVariables` object is spread into custom variables:\n\n```json\n{"email":"ann@acme.io","firstName":"Ann","lastName":"Lee","companyName":"Acme","customVariables":{"pain_point":"Slow onboarding"}}\n```\n\n```bash\nkenso contacts import --campaign 812 --file leads.jsonl --yes\ncat leads.jsonl | kenso contacts import --campaign 812 --file - --yes\n```\n\nA run read from stdin cannot be resumed with `kenso runs resume`, so prefer a file for large imports.\n\n### What the CLI checks before sending\n\nEvery row is checked locally first. A row that fails goes to `invalid.csv` with one of these reasons and is not sent:\n\n| Reason | Meaning |\n|---|---|\n| `missing_email` | The row has no email (and is not a LinkedIn-only lead) |\n| `invalid_email` | The email is not a valid address |\n| `missing_first_name` | The row has no first name |\n| `missing_last_name` | The row has no last name |\n| `missing_company` | The row has neither a company name nor a company domain |\n| `sales_navigator_url` | An email-less row whose LinkedIn URL is a Sales Navigator link: add the email or a linkedin.com/in/ URL |\n| `duplicate_in_file` | An earlier row of the file has the same email |\n\nKenso stays the authority and checks every row again.\n\n### What the dry run shows\n\nThe dry run maps the columns, checks the rows, reads the campaign, and asks for a credit estimate (`credit-estimates create`, kind `leads`). Its plan holds `rows`, `valid`, `invalid`, `mapping`, `customVariableKeys`, `estimate`, `credits` (`needed`, `available`, `sufficient`) and `next`, the exact apply command. If the estimate call fails, the plan still prints with `"estimate":null` and an `estimateError`.\n\n### How rows are sent\n\nThe CLI sends 1,000 rows per call to `POST /v1/campaigns/{campaignId}/contacts`, one call at a time per campaign, because two overlapping upserts of the same email could create duplicates. After a 5xx answer or a dropped connection it does not retry right away: it waits 130 seconds, so the first request has finished on the server, then resends the chunk once. Rows the first request saved come back `updated`.\n\n### Reading the result\n\nEach row in `results.csv` gets one status:\n\n| Status | Meaning |\n|---|---|\n| `created` | A new lead in the campaign |\n| `updated` | The lead was already there and was updated |\n| `skipped` | Kenso kept the lead out on purpose. `reason` is `duplicate`, `blocklisted`, `already_contacted`, `excluded` or another code |\n| `failed` | Kenso refused the row (`reason` such as `invalid_email` or `validation`, and an `error` message), or the call failed |\n| `invalid` | The CLI refused the row before sending it (see the table above) |\n\nA saved lead that cannot be emailed yet has `sendable` false, and the summary counts those leads in `notSendable` with a warning on stderr.\n\nExit codes: 0 when no row failed (skipped rows are not failures), 5 when some rows failed or were invalid, 6 when the plan\'s or campaign\'s lead limit stopped the run (`limit_reached`; raise the limit, then rerun the same command to send the rest).\n\n## Import a very large file on the server\n\nFor up to 100,000 rows, `--server-import` uploads the CSV as one server import job and waits for it (default 30 minutes, `--timeout`). It reports the job\'s counts but no per-row results.\n\n```bash\nkenso contacts import --campaign 812 --file big.csv --server-import --yes\nkenso contacts import --campaign 812 --file big.csv --server-import --timeout 1h --yes\n```\n\n## Update leads in bulk\n\n```bash\nkenso contacts update --file edits.csv --match id\nkenso contacts update --file edits.csv --match id --yes\nkenso contacts update --file edits.csv --match email --campaign 812 --yes\n```\n\n- `--match id` reads the contact id from an `id` or `contactId` column.\n- `--match email` finds each email among the leads of `--campaign`. An email it cannot find is `not_found`. The email column only finds the lead; it is never sent as an edit.\n- A column that is absent, or a blank cell, leaves that field unchanged. The literal `null` clears it.\n- The lead fields you can edit are `firstName`, `lastName`, `title`, `linkedInUrl`, and `email` with `--match id`. `companyName` and `companyDomain` cannot change here and are not sent. Every other column is a custom variable, mapped the same way as in an import, and `--map` works here too.\n- A row with nothing to change is `skipped` with reason `no_changes` and is not sent. Rows go 1,000 per call to `POST /v1/contacts/bulk-update`.\n\nTo edit one lead, use a one-row file from stdin:\n\n```bash\nprintf \'id,title\\n9001,VP Sales\\n\' | kenso contacts update --file - --match id --yes\n```\n\n## Remove, restore, pause and resume\n\nThese four take contact ids from `--ids` (one id per line, or a CSV or JSONL file with an `id` or `contactId` column, or `-` for stdin), or from a search with `--where` (remove, pause and resume). `--where` takes the body of `POST /v1/contacts/search` as JSON, `@file` or `-`, and does the search itself: its plan shows how many contacts match and the first ids, so run no separate search or list first. `q` matches names and email addresses only; a company is a `filters` condition on `ContactCompany.Name` (`operator` 2 is contains; `kenso describe contacts search` lists the fields and operators).\n\n```bash\nkenso contacts remove --ids ids.txt --dry-run\nkenso contacts remove --ids ids.txt --yes\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --dry-run\nkenso contacts remove --where \'{"campaignIds": [812], "filters": [{"conditions": {"field": "ContactCompany.Name", "operator": 2, "value": "acme"}}]}\' --yes\nkenso contacts remove --ids big.csv --confirm 2500 --yes\n```\n\n- Without `--yes`, the plan prints the count and the first ids.\n- Removing more than 1,000 contacts also needs `--confirm <count>`, and the count must match. The plan\'s `next` already carries the right `--confirm`.\n- Each id comes back `ok`, `skipped` when there was nothing to do (for example `not_deleted` when you restore a contact that is not removed), `not_found` or `failed`.\n- The remove summary carries the undo command, `"undo":"kenso contacts restore --run r_ubqu7wtx"`.\n\n```bash\nkenso contacts restore --run r_ubqu7wtx --yes\nkenso contacts restore --ids ids.txt --yes\nkenso contacts pause --where \'{"campaignIds": [812]}\' --yes\nkenso contacts resume --ids ids.txt --yes\n```\n\n`restore` takes `--ids` or `--run <runId>` of an earlier remove, not `--where`: a search cannot find removed contacts. `pause` is a beta command for workspaces with the `pause_leads` flag.\n\n## Tag and untag\n\n```bash\nkenso tags list\nkenso contacts tag --tag 31 --ids ids.txt --yes\nkenso contacts untag --tag 31 --ids ids.txt --yes\n```\n\n`tag` sends the ids to `POST /v1/tags/{tagId}/assignments/bulk-create` and `untag` to `POST /v1/tags/{tagId}/assignments/bulk-delete`, 250 per call. A contact that already has the tag counts as `ok`. Each contact\'s result is in `results.csv`: `ok`, `not_found`, or `failed` with the API\'s reason.\n\n## Export a campaign\'s leads\n\n```bash\nkenso contacts export --campaign 812 --out contacts.csv\nkenso contacts export --campaign 812 --wait\n```\n\nWith `--out`, the CLI creates the export, waits for the job (default 30 minutes, `--timeout`) and writes one CSV file (mode 0600). An audience-based campaign exports one CSV per segment in a ZIP: the CLI saves the ZIP as it came, prints `"format": "zip"` and its size instead of a row count, and warns when `--out` does not end in `.zip`. Without `--out` it prints the export job; `--wait` waits for it, or run the `next` it prints, `kenso jobs wait <jobId> --type contact_export`.\n\n## Recipes\n\n**Tag every lead of a campaign.** List the ids, then tag them:\n\n```bash\nkenso contacts list --campaign-id 812 --all -o ids > ids.txt\nkenso contacts tag --tag 31 --ids ids.txt --yes\n```\n\n**Fix the invalid rows and send them.** `invalid.csv` keeps each refused row\'s number and reason. Fix those rows in a new file and import it. Rerunning the original file also works: rows Kenso already saved come back `updated` or `skipped`.\n\n**Retry only what failed.** Filter `results.csv` to the `failed` rows, take those rows from the input by `row` number, and import that file.\n\n**Pause leads who replied elsewhere.** Plan with the filter (the plan shows the count), then apply:\n\n```bash\nkenso contacts pause --where @replied.json\nkenso contacts pause --where @replied.json --yes\n```\n\n**Edit one field on many leads by email.**\n\n```bash\nkenso contacts update --file titles.csv --match email --campaign 812 --dry-run\nkenso contacts update --file titles.csv --match email --campaign 812 --yes\n```\n';
8796
8800
  }
8797
8801
  });
8798
8802
 
@@ -11739,7 +11743,7 @@ function mapCreateAnswer(chunk, body2) {
11739
11743
  return { results, limitMessage };
11740
11744
  }
11741
11745
  async function sendImportChunk(campaignId, chunk, ctx, output) {
11742
- const send2 = () => ctx.client.request({
11746
+ const send = () => ctx.client.request({
11743
11747
  method: "POST",
11744
11748
  path: `/v1/campaigns/${campaignId}/contacts`,
11745
11749
  body: { contacts: chunk.map((item) => item.contact) },
@@ -11747,13 +11751,13 @@ async function sendImportChunk(campaignId, chunk, ctx, output) {
11747
11751
  });
11748
11752
  let res;
11749
11753
  try {
11750
- res = await send2();
11754
+ res = await send();
11751
11755
  } catch (err) {
11752
11756
  if (!(err instanceof KensoError) || err.exitCode !== ExitCode.Server) throw err;
11753
11757
  const waitMs = GATEWAY_TIMEOUT_MS + RESEND_MARGIN_MS;
11754
11758
  output.info(`Chunk ${ctx.chunkIndex + 1} failed (${err.message}). Waiting ${waitMs / 1e3} s for the first request to finish, then sending it again.`);
11755
11759
  await importTiming.sleep(waitMs, ctx.signal);
11756
- res = await send2();
11760
+ res = await send();
11757
11761
  }
11758
11762
  const { results, limitMessage } = mapCreateAnswer(chunk, res.body);
11759
11763
  const outcome = { results, rateLimitRemaining: rateLimitRemaining3(res.headers) };
@@ -12497,7 +12501,7 @@ function bulkCommand(kind) {
12497
12501
  const sentBefore = chunkAttempts(ctx.env);
12498
12502
  const execChunk = async (chunk, chunkCtx) => {
12499
12503
  runId = chunkCtx.runId;
12500
- const send2 = () => chunkCtx.client.request({
12504
+ const send = () => chunkCtx.client.request({
12501
12505
  method: "POST",
12502
12506
  path: route.path,
12503
12507
  body: { ids: chunk.map((item) => item.id) },
@@ -12507,13 +12511,13 @@ function bulkCommand(kind) {
12507
12511
  let sentAgain = kind === "remove" && await sentBefore(chunkCtx.runId, chunkCtx.chunkIndex);
12508
12512
  let res;
12509
12513
  try {
12510
- res = await send2();
12514
+ res = await send();
12511
12515
  } catch (err) {
12512
12516
  if (kind !== "remove" || !(err instanceof KensoError) || err.exitCode !== ExitCode.Server) throw err;
12513
12517
  ctx.output.info(`Chunk ${chunkCtx.chunkIndex + 1} failed (${err.message}). Sending it again.`);
12514
12518
  await importTiming.sleep(REMOVE_RESEND_DELAY_MS, chunkCtx.signal);
12515
12519
  sentAgain = true;
12516
- res = await send2();
12520
+ res = await send();
12517
12521
  }
12518
12522
  const results = mapBulkAnswer(chunk, res.body);
12519
12523
  return { results: sentAgain ? markRemovedEarlier(results) : results, rateLimitRemaining: rateLimitRemaining3(res.headers) };
@@ -12582,34 +12586,49 @@ var init_bulk_ids = __esm({
12582
12586
  // src/commands/contacts/tag.ts
12583
12587
  var tag_exports = {};
12584
12588
  __export(tag_exports, {
12589
+ mapTagAnswer: () => mapTagAnswer,
12585
12590
  tag: () => tag,
12586
12591
  untag: () => untag
12587
12592
  });
12588
- function send(kind, tagId, contactId, ctx) {
12589
- const path = `/v1/tags/${tagId}/assignments`;
12590
- if (kind === "tag") {
12591
- return ctx.client.request({ method: "POST", path, body: { entityType: ENTITY_TYPE, entityId: contactId }, retrySafe: true, signal: ctx.signal });
12593
+ function bulkPath(kind, tagId) {
12594
+ return `/v1/tags/${tagId}/assignments/${kind === "tag" ? "bulk-create" : "bulk-delete"}`;
12595
+ }
12596
+ function mapTagAnswer(chunk, body2, requestId) {
12597
+ const data = unwrap(body2);
12598
+ const entries2 = isRecord4(data) && Array.isArray(data.results) ? data.results : [];
12599
+ const results = [];
12600
+ for (const entry of entries2) {
12601
+ if (!isRecord4(entry) || typeof entry.index !== "number") continue;
12602
+ if (entry.status === "permission_denied") throw errorFromResponse(403, { error: { code: "permission_denied", message: entry.error } }, requestId);
12603
+ const item = chunk[entry.index];
12604
+ if (item === void 0) continue;
12605
+ const { row } = item;
12606
+ const id = String(item.id);
12607
+ const error = typeof entry.error === "string" && entry.error !== "" ? { error: entry.error } : {};
12608
+ if (entry.status === "assigned" || entry.status === "removed") results.push({ row, status: "ok", id });
12609
+ else if (entry.status === "not_found") results.push({ row, status: "not_found", id, reason: "not_found", ...error });
12610
+ else results.push({ row, status: "failed", id, reason: typeof entry.status === "string" ? entry.status : "failed", ...error });
12592
12611
  }
12593
- return ctx.client.request({ method: "DELETE", path, query: { entityType: ENTITY_TYPE, entityId: contactId }, signal: ctx.signal });
12612
+ return results;
12594
12613
  }
12595
12614
  async function tagChunk(kind, tagId, chunk, ctx) {
12596
- const results = [];
12597
- let remaining;
12598
- for (const { row, id } of chunk) {
12599
- const key = String(id);
12600
- try {
12601
- const res = await send(kind, tagId, id, ctx);
12602
- remaining = rateLimitRemaining3(res.headers) ?? remaining;
12603
- results.push({ row, status: "ok", id: key });
12604
- } catch (err) {
12605
- rethrowIfRunStopping(err);
12606
- const status = err instanceof KensoError ? err.httpStatus : void 0;
12607
- if (status === 409 && kind === "tag") results.push({ row, status: "skipped", id: key, reason: "already_tagged" });
12608
- else if (status === 404) results.push({ row, status: "not_found", id: key, reason: "not_found", error: err.message });
12609
- else results.push(failedRow(row, err, { id: key }));
12610
- }
12615
+ try {
12616
+ const res = await ctx.client.request({
12617
+ method: "POST",
12618
+ path: bulkPath(kind, tagId),
12619
+ body: { items: chunk.map(({ id }) => ({ entityType: ENTITY_TYPE, entityId: id })) },
12620
+ retrySafe: true,
12621
+ signal: ctx.signal
12622
+ });
12623
+ return { results: mapTagAnswer(chunk, res.body, res.requestId), rateLimitRemaining: rateLimitRemaining3(res.headers) };
12624
+ } catch (err) {
12625
+ rethrowIfRunStopping(err);
12626
+ const notFound = err instanceof KensoError && err.httpStatus === 404;
12627
+ const results = chunk.map(
12628
+ ({ row, id }) => notFound ? { row, status: "not_found", id: String(id), reason: "not_found", error: err.message } : failedRow(row, err, { id: String(id) })
12629
+ );
12630
+ return { results };
12611
12631
  }
12612
- return { results, rateLimitRemaining: remaining };
12613
12632
  }
12614
12633
  function tagCommand(kind) {
12615
12634
  const name = `kenso contacts ${kind}`;
@@ -12618,7 +12637,7 @@ function tagCommand(kind) {
12618
12637
  action: kind,
12619
12638
  summary: `${kind === "tag" ? "Add a tag to" : "Remove a tag from"} contacts by --ids only (a campaign: list its ids first)`,
12620
12639
  brief: "--ids only",
12621
- description: (kind === "tag" ? "Calls POST /v1/tags/{tagId}/assignments once per contact id (a contact that already has the tag is skipped). " : "Calls DELETE /v1/tags/{tagId}/assignments once per contact id. ") + "Ids come one per line, or from a CSV/JSONL with an id column. Without --yes it prints the count. Exit 5 when some ids failed or were not found.",
12640
+ description: `Sends the ids to POST /v1/tags/{tagId}/assignments/${kind === "tag" ? "bulk-create" : "bulk-delete"}, 250 per call. Ids come one per line, or from a CSV/JSONL with an id column. Without --yes it prints the count. Exit 5 when some ids failed or were not found.`,
12622
12641
  flags: {
12623
12642
  tag: { type: "string", description: "The tag id (see kenso tags list)", aliases: ["tag-id"] },
12624
12643
  ids: { type: "string", description: "Contact ids: one per line, or a CSV/JSONL with an id column; - for stdin" },
@@ -12626,7 +12645,7 @@ function tagCommand(kind) {
12626
12645
  concurrency: CONCURRENCY_FLAG
12627
12646
  },
12628
12647
  examples: [`kenso contacts ${kind} --tag 31 --ids ids.txt --dry-run`, `kenso contacts ${kind} --tag 31 --ids ids.txt --yes`],
12629
- operationIds: [kind === "tag" ? "tags.assign" : "tags.unassign"],
12648
+ operationIds: [kind === "tag" ? "tags.bulk-assign" : "tags.bulk-unassign"],
12630
12649
  dryRun: true,
12631
12650
  async run(ctx, { flags }) {
12632
12651
  const tagId = idFlag(flags, "tag", name);
@@ -12659,9 +12678,10 @@ var init_tag = __esm({
12659
12678
  "use strict";
12660
12679
  init_engine();
12661
12680
  init_errors();
12681
+ init_http();
12662
12682
  init_bulk_ids();
12663
12683
  init_common();
12664
- CHUNK_SIZE5 = 25;
12684
+ CHUNK_SIZE5 = 250;
12665
12685
  DEFAULT_CONCURRENCY3 = 4;
12666
12686
  ENTITY_TYPE = "contact";
12667
12687
  tag = tagCommand("tag");
@@ -16731,12 +16751,12 @@ __export(done_exports, {
16731
16751
  patchTask: () => patchTask
16732
16752
  });
16733
16753
  async function patchTask(ctx, taskId, change) {
16734
- const send2 = () => ctx.client.request({ method: "PATCH", path: `/v1/tasks/${taskId}`, body: change, signal: ctx.signal });
16754
+ const send = () => ctx.client.request({ method: "PATCH", path: `/v1/tasks/${taskId}`, body: change, signal: ctx.signal });
16735
16755
  try {
16736
- return unwrap((await send2()).body);
16756
+ return unwrap((await send()).body);
16737
16757
  } catch (error) {
16738
16758
  if (!(error instanceof KensoError) || error.httpStatus !== 409 || !taskChanged(error.details)) throw error;
16739
- return unwrap((await send2()).body);
16759
+ return unwrap((await send()).body);
16740
16760
  }
16741
16761
  }
16742
16762
  function taskChanged(body2) {