kenso 0.1.114 → 0.1.115

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
@@ -2477,7 +2477,7 @@ var VERSION;
2477
2477
  var init_version = __esm({
2478
2478
  "src/core/version.ts"() {
2479
2479
  "use strict";
2480
- VERSION = true ? "0.1.114" : "0.0.0-dev";
2480
+ VERSION = true ? "0.1.115" : "0.0.0-dev";
2481
2481
  }
2482
2482
  });
2483
2483
 
@@ -2752,9 +2752,9 @@ async function readAnswer(ctx) {
2752
2752
  const lines = createInterface({ input: ctx.stdin ?? process.stdin, terminal: false });
2753
2753
  let onAbort;
2754
2754
  try {
2755
- return await new Promise((resolve17, reject) => {
2756
- lines.once("line", resolve17);
2757
- lines.once("close", () => resolve17(""));
2755
+ return await new Promise((resolve18, reject) => {
2756
+ lines.once("line", resolve18);
2757
+ lines.once("close", () => resolve18(""));
2758
2758
  onAbort = () => reject(interrupted());
2759
2759
  ctx.signal.addEventListener("abort", onAbort, { once: true });
2760
2760
  });
@@ -6632,12 +6632,12 @@ function parseJsonl(text4, source) {
6632
6632
  }
6633
6633
  async function readInput(pathOrDash, opts) {
6634
6634
  const { path, bytes } = await readRaw(pathOrDash, opts?.stdin);
6635
- const sha2563 = createHash2("sha256").update(bytes).digest("hex");
6635
+ const sha2564 = createHash2("sha256").update(bytes).digest("hex");
6636
6636
  const text4 = bytes.toString("utf8");
6637
6637
  const source = path === "-" ? "stdin" : pathOrDash;
6638
6638
  const format = detectFormat(path, text4);
6639
6639
  const parsed2 = format === "csv" ? parseCsv(text4, source) : parseJsonl(text4, source);
6640
- return { path, format, sha256: sha2563, ...parsed2 };
6640
+ return { path, format, sha256: sha2564, ...parsed2 };
6641
6641
  }
6642
6642
  function idText(value) {
6643
6643
  if (typeof value === "number" && Number.isFinite(value)) return String(value);
@@ -8793,7 +8793,7 @@ var init_leads = __esm({
8793
8793
  var output_and_errors_default;
8794
8794
  var init_output_and_errors = __esm({
8795
8795
  "docs/output-and-errors.md"() {
8796
- output_and_errors_default = '# Output and errors\n\nEvery command follows one contract, so a script or an agent can parse any of them the same way.\n\n## stdout and stderr\n\n- **stdout carries data only.** Progress, warnings, notices and errors go to stderr.\n- No colors, spinners or pagers. On a terminal you get readable tables; in a pipe you get JSON.\n- A batch command (an import, update, remove, tag or `--each` write) takes `--yes`; without it, the command plans or refuses.\n- A command that deletes, archives or removes, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive` or `kenso api DELETE /v1/tags/7`, needs `--yes` too. Without it, a person at a terminal is asked to confirm; anywhere else (a pipe, a script, CI, a coding agent) it sends nothing and fails with `confirmation_required`, whose `next` is the same command with `--yes`.\n- Any other single write, such as `kenso tags create` or a write through `kenso api` or `kenso mcp call`, sends at once: add `--dry-run` to print the request first (it sends nothing), then run the command without it.\n- A command with no dry run, such as `kenso contacts export`, `kenso auth logout` or `kenso workspace use`, refuses `--dry-run` with `usage_error` (exit 2) and does nothing. Its help ends with `No --dry-run`, and `kenso describe <resource> <action>` shows `"dryRun": false`.\n\n## Formats\n\n| What the command returns | stdout is a terminal | stdout is a pipe or file |\n|---|---|---|\n| One object | key-value lines | compact JSON on one line |\n| A list | a table (first 8 scalar fields, cells cut at 60 characters) | NDJSON: one JSON object per line |\n| A batch run | key-value lines | one JSON summary object |\n| No content (HTTP 204) | nothing | nothing |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table` or `ids`. `--json` is the same as `-o json`.\n\n- `-o json` on a list prints one JSON array. On a terminal, `-o json` pretty-prints an object.\n- `-o ids` prints one id per line, ready for `--ids -`. Items without an `id` are skipped with one warning.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso contacts list --campaign-id 812 --all -o ids\n```\n\n## Shape the output\n\n- `--fields a,b.c` keeps only those fields (dots reach into nested objects).\n- `--query <JMESPath>` filters or reshapes in-process, so you need no `jq`. On a list it sees the whole list. There is no `--jq`: `--query` takes JMESPath, not jq syntax.\n- Neither applies to a batch summary, which always prints in full.\n- `threads list`, `contacts list` and `contacts search` print a short set of fields per row, in every format: a thread\'s id, channel, sender, subject, interest, read state, newest message time and preview, a contact\'s id, name, email, title, company and email validity, and a few more (the command\'s `--help` names them all). `--full` prints every field (`--full -o json` for a script that reads them all), `--fields` picks your own, and `--query` sees every field.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\nkenso threads list --folder inbox --full\n```\n\n## Lists and pages\n\nA list command prints one page. When there are more, it prints the command for the next page on stderr, for example `next: kenso tags list --limit 1 --cursor MQ`. `--all` follows every page and streams the items. `--limit` sets the page size and `--cursor` starts at a cursor.\n\n`accounts search`, `contacts search` and `people search` page the same way: one page with the `next:` command, or every page with `--all`. A search that asks for counts (`countBy` in `--data`) prints the whole answer instead: `data`, `pagination` and `counts`. Counts cover every match whatever the page, so ask for them on one page (`--limit 1`): `--all` with `countBy` is a usage error.\n\n```bash\nkenso tags list --limit 50\nkenso tags list --all\n```\n\n## Files: uploads and downloads\n\nA command whose API action takes a multipart upload takes `--file <path>`: the CLI reads the file and sends it in the form, with a content type from its extension (a `.png` goes as `image/png`), and the other flags as form fields. `--file <field>=<path>` names the form field, for a form with more than one file. An upload that also takes JSON, such as a logo from a URL instead of a file, sends JSON when you leave `--file` out.\n\nA command whose API action answers with a file (a CSV, an image, a ZIP) takes `--out <path>`: it saves the answer byte for byte (mode 0600) and prints `out`, `bytes` and `contentType`, so the file never passes through an agent\'s context. Without `--out`, a CSV prints as it came, and a binary file goes to stdout only when stdout is a pipe or a file: on a terminal it fails with `binary_output`, whose `next` adds `--out`.\n\n`kenso api` takes both, for any route: `--file` (repeat it for more files) sends multipart with the keys of a `--data` object as form fields, and `--out` saves any answer.\n\n```bash\nkenso saved-lists create-upload --saved-list-id 12 --file people.csv\nkenso workspaces replace-logo --workspace-id 42 --file ./logo.png\nkenso workspaces replace-logo --workspace-id 42 --source-url https://example.com/logo.png\nkenso attachments get-content --attachment-id att_123 --out ./invoice.pdf\nkenso api POST /v1/campaigns/812/email-sequence/images --file ./hero.png\nkenso api GET /v1/knowledge/exports/77/content --out knowledge.zip\n```\n\n## Live streams\n\n`kenso sync events` and `kenso onboarding-builds events` follow a live stream of server-sent events. They print one JSON line per event as it arrives, on a terminal too, with the event\'s name, its id when it has one, and its data:\n\n```json\n{"event":"hello","data":{"buildId":"obd_2x","status":"building","stage":"read","lastEventId":0}}\n{"event":"stage","id":"41","data":{"stage":"plan"}}\n{"event":"done","id":"42","data":{}}\n```\n\nA stream has no time limit while events arrive. The server ends each connection after 15 minutes with a `bye` event; the command then connects again at once, and after a dropped connection or 60 s without even a keepalive, after a second. A connection that brought nothing but `hello` and `bye` (a server that is restarting) backs off 1, 2, 4 ... 30 s. Once events carry an id (`onboarding-builds events`), it sends the last whole event\'s id as `Last-Event-ID`, so no event is lost or printed twice. A refusal (401, 403, 404) ends it at once; eight failed or empty connects in a row end it with the last error.\n\nIt runs until Ctrl-C (exit 130; every line printed is whole), or until one of these:\n\n| Flag | Ends the command |\n|---|---|\n| `--until <event>` | After the first event with that name; several names are comma-separated: `--until done,error` |\n| `--max-events <n>` | After n events, `hello` and `bye` included |\n| `--once` | When the server closes the connection, instead of connecting again |\n\n```bash\nkenso onboarding-builds events --build-id obd_2x --until done,error\nkenso sync events --max-events 2 # hello, then the first poke\n```\n\n`--output`, `--fields` and `--query` do not apply to a stream. `--last-event-id` starts an onboarding build stream after that id.\n\n## Errors\n\nWhen stderr is not a terminal, an error is one JSON line on stderr:\n\n```json\n{"error":{"code":"unknown_flag","message":"Unknown flag --fiel for kenso contacts import.","field":"fiel","hint":"did you mean --file?","next":"kenso contacts import --help"}}\n```\n\n| Key | Always there | Meaning |\n|---|---|---|\n| `code` | yes | A stable snake_case code to branch on |\n| `message` | yes | One sentence for a person |\n| `field` | no | The flag or input field at fault |\n| `hint` | no | What to change |\n| `next` | no | The exact command to run next, such as `kenso auth login`, `kenso workspace list --search <name>` or the same command with `--yes` |\n| `httpStatus` | no | The API\'s HTTP status, when the API answered |\n| `requestId` | no | The API\'s request id: quote it when you contact Kenso support |\n\nOn a terminal the same error prints as text: `Error: <message>`, then `field:`, `hint:`, `next:` and `requestId:` lines. The key never appears in an error.\n\n### How API errors map\n\nThe CLI looks at the HTTP status first, then at the API\'s own `error.code`, which wins when present.\n\n| HTTP status | Default code | Exit |\n|---|---|---|\n| 400, 422 | `validation_failed` | 2 |\n| 401 | `unauthorized` (`next`: `kenso auth login`) | 3 |\n| 403 | `forbidden`: the key\'s user or role cannot do this in this workspace | 3 |\n| 404 | `not_found` | 4 |\n| 409 | `conflict` | 7 |\n| 429 | `rate_limited`, after the CLI waited and retried | 6 |\n| 5xx | `server_error`, after retries where they are safe | 8 |\n| anything else | `http_error` | 1 |\n\nTwo API codes change the exit code: `workspace_required` exits 2 with `"next":"kenso workspace list --search <name>"`, and `limit_reached` (the plan\'s or the campaign\'s lead limit) exits 6.\n\n### Errors from the CLI itself\n\n| Code | Exit | When |\n|---|---|---|\n| `usage_error` | 2 | A required flag or argument is missing, two flags conflict (`--yes` with `--dry-run`), or `--dry-run` on a command that has no dry run |\n| `unknown_command` | 2 | No such command; `hint` suggests the closest one |\n| `unknown_flag`, `invalid_flag`, `invalid_flag_value`, `unexpected_argument` | 2 | A flag or argument the command does not take |\n| `invalid_query` | 2 | `--query` is not valid JMESPath |\n| `confirmation_required` | 2 | A delete, archive or remove ran without `--yes` where nobody can confirm: nothing was sent; `next` adds `--yes` |\n| `cancelled` | 2 | A person answered no to the confirmation: nothing was sent |\n| `file_unreadable` | 2 | An input file is missing, is a folder, cannot be opened, or cannot be parsed; the message names the line, such as `leads.csv line 3: a quote is not closed.` |\n| `config_invalid` | 2 | `~/.kenso/config.json` is not valid JSON: fix or delete it |\n| `feature_not_enabled` | 2 | Every action of the resource is a beta command your workspace has not enabled |\n| `invalid_key_format`, `key_required` | 2 | `auth login --with-key` read something that is not a Kenso key, or stdin is a terminal instead of a pipe |\n| `invalid_workspace_id` | 2 | `kenso workspace use` got an id that is not a positive whole number |\n| `unknown_topic` | 2 | `kenso docs` got a topic it does not have; `hint` lists the topics |\n| `file_unwritable` | 2 or 1 | An output file cannot be written: `--out` on `contacts export`, `kenso api` or a download command (2), `skill install` (1) |\n| `binary_output` | 2 | The answer is a binary file and stdout is a terminal: nothing was printed; `next` saves it with `--out` |\n| `no_api_key` | 3 | No key in `KENSO_API_KEY` or the profile (`next`: `kenso auth login`) |\n| `browser_login_unavailable`, `access_denied`, `login_expired` | 3 | Browser login is off, was denied, or timed out |\n| `run_not_found` | 4 | `kenso runs show` or `resume` got an unknown run id |\n| `docs_not_found` | 4 | `kenso docs reference` before the reference was generated (a source checkout without `pnpm build`) |\n| `run_in_progress`, `already_filled` | 7 | Another process is working on the run, or `studio fill` already ran with this file and these flags |\n| `skill_exists` | 7 | `kenso skill install` found a different `SKILL.md`; `next` adds `--force` to replace it |\n| `job_timeout`, `job_failed`, `job_canceled` | 1 | `kenso jobs wait` (or a command that waits on a job) ran out of time, or the job failed or was canceled |\n| `mcp_tool_error` | 1 | `kenso mcp call`: the MCP tool answered with an error |\n| `unsafe_path` | 1 | `studio pull` refused a file path that would land outside `--dir` |\n| `network_error` | 8 | The API could not be reached after retries |\n| `upload_failed`, `download_failed` | 8 or 1 | A signed upload or download of a Studio file failed: 8 when storage was unreachable or answered 5xx, 1 on a 4xx (often an expired link: run the command again) |\n| `pull_incomplete` | 8 | `studio pull`: a file came back with neither text nor a download link |\n| `unexpected_response` | 1 or 8 | The API answered something the CLI could not read |\n| `unexpected_error` | 1 | A bug: run again with `--verbose` and report it |\n| `interrupted` | 130 | Ctrl-C |\n\n## Exit codes\n\n| Code | Meaning |\n|---|---|\n| 0 | OK, including a batch where every row succeeded or was skipped |\n| 1 | Unexpected error |\n| 2 | Usage or input error: a bad flag, a bad file, a validation error |\n| 3 | Auth: no key, an invalid, revoked or expired key, or HTTP 401 or 403 |\n| 4 | Not found |\n| 5 | Partial: the batch finished and some rows failed, were not found or were invalid. See `results.csv` |\n| 6 | Rate limited after retries, or a plan or campaign lead limit stopped the run (`limit_reached`) |\n| 7 | Conflict or invalid state (HTTP 409), or a run another process holds |\n| 8 | Server error after retries (5xx), or the API is unreachable |\n| 9 | Answer refused: a Kenso sandbox run stopped because an answer held a credential or something shaped like one |\n| 130 | Interrupted. A batch run can be resumed: see its `next` |\n\nSkipped rows (duplicates, blocklisted, already contacted) are not failures: a batch with only created, updated and skipped rows exits 0.\n\n## Flags\n\n- Command flags go after the command: `kenso contacts import --campaign 812`. Global flags can go anywhere.\n- A boolean flag takes `--flag`, `--no-flag`, `--flag=true` and `--flag=false`.\n- A flag that carries a secret (`--password`, `--api-key`, `--api-secret`, any `--\u2026-token` or `--\u2026-secret`) also takes `-` (read stdin), `@file` (read the file) or `env:NAME` (read that environment variable), so the value stays out of shell history: `printf \'%s\' "$FATHOM_KEY" | kenso fathom-connection connect --api-key -`. A value typed on the command line still works and prints one warning. A typed secret that itself starts with `@` is written `@@` (`--password @@Spring2026` sends `@Spring2026`); one that is exactly `-` or starts with `env:` has to come through `@file` or `env:NAME`. `-` refuses a terminal, an empty value is refused, and only one flag can read stdin. `--dry-run` shows a secret as `***`. With `--each`, the plan, its `next` and the run record keep `@file` or `env:NAME` as typed and `kenso runs resume` reads it again; a secret from stdin is refused there.\n- `--help` on any command prints its flags, arguments and examples. `kenso describe <resource> <action>` prints the same as JSON, with the body schema.\n\n## Beta commands\n\nCommands that need a workspace feature flag (CRM, Studio and others) are beta. Help and `kenso describe` hide the ones your workspace has not enabled and say how many they hid; `--all-commands` shows them. Calling a hidden command still works: Kenso decides. `kenso <resource>` on a resource whose every action is hidden answers `feature_not_enabled` (exit 2) and names the flags it needs.\n\n```bash\nkenso --help --all-commands\nkenso describe --all-commands\n```\n\n## What the CLI sends\n\nEvery API call carries `Authorization: Bearer <key>`, `Ken-Version: 1.1`, `X-Ken-Workspace-Id` (when a workspace is picked), `User-Agent: kenso-cli/<version> (node <version>; <platform>)` and `X-Ken-Client: Kenso CLI`. When a coding agent runs the CLI, `X-Ken-Client` names it (`Kenso CLI via Claude Code`) and writes carry `X-Ken-Actor: agent`, so Kenso\'s activity log shows who made a change.\n';
8796
+ output_and_errors_default = '# Output and errors\n\nEvery command follows one contract, so a script or an agent can parse any of them the same way.\n\n## stdout and stderr\n\n- **stdout carries data only.** Progress, warnings, notices and errors go to stderr.\n- No colors, spinners or pagers. On a terminal you get readable tables; in a pipe you get JSON.\n- A batch command (an import, update, remove, tag or `--each` write) takes `--yes`; without it, the command plans or refuses.\n- A command that deletes, archives or removes, such as `kenso tags delete --tag-id 7`, `kenso campaigns archive` or `kenso api DELETE /v1/tags/7`, needs `--yes` too. Without it, a person at a terminal is asked to confirm; anywhere else (a pipe, a script, CI, a coding agent) it sends nothing and fails with `confirmation_required`, whose `next` is the same command with `--yes`.\n- Any other single write, such as `kenso tags create` or a write through `kenso api` or `kenso mcp call`, sends at once: add `--dry-run` to print the request first (it sends nothing), then run the command without it.\n- A command with no dry run, such as `kenso contacts export`, `kenso auth logout` or `kenso workspace use`, refuses `--dry-run` with `usage_error` (exit 2) and does nothing. Its help ends with `No --dry-run`, and `kenso describe <resource> <action>` shows `"dryRun": false`.\n\n## Formats\n\n| What the command returns | stdout is a terminal | stdout is a pipe or file |\n|---|---|---|\n| One object | key-value lines | compact JSON on one line |\n| A list | a table (first 8 scalar fields, cells cut at 60 characters) | NDJSON: one JSON object per line |\n| A batch run | key-value lines | one JSON summary object |\n| No content (HTTP 204) | nothing | nothing |\n\n`-o` or `--output` picks the format: `json`, `ndjson`, `table` or `ids`. `--json` is the same as `-o json`.\n\n- `-o json` on a list prints one JSON array. On a terminal, `-o json` pretty-prints an object.\n- `-o ids` prints one id per line, ready for `--ids -`. Items without an `id` are skipped with one warning.\n\n```bash\nkenso campaigns list --limit 3\nkenso campaigns list --limit 3 -o json\nkenso contacts list --campaign-id 812 --all -o ids\n```\n\n## Shape the output\n\n- `--fields a,b.c` keeps only those fields (dots reach into nested objects).\n- `--query <JMESPath>` filters or reshapes in-process, so you need no `jq`. On a list it sees the whole list. There is no `--jq`: `--query` takes JMESPath, not jq syntax.\n- Neither applies to a batch summary, which always prints in full.\n- `threads list`, `contacts list` and `contacts search` print a short set of fields per row, in every format: a thread\'s id, channel, sender, subject, interest, read state, newest message time and preview, a contact\'s id, name, email, title, company and email validity, and a few more (the command\'s `--help` names them all). `--full` prints every field (`--full -o json` for a script that reads them all), `--fields` picks your own, and `--query` sees every field.\n\n```bash\nkenso campaigns list --fields id,name,status\nkenso campaigns list --all --query "[?status==\'active\'].id"\nkenso me get --query "length(features)"\nkenso threads list --folder inbox --full\n```\n\n## Lists and pages\n\nA list command prints one page. When there are more, it prints the command for the next page on stderr, for example `next: kenso tags list --limit 1 --cursor MQ`. `--all` follows every page and streams the items. `--limit` sets the page size and `--cursor` starts at a cursor.\n\n`accounts search`, `contacts search` and `people search` page the same way: one page with the `next:` command, or every page with `--all`. A search that asks for counts (`countBy` in `--data`) prints the whole answer instead: `data`, `pagination` and `counts`. Counts cover every match whatever the page, so ask for them on one page (`--limit 1`): `--all` with `countBy` is a usage error.\n\n```bash\nkenso tags list --limit 50\nkenso tags list --all\n```\n\n## Files: uploads and downloads\n\nA command whose API action takes a multipart upload takes `--file <path>`: the CLI reads the file and sends it in the form, with a content type from its extension (a `.png` goes as `image/png`), and the other flags as form fields. `--file <field>=<path>` names the form field, for a form with more than one file. An upload that also takes JSON, such as a logo from a URL instead of a file, sends JSON when you leave `--file` out.\n\nA command whose API action answers with a file (a CSV, an image, a ZIP) takes `--out <path>`: it saves the answer byte for byte (mode 0600) and prints `out`, `bytes` and `contentType`, so the file never passes through an agent\'s context. Without `--out`, a CSV prints as it came, and a binary file goes to stdout only when stdout is a pipe or a file: on a terminal it fails with `binary_output`, whose `next` adds `--out`.\n\n`kenso api` takes both, for any route: `--file` (repeat it for more files) sends multipart with the keys of a `--data` object as form fields, and `--out` saves any answer.\n\n```bash\nkenso saved-lists create-upload --saved-list-id 12 --file people.csv\nkenso workspaces replace-logo --workspace-id 42 --file ./logo.png\nkenso workspaces replace-logo --workspace-id 42 --source-url https://example.com/logo.png\nkenso attachments get-content --attachment-id att_123 --out ./invoice.pdf\nkenso api POST /v1/campaigns/812/email-sequence/images --file ./hero.png\nkenso api GET /v1/knowledge/exports/77/content --out knowledge.zip\n```\n\n## Live streams\n\n`kenso sync events` and `kenso onboarding-builds events` follow a live stream of server-sent events. They print one JSON line per event as it arrives, on a terminal too, with the event\'s name, its id when it has one, and its data:\n\n```json\n{"event":"hello","data":{"buildId":"obd_2x","status":"building","stage":"read","lastEventId":0}}\n{"event":"stage","id":"41","data":{"stage":"plan"}}\n{"event":"done","id":"42","data":{}}\n```\n\nA stream has no time limit while events arrive. The server ends each connection after 15 minutes with a `bye` event; the command then connects again at once, and after a dropped connection or 60 s without even a keepalive, after a second. A connection that brought nothing but `hello` and `bye` (a server that is restarting) backs off 1, 2, 4 ... 30 s. Once events carry an id (`onboarding-builds events`), it sends the last whole event\'s id as `Last-Event-ID`, so no event is lost or printed twice. A refusal (401, 403, 404) ends it at once; eight failed or empty connects in a row end it with the last error.\n\nIt runs until Ctrl-C (exit 130; every line printed is whole), or until one of these:\n\n| Flag | Ends the command |\n|---|---|\n| `--until <event>` | After the first event with that name; several names are comma-separated: `--until done,error` |\n| `--max-events <n>` | After n events, `hello` and `bye` included |\n| `--once` | When the server closes the connection, instead of connecting again |\n\n```bash\nkenso onboarding-builds events --build-id obd_2x --until done,error\nkenso sync events --max-events 2 # hello, then the first poke\n```\n\n`--output`, `--fields` and `--query` do not apply to a stream. `--last-event-id` starts an onboarding build stream after that id.\n\n## Errors\n\nWhen stderr is not a terminal, an error is one JSON line on stderr:\n\n```json\n{"error":{"code":"unknown_flag","message":"Unknown flag --fiel for kenso contacts import.","field":"fiel","hint":"did you mean --file?","next":"kenso contacts import --help"}}\n```\n\n| Key | Always there | Meaning |\n|---|---|---|\n| `code` | yes | A stable snake_case code to branch on |\n| `message` | yes | One sentence for a person |\n| `field` | no | The flag or input field at fault |\n| `hint` | no | What to change |\n| `next` | no | The exact command to run next, such as `kenso auth login`, `kenso workspace list --search <name>` or the same command with `--yes` |\n| `httpStatus` | no | The API\'s HTTP status, when the API answered |\n| `requestId` | no | The API\'s request id: quote it when you contact Kenso support |\n\nOn a terminal the same error prints as text: `Error: <message>`, then `field:`, `hint:`, `next:` and `requestId:` lines. The key never appears in an error.\n\n### How API errors map\n\nThe CLI looks at the HTTP status first, then at the API\'s own `error.code`, which wins when present.\n\n| HTTP status | Default code | Exit |\n|---|---|---|\n| 400, 422 | `validation_failed` | 2 |\n| 401 | `unauthorized` (`next`: `kenso auth login`) | 3 |\n| 403 | `forbidden`: the key\'s user or role cannot do this in this workspace | 3 |\n| 404 | `not_found` | 4 |\n| 409 | `conflict` | 7 |\n| 429 | `rate_limited`, after the CLI waited and retried | 6 |\n| 5xx | `server_error`, after retries where they are safe | 8 |\n| anything else | `http_error` | 1 |\n\nTwo API codes change the exit code: `workspace_required` exits 2 with `"next":"kenso workspace list --search <name>"`, and `limit_reached` (the plan\'s or the campaign\'s lead limit) exits 6.\n\n### Errors from the CLI itself\n\n| Code | Exit | When |\n|---|---|---|\n| `usage_error` | 2 | A required flag or argument is missing, two flags conflict (`--yes` with `--dry-run`), or `--dry-run` on a command that has no dry run |\n| `unknown_command` | 2 | No such command; `hint` suggests the closest one |\n| `unknown_flag`, `invalid_flag`, `invalid_flag_value`, `unexpected_argument` | 2 | A flag or argument the command does not take |\n| `invalid_query` | 2 | `--query` is not valid JMESPath |\n| `confirmation_required` | 2 | A delete, archive or remove ran without `--yes` where nobody can confirm: nothing was sent; `next` adds `--yes` |\n| `cancelled` | 2 | A person answered no to the confirmation: nothing was sent |\n| `file_unreadable` | 2 | An input file is missing, is a folder, cannot be opened, or cannot be parsed; the message names the line, such as `leads.csv line 3: a quote is not closed.` |\n| `config_invalid` | 2 | `~/.kenso/config.json` is not valid JSON: fix or delete it |\n| `feature_not_enabled` | 2 | Every action of the resource is a beta command your workspace has not enabled |\n| `invalid_key_format`, `key_required` | 2 | `auth login --with-key` read something that is not a Kenso key, or stdin is a terminal instead of a pipe |\n| `invalid_workspace_id` | 2 | `kenso workspace use` got an id that is not a positive whole number |\n| `unknown_topic` | 2 | `kenso docs` got a topic it does not have; `hint` lists the topics |\n| `file_unwritable` | 2 or 1 | An output file cannot be written: `--out` on `contacts export`, `kenso api` or a download command (2), `skill install` (1) |\n| `binary_output` | 2 | The answer is a binary file and stdout is a terminal: nothing was printed; `next` saves it with `--out` |\n| `no_api_key` | 3 | No key in `KENSO_API_KEY` or the profile (`next`: `kenso auth login`) |\n| `browser_login_unavailable`, `access_denied`, `login_expired` | 3 | Browser login is off, was denied, or timed out |\n| `run_not_found` | 4 | `kenso runs show` or `resume` got an unknown run id |\n| `docs_not_found` | 4 | `kenso docs reference` before the reference was generated (a source checkout without `pnpm build`) |\n| `run_in_progress`, `already_filled` | 7 | Another process is working on the run, or `studio fill` already ran with this file and these flags |\n| `skill_exists` | 7 | `kenso skill install` found a different `SKILL.md`; `next` adds `--force` to replace it |\n| `local_changes` | 7 | `studio pull` would replace files that no earlier pull wrote or push sent, or that changed since; nothing was written, and `next` adds `--force` to replace them |\n| `job_timeout`, `job_failed`, `job_canceled` | 1 | `kenso jobs wait` (or a command that waits on a job) ran out of time, or the job failed or was canceled |\n| `mcp_tool_error` | 1 | `kenso mcp call`: the MCP tool answered with an error |\n| `unsafe_path` | 1 | `studio pull` refused a file path that would land outside `--dir`, starts a file or folder name with a dot, or passes through a symbolic link |\n| `network_error` | 8 | The API could not be reached after retries |\n| `upload_failed`, `download_failed` | 8 or 1 | A signed upload or download of a Studio file failed: 8 when storage was unreachable or answered 5xx, 1 on a 4xx (often an expired link: run the command again) |\n| `pull_incomplete` | 8 | `studio pull`: a file came back with neither text nor a download link |\n| `unexpected_response` | 1 or 8 | The API answered something the CLI could not read |\n| `unexpected_error` | 1 | A bug: run again with `--verbose` and report it |\n| `interrupted` | 130 | Ctrl-C |\n\n## Exit codes\n\n| Code | Meaning |\n|---|---|\n| 0 | OK, including a batch where every row succeeded or was skipped |\n| 1 | Unexpected error |\n| 2 | Usage or input error: a bad flag, a bad file, a validation error |\n| 3 | Auth: no key, an invalid, revoked or expired key, or HTTP 401 or 403 |\n| 4 | Not found |\n| 5 | Partial: the batch finished and some rows failed, were not found or were invalid. See `results.csv` |\n| 6 | Rate limited after retries, or a plan or campaign lead limit stopped the run (`limit_reached`) |\n| 7 | Conflict or invalid state (HTTP 409), or a run another process holds |\n| 8 | Server error after retries (5xx), or the API is unreachable |\n| 9 | Answer refused: a Kenso sandbox run stopped because an answer held a credential or something shaped like one |\n| 130 | Interrupted. A batch run can be resumed: see its `next` |\n\nSkipped rows (duplicates, blocklisted, already contacted) are not failures: a batch with only created, updated and skipped rows exits 0.\n\n## Flags\n\n- Command flags go after the command: `kenso contacts import --campaign 812`. Global flags can go anywhere.\n- A boolean flag takes `--flag`, `--no-flag`, `--flag=true` and `--flag=false`.\n- A flag that carries a secret (`--password`, `--api-key`, `--api-secret`, any `--\u2026-token` or `--\u2026-secret`) also takes `-` (read stdin), `@file` (read the file) or `env:NAME` (read that environment variable), so the value stays out of shell history: `printf \'%s\' "$FATHOM_KEY" | kenso fathom-connection connect --api-key -`. A value typed on the command line still works and prints one warning. A typed secret that itself starts with `@` is written `@@` (`--password @@Spring2026` sends `@Spring2026`); one that is exactly `-` or starts with `env:` has to come through `@file` or `env:NAME`. `-` refuses a terminal, an empty value is refused, and only one flag can read stdin. `--dry-run` shows a secret as `***`. With `--each`, the plan, its `next` and the run record keep `@file` or `env:NAME` as typed and `kenso runs resume` reads it again; a secret from stdin is refused there.\n- `--help` on any command prints its flags, arguments and examples. `kenso describe <resource> <action>` prints the same as JSON, with the body schema.\n\n## Beta commands\n\nCommands that need a workspace feature flag (CRM, Studio and others) are beta. Help and `kenso describe` hide the ones your workspace has not enabled and say how many they hid; `--all-commands` shows them. Calling a hidden command still works: Kenso decides. `kenso <resource>` on a resource whose every action is hidden answers `feature_not_enabled` (exit 2) and names the flags it needs.\n\n```bash\nkenso --help --all-commands\nkenso describe --all-commands\n```\n\n## What the CLI sends\n\nEvery API call carries `Authorization: Bearer <key>`, `Ken-Version: 1.1`, `X-Ken-Workspace-Id` (when a workspace is picked), `User-Agent: kenso-cli/<version> (node <version>; <platform>)` and `X-Ken-Client: Kenso CLI`. When a coding agent runs the CLI, `X-Ken-Client` names it (`Kenso CLI via Claude Code`) and writes carry `X-Ken-Actor: agent`, so Kenso\'s activity log shows who made a change.\n';
8797
8797
  }
8798
8798
  });
8799
8799
 
@@ -8817,7 +8817,7 @@ var init_sandbox = __esm({
8817
8817
  var studio_default;
8818
8818
  var init_studio = __esm({
8819
8819
  "docs/studio.md"() {
8820
- studio_default = "# Studio (beta)\n\nStudio templates are the pages, docs and other assets Kenso builds for each account or lead. The `kenso studio` commands let you edit a template as a folder of files on your machine, check it, preview it, and fill it for many accounts or leads at once. They are beta: they need the `studio` feature flag on your workspace. Help and `kenso describe` hide them until your workspace has it; `--all-commands` shows them.\n\n| Command | What it does |\n|---|---|\n| `studio pull <templateId> --dir <dir>` | Write a template version's files to a folder |\n| `studio push <templateId> --dir <dir>` | Save the folder's files to the template's draft and print the validation |\n| `studio validate <templateId> --dir <dir>` | Validate the folder against the template without saving |\n| `studio preview <templateId>` | Render a version for up to 3 accounts and print the preview links |\n| `studio fill <templateId>` | Fill the template for many accounts or campaign leads, estimate first |\n\nFind template ids with the generated commands:\n\n```bash\nkenso asset-templates list\n```\n\n## Edit a template locally\n\n```bash\nkenso studio pull 12 --dir ./my-template\nkenso studio validate 12 --dir ./my-template\nkenso studio push 12 --dir ./my-template\nkenso studio preview 12 --dir ./my-template --account-ids 501,502\nkenso studio push 12 --dir ./my-template --publish\n```\n\n### pull\n\n`pull` writes every file of the version under `--dir`: text files from the answer, binaries downloaded from signed links and checked against their SHA-256. It overwrites files with the same path and leaves other files in the folder alone. It checks every path before it writes anything, and refuses one that would land outside `--dir` (`unsafe_path`).\n\n`--template-version` picks the version: `draft`, `latest` (the latest published) or a version id. The default is the draft, else the latest published version. (The flag is not `--version`: after a command, `--version` fails with `unknown_flag` and points at `--template-version`.)\n\n```bash\nkenso studio pull 12 --dir ./v3 --template-version 345\nkenso studio pull 12 --dir ./my-template --dry-run\n```\n\nIt prints `{templateId, versionId, files, dir}`. `--dry-run` lists the paths and writes nothing.\n\n### push\n\n`push` reads `--dir`, skipping dotfiles, dot folders and `node_modules`.\n\n- A text file (valid UTF-8, no NUL byte, under 1 MB) goes inline.\n- Any other file is uploaded through a signed upload URL first, 4 at a time, up to 5 MB each. A larger file is refused before any call.\n- One push then saves the files into the draft and prints `{templateId, versionId, versionNumber, validation, changed, deleted}`.\n\nFiles that are in the draft but not in the folder stay, unless you pass `--delete-missing`. `--message` describes the change (default \"Pushed with the Kenso CLI\"). With `--publish`, the new version is published when validation passes, and the output adds `published`.\n\n```bash\nkenso studio push 12 --dir ./my-template --message \"New hero copy\"\nkenso studio push 12 --dir ./my-template --delete-missing --publish\nkenso studio push 12 --dir ./my-template --dry-run\n```\n\nWhen validation finds errors, the draft is still saved: the result prints, then the error `validation_failed` (exit 2) with the first problem as its `hint`. When publishing fails after a good push, the push result still prints and the error says which version was saved. `--dry-run` lists what would be sent and calls nothing.\n\n### validate\n\n`validate` reads the folder the same way and checks the files laid over the draft, as a push would, without saving them. Binaries are uploaded so they can be checked. `--delete-missing` validates exactly the folder's files. It prints the validation and exits 2 when there are errors.\n\n### preview\n\n`preview` renders a saved version, not your local files: the draft, else the latest published version, or `--version-id`. It takes up to a minute per account.\n\n```bash\nkenso studio preview 12\nkenso studio preview 12 --account-ids 501,502,503 --mode render\nkenso studio preview 12 --sample samples/acme.json\nkenso studio preview 12 --mode interact --interact @steps.json\n```\n\n- `--account-ids` takes up to 3 ids. Without it, Kenso picks the 3 most recently touched accounts, else the template's samples.\n- `--mode` is `render` (default) or `interact`. `--interact` takes the click, type and wait steps as JSON, `@file` or `-` (up to 20).\n- With `--dir`, the CLI compares your folder to the version it renders and warns on stderr when they differ, naming the push command to run first.\n\nThe output lists each preview's link, screenshots, console errors and link issues.\n\n## Fill a template for many accounts or leads\n\n`fill` creates pages for a list of accounts, or for the leads of a campaign. A fill is charged per page, so it always prices the work first.\n\n```bash\nkenso studio fill 12 --accounts accounts.txt\nkenso studio fill 12 --accounts accounts.csv --column accountId --yes --wait\nkenso studio fill 12 --campaign 345 --contacts leads.csv --yes\n```\n\n- **Ids** come from `--accounts <file>`, or from `--contacts <file>` with `--campaign <id>`; `-` reads stdin. A file holds one id per line, or a CSV or JSONL with an id column (`--column`, else `id`, else `contactId`). Repeated ids are filled once.\n- **Without `--yes`** (or with `--estimate`) it prints the estimate and the apply command, and creates nothing. For a campaign, the estimate counts one page per lead; Kenso builds one page per company, so it is an upper bound.\n- **With `--yes`** it creates one fill run per 500 ids, one after another.\n- **With `--wait`** it follows each run every 5 seconds until it completes, fails or is cancelled. Without it, follow a run with `kenso asset-runs get --run-id <id>`.\n\nThe summary lists `runs: [{runId, state, rows}]`, and `results.csv` has one line per id with its page id and state.\n\n**The same fill never runs twice.** Rebuilding a page charges again, so when you rerun a fill with the same file (the same bytes) and the same flags:\n\n- an unfinished fill continues where it stopped;\n- a finished fill where every id succeeded answers from that run and changes nothing;\n- anything else is refused with `already_filled` (exit 7). To retry only the ids that failed, take them from the earlier run's `results.csv` into a new file and fill that file.\n\nThe guard compares the file and the flags, not the ids: the same ids in another file, or in another order, are filled and charged again. Keep one ids file per fill, and check `kenso runs list` before you fill ids from a new file.\n\n## Other Studio commands\n\nEverything else (create a template, list versions, restore a version, datasets, publish) is a generated command under `asset-templates`, `asset-runs` and `asset-template-datasets`:\n\n```bash\nkenso asset-templates --help --all-commands\nkenso describe asset-templates\n```\n";
8820
+ studio_default = "# Studio (beta)\n\nStudio templates are the pages, docs and other assets Kenso builds for each account or lead. The `kenso studio` commands let you edit a template as a folder of files on your machine, check it, preview it, and fill it for many accounts or leads at once. They are beta: they need the `studio` feature flag on your workspace. Help and `kenso describe` hide them until your workspace has it; `--all-commands` shows them.\n\n| Command | What it does |\n|---|---|\n| `studio pull <templateId> --dir <dir>` | Write a template version's files to a folder |\n| `studio push <templateId> --dir <dir>` | Save the folder's files to the template's draft and print the validation |\n| `studio validate <templateId> --dir <dir>` | Validate the folder against the template without saving |\n| `studio preview <templateId>` | Render a version for up to 3 accounts and print the preview links |\n| `studio fill <templateId>` | Fill the template for many accounts or campaign leads, estimate first |\n\nFind template ids with the generated commands:\n\n```bash\nkenso asset-templates list\n```\n\n## Edit a template locally\n\n```bash\nkenso studio pull 12 --dir ./my-template\nkenso studio validate 12 --dir ./my-template\nkenso studio push 12 --dir ./my-template\nkenso studio preview 12 --dir ./my-template --account-ids 501,502\nkenso studio push 12 --dir ./my-template --publish\n```\n\n### pull\n\n`pull` writes every file of the version under `--dir`: text files from the answer, binaries downloaded from signed links and checked against their SHA-256. It leaves other files in the folder alone. It checks every path before it writes anything, and refuses (`unsafe_path`) one that would land outside `--dir`, one with a file or folder name that starts with a dot (such as `.claude/` or `.mcp.json`, which editors and coding agents read as their own settings), and one that passes through a symbolic link.\n\n`pull` replaces a file that is already there only when an earlier pull wrote it or a push sent it and nobody changed it since, or when it already holds the new content. `.kenso-pull.json` at the top of the folder records what pulls wrote and pushes sent; push skips it like any dotfile. So pull, edit, push and pull again works as before, and a teammate's change replaces the files you did not change since your last pull or push. A file you added or changed and did not push stops the pull before anything is written: `local_changes` (exit 7) lists them. Move them away or compare them with the template, or add `--force` to replace them with the template's version. The first pull into a folder that an older version of the CLI pulled into may ask for `--force` once, for files that changed in the template since.\n\n`--template-version` picks the version: `draft`, `latest` (the latest published) or a version id. The default is the draft, else the latest published version. (The flag is not `--version`: after a command, `--version` fails with `unknown_flag` and points at `--template-version`.)\n\n```bash\nkenso studio pull 12 --dir ./v3 --template-version 345\nkenso studio pull 12 --dir ./my-template --dry-run\n```\n\nIt prints `{templateId, versionId, files, dir}`, plus `replaced` when `--force` replaced files. `--dry-run` lists the paths, and as `conflicts` the files it would not replace without `--force`, and writes nothing.\n\n### push\n\n`push` reads `--dir`, skipping dotfiles, dot folders, `node_modules`, and Markdown files other than `README.md`, `brief.md` and `ideas.md` at the top of the folder (Studio stores no other `.md`, so a coding agent's `CLAUDE.md` or `AGENTS.md` in the folder stays local).\n\n- A text file (valid UTF-8, no NUL byte, under 1 MB) goes inline.\n- Any other file is uploaded through a signed upload URL first, 4 at a time, up to 5 MB each. A larger file is refused before any call.\n- One push then saves the files into the draft and prints `{templateId, versionId, versionNumber, validation, changed, deleted}`.\n\nFiles that are in the draft but not in the folder stay, unless you pass `--delete-missing`. `--message` describes the change (default \"Pushed with the Kenso CLI\"). With `--publish`, the new version is published when validation passes, and the output adds `published`.\n\n```bash\nkenso studio push 12 --dir ./my-template --message \"New hero copy\"\nkenso studio push 12 --dir ./my-template --delete-missing --publish\nkenso studio push 12 --dir ./my-template --dry-run\n```\n\nWhen validation finds errors, the draft is still saved: the result prints, then the error `validation_failed` (exit 2) with the first problem as its `hint`. When publishing fails after a good push, the push result still prints and the error says which version was saved. `--dry-run` lists what would be sent and calls nothing.\n\n### validate\n\n`validate` reads the folder the same way and checks the files laid over the draft, as a push would, without saving them. Binaries are uploaded so they can be checked. `--delete-missing` validates exactly the folder's files. It prints the validation and exits 2 when there are errors.\n\n### preview\n\n`preview` renders a saved version, not your local files: the draft, else the latest published version, or `--version-id`. It takes up to a minute per account.\n\n```bash\nkenso studio preview 12\nkenso studio preview 12 --account-ids 501,502,503 --mode render\nkenso studio preview 12 --sample samples/acme.json\nkenso studio preview 12 --mode interact --interact @steps.json\n```\n\n- `--account-ids` takes up to 3 ids. Without it, Kenso picks the 3 most recently touched accounts, else the template's samples.\n- `--mode` is `render` (default) or `interact`. `--interact` takes the click, type and wait steps as JSON, `@file` or `-` (up to 20).\n- With `--dir`, the CLI compares your folder to the version it renders and warns on stderr when they differ, naming the push command to run first.\n\nThe output lists each preview's link, screenshots, console errors and link issues.\n\n## Fill a template for many accounts or leads\n\n`fill` creates pages for a list of accounts, or for the leads of a campaign. A fill is charged per page, so it always prices the work first.\n\n```bash\nkenso studio fill 12 --accounts accounts.txt\nkenso studio fill 12 --accounts accounts.csv --column accountId --yes --wait\nkenso studio fill 12 --campaign 345 --contacts leads.csv --yes\n```\n\n- **Ids** come from `--accounts <file>`, or from `--contacts <file>` with `--campaign <id>`; `-` reads stdin. A file holds one id per line, or a CSV or JSONL with an id column (`--column`, else `id`, else `contactId`). Repeated ids are filled once.\n- **Without `--yes`** (or with `--estimate`) it prints the estimate and the apply command, and creates nothing. For a campaign, the estimate counts one page per lead; Kenso builds one page per company, so it is an upper bound.\n- **With `--yes`** it creates one fill run per 500 ids, one after another.\n- **With `--wait`** it follows each run every 5 seconds until it completes, fails or is cancelled. Without it, follow a run with `kenso asset-runs get --run-id <id>`.\n\nThe summary lists `runs: [{runId, state, rows}]`, and `results.csv` has one line per id with its page id and state.\n\n**The same fill never runs twice.** Rebuilding a page charges again, so when you rerun a fill with the same file (the same bytes) and the same flags:\n\n- an unfinished fill continues where it stopped;\n- a finished fill where every id succeeded answers from that run and changes nothing;\n- anything else is refused with `already_filled` (exit 7). To retry only the ids that failed, take them from the earlier run's `results.csv` into a new file and fill that file.\n\nThe guard compares the file and the flags, not the ids: the same ids in another file, or in another order, are filled and charged again. Keep one ids file per fill, and check `kenso runs list` before you fill ids from a new file.\n\n## Other Studio commands\n\nEverything else (create a template, list versions, restore a version, datasets, publish) is a generated command under `asset-templates`, `asset-runs` and `asset-template-datasets`:\n\n```bash\nkenso asset-templates --help --all-commands\nkenso describe asset-templates\n```\n";
8821
8821
  }
8822
8822
  });
8823
8823
 
@@ -15563,7 +15563,8 @@ var init_common3 = __esm({
15563
15563
  });
15564
15564
 
15565
15565
  // src/commands/studio/folder.ts
15566
- import { readdir as readdir2, readFile as readFile11, stat as stat2 } from "node:fs/promises";
15566
+ import { createHash as createHash6 } from "node:crypto";
15567
+ import { lstat, readdir as readdir2, readFile as readFile11, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
15567
15568
  import { extname as extname6, isAbsolute, join as join15, relative, resolve as resolve11, sep } from "node:path";
15568
15569
  function textOf2(bytes) {
15569
15570
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
@@ -15589,6 +15590,7 @@ async function readFolder(dir2) {
15589
15590
  const abs = join15(folder, entry.name);
15590
15591
  if (entry.isDirectory()) await walk(abs);
15591
15592
  else if (entry.isFile()) {
15593
+ if (extname6(entry.name).toLowerCase() === ".md" && !(folder === root2 && TEMPLATE_MARKDOWN.has(entry.name))) continue;
15592
15594
  const bytes = await readFile11(abs);
15593
15595
  files.push({ path: relative(root2, abs).split(sep).join("/"), bytes, text: textOf2(bytes) });
15594
15596
  }
@@ -15599,18 +15601,52 @@ async function readFolder(dir2) {
15599
15601
  }
15600
15602
  function safeJoin(root2, bundlePath) {
15601
15603
  const segments = bundlePath.split("/");
15602
- const bad = bundlePath === "" || isAbsolute(bundlePath) || /^[A-Za-z]:/.test(bundlePath) || bundlePath.includes("\\") || bundlePath.includes("\0") || segments.some((s) => s === "" || s === "." || s === "..");
15604
+ const bad = bundlePath === "" || isAbsolute(bundlePath) || /^[A-Za-z]:/.test(bundlePath) || bundlePath.includes("\\") || bundlePath.includes("\0") || segments.some((s) => s === "" || s.startsWith("."));
15603
15605
  const target2 = resolve11(root2, ...segments);
15604
15606
  if (bad || !target2.startsWith(root2.endsWith(sep) ? root2 : root2 + sep)) {
15605
- throw new KensoError({
15606
- code: "unsafe_path",
15607
- message: `Refusing to write "${bundlePath}": it is not a plain relative path inside ${root2}.`,
15608
- exitCode: ExitCode.Error,
15609
- hint: "The template holds a file path the CLI will not write. Nothing was written."
15610
- });
15607
+ throw unsafePath(bundlePath, `it is not a plain relative path inside ${root2}`);
15611
15608
  }
15612
15609
  return target2;
15613
15610
  }
15611
+ async function existingFileNoLinks(root2, target2, bundlePath) {
15612
+ const parts2 = relative(root2, target2).split(sep);
15613
+ let at = root2;
15614
+ for (const [i, part] of parts2.entries()) {
15615
+ at = join15(at, part);
15616
+ const info = await lstat(at).catch(() => void 0);
15617
+ if (!info) return false;
15618
+ if (info.isSymbolicLink()) throw unsafePath(bundlePath, `${at} is a symbolic link`);
15619
+ if (i === parts2.length - 1) {
15620
+ if (!info.isFile()) throw unsafePath(bundlePath, `${at} exists and is not a file`);
15621
+ return true;
15622
+ }
15623
+ }
15624
+ return false;
15625
+ }
15626
+ async function readPullState(root2) {
15627
+ try {
15628
+ const files = JSON.parse(await readFile11(join15(root2, PULL_STATE), "utf8"))?.files;
15629
+ if (typeof files !== "object" || files === null) return {};
15630
+ return Object.fromEntries(Object.entries(files).filter((entry) => typeof entry[1] === "string"));
15631
+ } catch {
15632
+ return {};
15633
+ }
15634
+ }
15635
+ async function recordPullState(root2, entries2) {
15636
+ const path = join15(root2, PULL_STATE);
15637
+ await existingFileNoLinks(root2, path, PULL_STATE);
15638
+ const files = { ...await readPullState(root2), ...Object.fromEntries(entries2) };
15639
+ await writeFile4(path, `${JSON.stringify({ files }, null, 2)}
15640
+ `);
15641
+ }
15642
+ function unsafePath(bundlePath, why) {
15643
+ return new KensoError({
15644
+ code: "unsafe_path",
15645
+ message: `Refusing to write "${bundlePath}": ${why}.`,
15646
+ exitCode: ExitCode.Error,
15647
+ hint: "The template holds a file path the CLI will not write, or the folder has a link or folder in its way. Nothing was written."
15648
+ });
15649
+ }
15614
15650
  function contentTypeOf(path) {
15615
15651
  return CONTENT_TYPES2[extname6(path).toLowerCase()] ?? "application/octet-stream";
15616
15652
  }
@@ -15632,7 +15668,7 @@ async function mapLimit(items, limit, fn) {
15632
15668
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
15633
15669
  return out;
15634
15670
  }
15635
- var TEXT_MAX_BYTES, UPLOAD_MAX_BYTES, utf8, CONTENT_TYPES2;
15671
+ var TEXT_MAX_BYTES, UPLOAD_MAX_BYTES, utf8, TEMPLATE_MARKDOWN, PULL_STATE, sha2562, CONTENT_TYPES2;
15636
15672
  var init_folder = __esm({
15637
15673
  "src/commands/studio/folder.ts"() {
15638
15674
  "use strict";
@@ -15641,6 +15677,9 @@ var init_folder = __esm({
15641
15677
  TEXT_MAX_BYTES = 1024 * 1024;
15642
15678
  UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
15643
15679
  utf8 = new TextDecoder("utf-8", { fatal: true });
15680
+ TEMPLATE_MARKDOWN = /* @__PURE__ */ new Set(["README.md", "brief.md", "ideas.md"]);
15681
+ PULL_STATE = ".kenso-pull.json";
15682
+ sha2562 = (bytes) => createHash6("sha256").update(bytes).digest("hex");
15644
15683
  CONTENT_TYPES2 = {
15645
15684
  ".png": "image/png",
15646
15685
  ".jpg": "image/jpeg",
@@ -15665,7 +15704,7 @@ var init_folder = __esm({
15665
15704
  });
15666
15705
 
15667
15706
  // src/commands/studio/transfer.ts
15668
- import { createHash as createHash6 } from "node:crypto";
15707
+ import { createHash as createHash7 } from "node:crypto";
15669
15708
  function interrupted6() {
15670
15709
  return new KensoError({ code: "interrupted", message: "Interrupted.", exitCode: ExitCode.Interrupted });
15671
15710
  }
@@ -15731,10 +15770,10 @@ async function bundleFiles(ctx, templateId, files) {
15731
15770
  }
15732
15771
  return out;
15733
15772
  }
15734
- async function download2(url, path, sha2563, signal) {
15773
+ async function download2(url, path, sha2564, signal) {
15735
15774
  const res = await presigned(url, { method: "GET" }, `Downloading ${path}`, "download_failed", signal);
15736
15775
  const bytes = Buffer.from(await res.arrayBuffer());
15737
- if (sha2563 && createHash6("sha256").update(bytes).digest("hex") !== sha2563.toLowerCase()) {
15776
+ if (sha2564 && createHash7("sha256").update(bytes).digest("hex") !== sha2564.toLowerCase()) {
15738
15777
  throw new KensoError({
15739
15778
  code: "download_failed",
15740
15779
  message: `${path} did not download intact (its SHA-256 does not match).`,
@@ -15761,8 +15800,8 @@ var pull_exports = {};
15761
15800
  __export(pull_exports, {
15762
15801
  default: () => pull_default
15763
15802
  });
15764
- import { mkdir, writeFile as writeFile4 } from "node:fs/promises";
15765
- import { dirname as dirname2, resolve as resolve12 } from "node:path";
15803
+ import { mkdir, readFile as readFile12, writeFile as writeFile5 } from "node:fs/promises";
15804
+ import { dirname as dirname2, join as join16, resolve as resolve12 } from "node:path";
15766
15805
  var command50, pull_default;
15767
15806
  var init_pull = __esm({
15768
15807
  "src/commands/studio/pull.ts"() {
@@ -15770,6 +15809,7 @@ var init_pull = __esm({
15770
15809
  init_errors();
15771
15810
  init_exit_codes();
15772
15811
  init_http();
15812
+ init_columns();
15773
15813
  init_common3();
15774
15814
  init_folder();
15775
15815
  init_transfer2();
@@ -15777,17 +15817,19 @@ var init_pull = __esm({
15777
15817
  resource: "studio",
15778
15818
  action: "pull",
15779
15819
  summary: "Write a template version's files to a folder",
15780
- description: "Reads GET /v1/asset-templates/{templateId}/pull and writes every file under --dir: text files from the answer, binaries downloaded from their signed links. Existing files with the same path are overwritten; other files in the folder are left alone. A path that would land outside --dir is refused before anything is written. --template-version picks the version: draft, latest (published) or a version id; the default is the draft, else the latest published version. --dry-run lists the paths without writing or downloading anything.",
15820
+ description: `Reads GET /v1/asset-templates/{templateId}/pull and writes every file under --dir: text files from the answer, binaries downloaded from their signed links. It replaces an existing file only when an earlier pull wrote it or a push sent it and it has not changed since (${PULL_STATE} in the folder records both), or with --force; other files in the folder are left alone. Every path is checked before anything is written: one that would land outside --dir, starts with a dot, or passes through a symbolic link is refused. --template-version picks the version: draft, latest (published) or a version id; the default is the draft, else the latest published version. --dry-run lists the paths, and the files it would not replace, without writing or downloading anything.`,
15781
15821
  flags: {
15782
15822
  dir: { type: "string", required: true, description: "The folder to write the files to (created when missing)" },
15783
- "template-version": { type: "string", description: "draft, latest or a version id (default: the draft, else the latest published)" }
15823
+ "template-version": { type: "string", description: "draft, latest or a version id (default: the draft, else the latest published)" },
15824
+ force: { type: "boolean", description: "Replace files that no earlier pull wrote or push sent, or that changed since" }
15784
15825
  },
15785
15826
  positionals: [TEMPLATE_ID],
15786
15827
  examples: ["kenso studio pull 12 --dir ./my-template", "kenso studio pull 12 --dir ./v3 --template-version 345"],
15787
15828
  beta: { featureGates: STUDIO_GATES },
15788
15829
  operationIds: ["asset-templates.pull"],
15789
15830
  dryRun: true,
15790
- async run(ctx, { flags, positionals }) {
15831
+ async run(ctx, args) {
15832
+ const { flags, positionals } = args;
15791
15833
  const templateId = positiveId3(positionals[0], "templateId");
15792
15834
  const version = typeof flags["template-version"] === "string" ? flags["template-version"].trim() : void 0;
15793
15835
  if (version !== void 0 && !/^(draft|latest|\d+)$/.test(version)) {
@@ -15806,17 +15848,46 @@ var init_pull = __esm({
15806
15848
  if (missing2) {
15807
15849
  throw new KensoError({ code: "pull_incomplete", message: `${missing2.path} came back with neither text nor a download link.`, exitCode: ExitCode.Server });
15808
15850
  }
15851
+ const statePath2 = join16(dir2, PULL_STATE);
15852
+ await existingFileNoLinks(dir2, statePath2, PULL_STATE);
15853
+ const state = await readPullState(dir2);
15854
+ const conflicts = [];
15855
+ for (const { path, file, target: target2 } of files) {
15856
+ if (!await existingFileNoLinks(dir2, target2, path)) continue;
15857
+ const current = sha2562(await readFile12(target2));
15858
+ const next = typeof file.text === "string" ? sha2562(Buffer.from(file.text, "utf8")) : file.sha256?.toLowerCase();
15859
+ if (current !== next && current !== state[path]) conflicts.push(path);
15860
+ }
15809
15861
  if (ctx.flags.dryRun) {
15810
- ctx.output.object({ dryRun: true, templateId, versionId: pulled.versionId, dir: dir2, files: files.map(({ path }) => path) });
15862
+ ctx.output.object({
15863
+ dryRun: true,
15864
+ templateId,
15865
+ versionId: pulled.versionId,
15866
+ dir: dir2,
15867
+ files: files.map(({ path }) => path),
15868
+ ...conflicts.length > 0 ? { conflicts } : {}
15869
+ });
15811
15870
  return ExitCode.Ok;
15812
15871
  }
15872
+ if (conflicts.length > 0 && flags.force !== true) {
15873
+ throw new KensoError({
15874
+ code: "local_changes",
15875
+ message: `Pulling would replace ${conflicts.length} file${conflicts.length === 1 ? "" : "s"} in ${dir2} that no earlier pull wrote or push sent, or that changed since: ${conflicts.join(", ")}.`,
15876
+ exitCode: ExitCode.Conflict,
15877
+ field: "force",
15878
+ hint: "They are files you added or changed since the last pull or push. Move them away or compare them with the template first, or add --force to replace them with the template's version. Nothing was written.",
15879
+ next: commandLine2(ctx, "studio pull", { flags: { ...flags, force: true }, positionals })
15880
+ });
15881
+ }
15813
15882
  await mkdir(dir2, { recursive: true });
15814
- await mapLimit(files, PARALLEL_TRANSFERS, async ({ path, file, target: target2 }) => {
15815
- const content = typeof file.text === "string" ? file.text : await download2(file.downloadUrl, path, file.sha256, ctx.signal);
15883
+ const written = await mapLimit(files, PARALLEL_TRANSFERS, async ({ path, file, target: target2 }) => {
15884
+ const content = typeof file.text === "string" ? Buffer.from(file.text, "utf8") : await download2(file.downloadUrl, path, file.sha256, ctx.signal);
15816
15885
  await mkdir(dirname2(target2), { recursive: true });
15817
- await writeFile4(target2, content);
15886
+ await writeFile5(target2, content);
15887
+ return [path, sha2562(content)];
15818
15888
  });
15819
- ctx.output.object({ templateId, versionId: pulled.versionId, files: files.length, dir: dir2 });
15889
+ await recordPullState(dir2, written);
15890
+ ctx.output.object({ templateId, versionId: pulled.versionId, files: files.length, dir: dir2, ...conflicts.length > 0 ? { replaced: conflicts } : {} });
15820
15891
  return ExitCode.Ok;
15821
15892
  }
15822
15893
  };
@@ -15828,7 +15899,7 @@ var init_pull = __esm({
15828
15899
  async function readLocalTemplate(templateId, dir2) {
15829
15900
  const files = await readFolder(dir2);
15830
15901
  if (files.length === 0) {
15831
- throw usageError(`${dir2} has no template files (dotfiles and node_modules are skipped).`, {
15902
+ throw usageError(`${dir2} has no template files (dotfiles, node_modules and Markdown files other than README.md, brief.md and ideas.md are skipped).`, {
15832
15903
  field: "dir",
15833
15904
  next: `kenso studio pull ${templateId} --dir ${dir2}`
15834
15905
  });
@@ -15853,6 +15924,7 @@ var push_exports = {};
15853
15924
  __export(push_exports, {
15854
15925
  default: () => push_default
15855
15926
  });
15927
+ import { resolve as resolve13 } from "node:path";
15856
15928
  var BUILT_BY, DEFAULT_MESSAGE, command51, push_default;
15857
15929
  var init_push = __esm({
15858
15930
  "src/commands/studio/push.ts"() {
@@ -15862,14 +15934,16 @@ var init_push = __esm({
15862
15934
  init_http();
15863
15935
  init_columns();
15864
15936
  init_common3();
15937
+ init_folder();
15865
15938
  init_read();
15939
+ init_transfer2();
15866
15940
  BUILT_BY = "customer_agent";
15867
15941
  DEFAULT_MESSAGE = "Pushed with the Kenso CLI";
15868
15942
  command51 = {
15869
15943
  resource: "studio",
15870
15944
  action: "push",
15871
15945
  summary: "Save a folder's files to a template's draft and print the validation",
15872
- description: "Reads --dir (skipping dotfiles and node_modules). Text files (valid UTF-8, no NUL byte, under 1 MB) go inline; every other file is uploaded through a signed upload URL first, 4 at a time, up to 5 MB each. Then one push saves them into the draft and prints the validation result. Files not in the folder stay in the draft unless --delete-missing. With --publish, the new version is published when validation passes. Exit 2 when validation finds errors (the draft is still saved). --dry-run only lists the files a push would send; kenso studio validate checks them without saving.",
15946
+ description: "Reads --dir (skipping dotfiles, node_modules, and Markdown files other than README.md, brief.md and ideas.md at the top, which Studio does not store). Text files (valid UTF-8, no NUL byte, under 1 MB) go inline; every other file is uploaded through a signed upload URL first, 4 at a time, up to 5 MB each. Then one push saves them into the draft and prints the validation result. Files not in the folder stay in the draft unless --delete-missing. With --publish, the new version is published when validation passes. Exit 2 when validation finds errors (the draft is still saved). --dry-run only lists the files a push would send; kenso studio validate checks them without saving.",
15873
15947
  flags: {
15874
15948
  dir: { type: "string", required: true, description: "The template folder" },
15875
15949
  "delete-missing": { type: "boolean", description: "Make the draft hold exactly the folder's files" },
@@ -15886,11 +15960,11 @@ var init_push = __esm({
15886
15960
  const templateId = positiveId3(positionals[0], "templateId");
15887
15961
  const message = typeof flags.message === "string" && flags.message.trim() !== "" ? flags.message : DEFAULT_MESSAGE;
15888
15962
  if (ctx.flags.dryRun) {
15889
- const local = await readLocalTemplate(templateId, String(flags.dir));
15963
+ const local2 = await readLocalTemplate(templateId, String(flags.dir));
15890
15964
  ctx.output.object({
15891
15965
  dryRun: true,
15892
15966
  templateId,
15893
- files: local.map((f) => ({ path: f.path, bytes: f.bytes.length, sentAs: f.text === void 0 && f.bytes.length > 0 ? "upload" : "text" })),
15967
+ files: local2.map((f) => ({ path: f.path, bytes: f.bytes.length, sentAs: f.text === void 0 && f.bytes.length > 0 ? "upload" : "text" })),
15894
15968
  deleteMissing: flags["delete-missing"] === true,
15895
15969
  message,
15896
15970
  publish: flags.publish === true,
@@ -15898,7 +15972,8 @@ var init_push = __esm({
15898
15972
  });
15899
15973
  return ExitCode.Ok;
15900
15974
  }
15901
- const files = await readTemplateFolder(ctx, templateId, String(flags.dir));
15975
+ const local = await readLocalTemplate(templateId, String(flags.dir));
15976
+ const files = await bundleFiles(ctx, templateId, local);
15902
15977
  const res = await ctx.client.request({
15903
15978
  method: "POST",
15904
15979
  path: `/v1/asset-templates/${templateId}/push`,
@@ -15906,6 +15981,7 @@ var init_push = __esm({
15906
15981
  signal: ctx.signal
15907
15982
  });
15908
15983
  const pushed = unwrap(res.body) ?? {};
15984
+ await recordPullState(resolve13(String(flags.dir)), local.map((f) => [f.path, sha2562(f.bytes)]));
15909
15985
  const versionId = pushed.version?.id;
15910
15986
  const result = {
15911
15987
  templateId,
@@ -16013,7 +16089,7 @@ var preview_exports = {};
16013
16089
  __export(preview_exports, {
16014
16090
  default: () => preview_default
16015
16091
  });
16016
- import { createHash as createHash7 } from "node:crypto";
16092
+ import { createHash as createHash8 } from "node:crypto";
16017
16093
  function list(paths) {
16018
16094
  return paths.length > SHOWN ? `${paths.slice(0, SHOWN).join(", ")} and ${paths.length - SHOWN} more` : paths.join(", ");
16019
16095
  }
@@ -16031,7 +16107,7 @@ async function warnIfFolderDiffers(ctx, templateId, dir2, versionId, push) {
16031
16107
  for (const file of local) {
16032
16108
  const remote = saved[file.path];
16033
16109
  if (!remote) onlyLocal.push(file.path);
16034
- else if (createHash7("sha256").update(file.bytes).digest("hex") !== remote.sha256?.toLowerCase()) changed.push(file.path);
16110
+ else if (createHash8("sha256").update(file.bytes).digest("hex") !== remote.sha256?.toLowerCase()) changed.push(file.path);
16035
16111
  }
16036
16112
  const localPaths = new Set(local.map((f) => f.path));
16037
16113
  const onlySaved = Object.keys(saved).filter((path) => !localPaths.has(path)).sort();
@@ -16221,9 +16297,9 @@ var fill_exports = {};
16221
16297
  __export(fill_exports, {
16222
16298
  default: () => fill_default
16223
16299
  });
16224
- import { createHash as createHash8 } from "node:crypto";
16225
- import { readFile as readFile12 } from "node:fs/promises";
16226
- import { join as join16, resolve as resolve13 } from "node:path";
16300
+ import { createHash as createHash9 } from "node:crypto";
16301
+ import { readFile as readFile13 } from "node:fs/promises";
16302
+ import { join as join17, resolve as resolve14 } from "node:path";
16227
16303
  async function readTarget(ctx, flags) {
16228
16304
  const accounts = stringFlag(flags.accounts);
16229
16305
  const campaign = stringFlag(flags.campaign);
@@ -16256,7 +16332,7 @@ async function readTarget(ctx, flags) {
16256
16332
  items: [...firstRow].map(([id, row]) => ({ id, row })),
16257
16333
  duplicates: raw.length - firstRow.size,
16258
16334
  ...campaign !== void 0 ? { campaignId: positiveId3(campaign, "campaign") } : {},
16259
- input: source === "-" ? { path: "-", sha256: sha2562(raw.join("\n")) } : { path: resolve13(source), sha256: sha2562(await readFile12(resolve13(source))) }
16335
+ input: source === "-" ? { path: "-", sha256: sha2563(raw.join("\n")) } : { path: resolve14(source), sha256: sha2563(await readFile13(resolve14(source))) }
16260
16336
  };
16261
16337
  }
16262
16338
  async function refuseRefill(ctx, args, target2) {
@@ -16274,7 +16350,7 @@ async function refuseRefill(ctx, args, target2) {
16274
16350
  code: "already_filled",
16275
16351
  exitCode: ExitCode.Conflict,
16276
16352
  message: unfinished ? `Run ${earlier.runId} is already filling these ${ids2} (${earlier.status}).` : `Run ${earlier.runId} already filled these ${ids2}.`,
16277
- hint: unfinished ? "Continue that run instead: a new fill would create every fill run again." : succeeded ? "Every page was filled. Filling again rebuilds and charges every page that is not building or live; to do that anyway, use kenso asset-runs create." : `Filling again rebuilds and charges every page that is not building or live. To retry only the failed ones, put the ${target2.key} values of the failed rows in ${join16(earlier.dir, "results.csv")} in a file and fill that file.`,
16353
+ hint: unfinished ? "Continue that run instead: a new fill would create every fill run again." : succeeded ? "Every page was filled. Filling again rebuilds and charges every page that is not building or live; to do that anyway, use kenso asset-runs create." : `Filling again rebuilds and charges every page that is not building or live. To retry only the failed ones, put the ${target2.key} values of the failed rows in ${join17(earlier.dir, "results.csv")} in a file and fill that file.`,
16278
16354
  next: unfinished ? `kenso runs resume ${earlier.runId}` : `kenso runs show ${earlier.runId}`
16279
16355
  });
16280
16356
  }
@@ -16315,7 +16391,7 @@ function estimateOutput(templateId, target2, estimate2) {
16315
16391
  ...target2.campaignId !== void 0 ? { estimateNote: "An upper bound: it counts one page per lead, and a campaign run builds one page per company." } : {}
16316
16392
  };
16317
16393
  }
16318
- var COMMAND6, sha2562, command54, fill_default;
16394
+ var COMMAND6, sha2563, command54, fill_default;
16319
16395
  var init_fill = __esm({
16320
16396
  "src/commands/studio/fill.ts"() {
16321
16397
  "use strict";
@@ -16330,7 +16406,7 @@ var init_fill = __esm({
16330
16406
  init_common3();
16331
16407
  init_fill_runs();
16332
16408
  COMMAND6 = "studio fill";
16333
- sha2562 = (data) => createHash8("sha256").update(data).digest("hex");
16409
+ sha2563 = (data) => createHash9("sha256").update(data).digest("hex");
16334
16410
  command54 = {
16335
16411
  resource: "studio",
16336
16412
  action: "fill",
@@ -16790,14 +16866,14 @@ var init_views = __esm({
16790
16866
  // src/commands/webhooks/local.ts
16791
16867
  import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
16792
16868
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
16793
- import { join as join17 } from "node:path";
16869
+ import { join as join18 } from "node:path";
16794
16870
  function webhooksDir(env) {
16795
- const dir2 = join17(configDir(env), "webhooks");
16871
+ const dir2 = join18(configDir(env), "webhooks");
16796
16872
  mkdirSync4(dir2, { recursive: true, mode: 448 });
16797
16873
  return dir2;
16798
16874
  }
16799
16875
  function signingSecretPath(env) {
16800
- return join17(webhooksDir(env), "signing-secret");
16876
+ return join18(webhooksDir(env), "signing-secret");
16801
16877
  }
16802
16878
  function signingSecret(env) {
16803
16879
  const file = signingSecretPath(env);
@@ -16848,7 +16924,7 @@ async function forward(url, event, secret, signal) {
16848
16924
  }
16849
16925
  }
16850
16926
  function statePath(env, workspaceId) {
16851
- return join17(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
16927
+ return join18(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
16852
16928
  }
16853
16929
  function writeListenerState(env, workspaceId, state) {
16854
16930
  writeFileSync4(statePath(env, workspaceId), `${JSON.stringify(state)}
@@ -16904,7 +16980,7 @@ async function poll2(ctx, types, cursor2) {
16904
16980
  return unwrap(res.body) ?? {};
16905
16981
  }
16906
16982
  function readBody(req) {
16907
- return new Promise((resolve17, reject) => {
16983
+ return new Promise((resolve18, reject) => {
16908
16984
  let size = 0;
16909
16985
  const chunks = [];
16910
16986
  req.on("data", (chunk) => {
@@ -16912,7 +16988,7 @@ function readBody(req) {
16912
16988
  if (size > MAX_TRIGGER_BYTES) req.destroy(new Error("too large"));
16913
16989
  else chunks.push(chunk);
16914
16990
  });
16915
- req.on("end", () => resolve17(Buffer.concat(chunks).toString("utf8")));
16991
+ req.on("end", () => resolve18(Buffer.concat(chunks).toString("utf8")));
16916
16992
  req.on("error", reject);
16917
16993
  });
16918
16994
  }
@@ -17000,7 +17076,7 @@ var init_listen = __esm({
17000
17076
  reply(res, 200, { forward: result ?? null });
17001
17077
  }).catch(() => reply(res, 400, { error: "invalid_event" }));
17002
17078
  });
17003
- await new Promise((resolve17) => server.listen(0, "127.0.0.1", resolve17));
17079
+ await new Promise((resolve18) => server.listen(0, "127.0.0.1", resolve18));
17004
17080
  const url = `http://127.0.0.1:${server.address().port}/events`;
17005
17081
  writeListenerState(ctx.env, workspaceId, { pid: process.pid, url, token, forwardTo: target2, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
17006
17082
  try {
@@ -17189,7 +17265,7 @@ var init_status3 = __esm({
17189
17265
 
17190
17266
  // src/work/files.ts
17191
17267
  import { closeSync as closeSync2, constants, fchmodSync, fstatSync, lstatSync, openSync as openSync2, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
17192
- import { join as join18 } from "node:path";
17268
+ import { join as join19 } from "node:path";
17193
17269
  function agentName(value) {
17194
17270
  if (typeof value !== "string") return void 0;
17195
17271
  const name = value.trim().slice(0, MAX_AGENT_NAME);
@@ -17208,7 +17284,7 @@ function workFileName(claimId) {
17208
17284
  function writeWorkFile(dir2, work, mode = 384) {
17209
17285
  const name = workFileName(work.claimId);
17210
17286
  if (!isPlainFileName(work.answersFile)) throw new Error("answersFile is not a plain file name");
17211
- const path = join18(dir2, name);
17287
+ const path = join19(dir2, name);
17212
17288
  const fd = openSync2(path, "wx", mode);
17213
17289
  try {
17214
17290
  writeFileSync5(fd, JSON.stringify(work, null, 2) + "\n", "utf8");
@@ -17329,14 +17405,14 @@ function agentKensoEnv(opts) {
17329
17405
  }
17330
17406
  function sudoExec(user, command69, args, opts = {}) {
17331
17407
  const [sudo = "/usr/bin/sudo", ...lead] = user.sudo;
17332
- return new Promise((resolve17) => {
17408
+ return new Promise((resolve18) => {
17333
17409
  execFile(
17334
17410
  sudo,
17335
17411
  [...lead, ...sudoArgs(user.name, command69, args)],
17336
17412
  { env: { PATH: SUDO_PATH }, cwd: "/", timeout: opts.timeoutMs ?? PROBE_TIMEOUT_MS, maxBuffer: opts.maxBuffer ?? 1024 * 1024, encoding: "utf8", windowsHide: true, shell: false },
17337
17413
  (err, stdout, stderr) => {
17338
17414
  const code = err ? err.code : 0;
17339
- resolve17({ exitCode: typeof code === "number" ? code : null, stdout, stderr });
17415
+ resolve18({ exitCode: typeof code === "number" ? code : null, stdout, stderr });
17340
17416
  }
17341
17417
  );
17342
17418
  });
@@ -17432,7 +17508,7 @@ var init_agent_user = __esm({
17432
17508
  // src/commands/work/folder.ts
17433
17509
  import { existsSync as existsSync9 } from "node:fs";
17434
17510
  import { appendFile as appendFile3, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
17435
- import { dirname as dirname3, join as join19, resolve as resolve14 } from "node:path";
17511
+ import { dirname as dirname3, join as join20, resolve as resolve15 } from "node:path";
17436
17512
  var WorkRunFolder;
17437
17513
  var init_folder2 = __esm({
17438
17514
  "src/commands/work/folder.ts"() {
@@ -17474,12 +17550,12 @@ var init_folder2 = __esm({
17474
17550
  const makeDir = (path) => this.shared ? ensureDir(path, SHARED_DIR_MODE) : ensurePrivateDir2(path);
17475
17551
  let dir2;
17476
17552
  if (this.outDir === void 0) {
17477
- dir2 = join19(root2, this.runId);
17553
+ dir2 = join20(root2, this.runId);
17478
17554
  if (!this.shared) ensurePrivateDir2(root2);
17479
17555
  makeDir(dir2);
17480
17556
  } else {
17481
- dir2 = resolve14(this.outDir);
17482
- const existing = existsSync9(join19(dir2, "run.json")) ? await readRunDir(dir2) : null;
17557
+ dir2 = resolve15(this.outDir);
17558
+ const existing = existsSync9(join20(dir2, "run.json")) ? await readRunDir(dir2) : null;
17483
17559
  if (existing && !existing.command.startsWith("work ")) {
17484
17560
  throw usageError(`${dir2} already holds run ${existing.runId} (${existing.command}).`, {
17485
17561
  field: "out",
@@ -17487,17 +17563,17 @@ var init_folder2 = __esm({
17487
17563
  });
17488
17564
  }
17489
17565
  makeDir(dir2);
17490
- for (const name of ["results.ndjson", "summary.json"]) await unlink3(join19(dir2, name)).catch(() => void 0);
17566
+ for (const name of ["results.ndjson", "summary.json"]) await unlink3(join20(dir2, name)).catch(() => void 0);
17491
17567
  try {
17492
17568
  if (!this.shared) ensurePrivateDir2(root2);
17493
- await symlink2(dir2, join19(root2, this.runId), "junction");
17569
+ await symlink2(dir2, join20(root2, this.runId), "junction");
17494
17570
  } catch (err) {
17495
17571
  this.ctx.output.warn(`Could not link ${dir2} into ${root2} (${err.message}): kenso runs will not list this run.`);
17496
17572
  }
17497
17573
  }
17498
17574
  this.dir = dir2;
17499
17575
  if (this.shared) {
17500
- this.tmpDir = join19(dir2, "tmp");
17576
+ this.tmpDir = join20(dir2, "tmp");
17501
17577
  ensureDir(this.tmpDir, JOB_DIR_MODE);
17502
17578
  }
17503
17579
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -17524,7 +17600,7 @@ var init_folder2 = __esm({
17524
17600
  * writes (3770) under a jobs folder it can only pass through (2750).
17525
17601
  */
17526
17602
  async jobDir(claimId) {
17527
- const dir2 = join19(await this.ensure(), "jobs", claimId);
17603
+ const dir2 = join20(await this.ensure(), "jobs", claimId);
17528
17604
  if (this.shared) {
17529
17605
  ensureDir(dirname3(dir2), SHARED_DIR_MODE);
17530
17606
  ensureDir(dir2, JOB_DIR_MODE);
@@ -17540,13 +17616,13 @@ var init_folder2 = __esm({
17540
17616
  async append(line) {
17541
17617
  if (!this.dir) return;
17542
17618
  const json = JSON.stringify(line, (_key, value) => typeof value === "string" ? redact(value) : value);
17543
- await appendFile3(join19(this.dir, "results.ndjson"), `${json}
17619
+ await appendFile3(join20(this.dir, "results.ndjson"), `${json}
17544
17620
  `, { mode: 384 });
17545
17621
  }
17546
17622
  /** summary.json, and run.json with the final status, the claims (chunkCount) and the items (rows). */
17547
17623
  async finish(status, claims, items, summary) {
17548
17624
  if (!this.dir || !this.record) return;
17549
- await writeJsonAtomic(join19(this.dir, "summary.json"), summary);
17625
+ await writeJsonAtomic(join20(this.dir, "summary.json"), summary);
17550
17626
  this.record = { ...this.record, status, chunkCount: claims, rows: items, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
17551
17627
  await writeRunRecord(this.record);
17552
17628
  }
@@ -17653,7 +17729,7 @@ var init_pull2 = __esm({
17653
17729
  // src/commands/work/answers.ts
17654
17730
  import { randomUUID as randomUUID3 } from "node:crypto";
17655
17731
  import { existsSync as existsSync10 } from "node:fs";
17656
- import { basename as basename5, dirname as dirname4, join as join20 } from "node:path";
17732
+ import { basename as basename5, dirname as dirname4, join as join21 } from "node:path";
17657
17733
  function zeroTotals() {
17658
17734
  return { accepted: 0, rejected: 0, expired: 0, duplicate: 0, dropped: 0 };
17659
17735
  }
@@ -17725,7 +17801,7 @@ function droppedResult(d) {
17725
17801
  return { itemId: d.itemId ?? null, status: "dropped", reason: d.reason, message: `Answer ${d.index + 1} of the file was not sent: ${d.reason.replace(/_/g, " ")}.` };
17726
17802
  }
17727
17803
  async function writeResults(answersPath, claimId, results, totals) {
17728
- const path = join20(dirname4(answersPath), `${claimId}.results.json`);
17804
+ const path = join21(dirname4(answersPath), `${claimId}.results.json`);
17729
17805
  await writeJsonAtomic(path, { version: 1, claimId, submittedAt: (/* @__PURE__ */ new Date()).toISOString(), ...totals, results });
17730
17806
  return path;
17731
17807
  }
@@ -17754,7 +17830,7 @@ function workFileNextTo(answersPath) {
17754
17830
  hint: "Write the answers to <claimId>.answers.json next to its <claimId>.work.json, as the work file's rules say."
17755
17831
  });
17756
17832
  }
17757
- const workPath = join20(dirname4(answersPath), `${claimId}.work.json`);
17833
+ const workPath = join21(dirname4(answersPath), `${claimId}.work.json`);
17758
17834
  if (!existsSync10(workPath)) {
17759
17835
  throw usageError(`${workPath} is missing: kenso work submit reads it next to the answers file.`, { field: "answers-file" });
17760
17836
  }
@@ -17787,7 +17863,7 @@ var submit_exports = {};
17787
17863
  __export(submit_exports, {
17788
17864
  default: () => submit_default
17789
17865
  });
17790
- import { resolve as resolve15 } from "node:path";
17866
+ import { resolve as resolve16 } from "node:path";
17791
17867
  var command63, submit_default;
17792
17868
  var init_submit = __esm({
17793
17869
  "src/commands/work/submit.ts"() {
@@ -17809,7 +17885,7 @@ var init_submit = __esm({
17809
17885
  beta: BETA,
17810
17886
  operationIds: ["agent-work.submit-answers"],
17811
17887
  async run(ctx, { positionals }) {
17812
- const paths = [...new Set(positionals.map((p) => resolve15(p)))];
17888
+ const paths = [...new Set(positionals.map((p) => resolve16(p)))];
17813
17889
  const jobs = paths.map((path) => {
17814
17890
  const work = workFileNextTo(path);
17815
17891
  const read2 = readAnswersFile(path, work);
@@ -17886,7 +17962,7 @@ var init_release = __esm({
17886
17962
  import { spawn as nodeSpawn3 } from "node:child_process";
17887
17963
  import { rmSync as rmSync3, statSync as statSync2 } from "node:fs";
17888
17964
  import { access, constants as constants2 } from "node:fs/promises";
17889
- import { delimiter as delimiter2, join as join21 } from "node:path";
17965
+ import { delimiter as delimiter2, join as join22 } from "node:path";
17890
17966
  import { setTimeout as delay12 } from "node:timers/promises";
17891
17967
  function childEnv(parent, adapter, extra) {
17892
17968
  const scrub = new Set(adapter.scrubEnv.map((name) => name.toUpperCase()));
@@ -17923,7 +17999,7 @@ async function resolveBinary(adapter, env, override2) {
17923
17999
  }
17924
18000
  for (const dir2 of pathDirs(env)) {
17925
18001
  for (const ext of extensions) {
17926
- const candidate = join21(dir2, name + ext);
18002
+ const candidate = join22(dir2, name + ext);
17927
18003
  if (await isExecutableFile(candidate)) return candidate;
17928
18004
  }
17929
18005
  }
@@ -17992,7 +18068,7 @@ async function groupGone(pid, runAs) {
17992
18068
  }
17993
18069
  }
17994
18070
  function runChild(spawnFn, bin, built, job, env, signal, runAs) {
17995
- return new Promise((resolve17) => {
18071
+ return new Promise((resolve18) => {
17996
18072
  const stdout = new Tail(OUTPUT_CAP_BYTES);
17997
18073
  const stderr = new Tail(OUTPUT_CAP_BYTES);
17998
18074
  let child;
@@ -18007,7 +18083,7 @@ function runChild(spawnFn, bin, built, job, env, signal, runAs) {
18007
18083
  shell: false
18008
18084
  });
18009
18085
  } catch (err) {
18010
- resolve17({ exitCode: null, stdout: "", stderr: "", spawnError: err });
18086
+ resolve18({ exitCode: null, stdout: "", stderr: "", spawnError: err });
18011
18087
  return;
18012
18088
  }
18013
18089
  let stopped;
@@ -18025,7 +18101,7 @@ function runChild(spawnFn, bin, built, job, env, signal, runAs) {
18025
18101
  signal?.removeEventListener("abort", onAbort);
18026
18102
  void groupGone(pid, runAs).then(() => {
18027
18103
  if (pid !== void 0) liveGroups.delete(pid);
18028
- resolve17({ exitCode, stdout: stdout.text(), stderr: stderr.text(), stopped, spawnError });
18104
+ resolve18({ exitCode, stdout: stdout.text(), stderr: stderr.text(), stopped, spawnError });
18029
18105
  });
18030
18106
  };
18031
18107
  const stop = (why) => {
@@ -18089,11 +18165,11 @@ async function runAgentJob(adapter, job, deps) {
18089
18165
  }
18090
18166
  let work;
18091
18167
  try {
18092
- work = readWorkFile(join21(job.cwd, job.workFile));
18168
+ work = readWorkFile(join22(job.cwd, job.workFile));
18093
18169
  } catch (err) {
18094
18170
  return result("fatal", null, `the work file could not be read: ${err.message}`);
18095
18171
  }
18096
- const answersPath = join21(job.cwd, job.answersFile);
18172
+ const answersPath = join22(job.cwd, job.answersFile);
18097
18173
  try {
18098
18174
  rmSync3(answersPath, { force: true });
18099
18175
  } catch (err) {
@@ -18220,22 +18296,22 @@ function runStatus(bin, args, env, adapter, runAs) {
18220
18296
  const command69 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
18221
18297
  const commandArgs2 = runAs ? [...runAs.sudo.slice(1), ...sudoArgs(runAs.name, bin, args)] : args;
18222
18298
  const options = runAs ? { env: { PATH: SUDO_PATH }, cwd: "/" } : { env: childEnv(env, adapter) };
18223
- return new Promise((resolve17) => {
18299
+ return new Promise((resolve18) => {
18224
18300
  execFile2(
18225
18301
  command69,
18226
18302
  commandArgs2,
18227
18303
  { ...options, timeout: STATUS_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
18228
18304
  (err, stdout, stderr) => {
18229
18305
  if (err && typeof err.code === "string") {
18230
- resolve17(void 0);
18306
+ resolve18(void 0);
18231
18307
  return;
18232
18308
  }
18233
18309
  if (err && err.killed) {
18234
- resolve17(void 0);
18310
+ resolve18(void 0);
18235
18311
  return;
18236
18312
  }
18237
18313
  const exitCode = err ? err.code ?? null : 0;
18238
- resolve17({ exitCode: typeof exitCode === "number" ? exitCode : null, stdout: plain(String(stdout)), stderr: plain(String(stderr)) });
18314
+ resolve18({ exitCode: typeof exitCode === "number" ? exitCode : null, stdout: plain(String(stdout)), stderr: plain(String(stderr)) });
18239
18315
  }
18240
18316
  );
18241
18317
  });
@@ -18503,7 +18579,7 @@ ${out.stderr}`;
18503
18579
  });
18504
18580
 
18505
18581
  // src/work/adapters/opencode.ts
18506
- import { basename as basename6, join as join22 } from "node:path";
18582
+ import { basename as basename6, join as join23 } from "node:path";
18507
18583
  var opencode;
18508
18584
  var init_opencode = __esm({
18509
18585
  "src/work/adapters/opencode.ts"() {
@@ -18547,7 +18623,7 @@ ${out.stderr}`);
18547
18623
  if (job.model) args.push("--model", job.model);
18548
18624
  args.push(job.instruction);
18549
18625
  const env = { OPENCODE_CONFIG_CONTENT: JSON.stringify(config) };
18550
- if (job.tmpDir !== void 0) env.OPENCODE_DB = join22(job.tmpDir, `opencode-${basename6(job.cwd)}.db`);
18626
+ if (job.tmpDir !== void 0) env.OPENCODE_DB = join23(job.tmpDir, `opencode-${basename6(job.cwd)}.db`);
18551
18627
  return { args, env };
18552
18628
  },
18553
18629
  classify: classifyByExit
@@ -18751,8 +18827,8 @@ var init_scan = __esm({
18751
18827
  });
18752
18828
 
18753
18829
  // src/work/credentials.ts
18754
- import { createHash as createHash9 } from "node:crypto";
18755
- import { join as join23 } from "node:path";
18830
+ import { createHash as createHash10 } from "node:crypto";
18831
+ import { join as join24 } from "node:path";
18756
18832
  function unreadable(why) {
18757
18833
  return new KensoError({
18758
18834
  code: "credentials_unreadable",
@@ -18840,9 +18916,9 @@ var init_credentials = __esm({
18840
18916
  }
18841
18917
  }
18842
18918
  async read(rel) {
18843
- const r = await sudoExec(this.user, CAT, [join23(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
18919
+ const r = await sudoExec(this.user, CAT, [join24(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
18844
18920
  if (r.exitCode !== 0) return /No such file or directory/.test(r.stderr) ? "missing" : "unreadable";
18845
- const digest = createHash9("sha256").update(r.stdout).digest("hex");
18921
+ const digest = createHash10("sha256").update(r.stdout).digest("hex");
18846
18922
  if (this.seen.get(rel) !== digest) {
18847
18923
  this.index.add(r.stdout);
18848
18924
  this.seen.set(rel, digest);
@@ -18855,7 +18931,7 @@ var init_credentials = __esm({
18855
18931
 
18856
18932
  // src/work/guide.ts
18857
18933
  import { closeSync as closeSync3, fchmodSync as fchmodSync2, openSync as openSync3, writeFileSync as writeFileSync6 } from "node:fs";
18858
- import { join as join24 } from "node:path";
18934
+ import { join as join25 } from "node:path";
18859
18935
  function agentGuide(opts) {
18860
18936
  const browser = opts.browser ?? findOperation("browser-runs", "create") !== void 0;
18861
18937
  const parts2 = opts.kensoKey ? [JOB, KENSO, ...browser ? [BROWSER] : [], NEVER] : [JOB, NO_KENSO, NEVER];
@@ -18863,7 +18939,7 @@ function agentGuide(opts) {
18863
18939
  }
18864
18940
  function writeAgentGuide(dir2, text4, mode = WORK_FILE_MODE) {
18865
18941
  for (const name of GUIDE_FILES) {
18866
- const fd = openSync3(join24(dir2, name), "wx", mode);
18942
+ const fd = openSync3(join25(dir2, name), "wx", mode);
18867
18943
  try {
18868
18944
  writeFileSync6(fd, text4, "utf8");
18869
18945
  fchmodSync2(fd, mode);
@@ -19017,7 +19093,7 @@ var init_instruction = __esm({
19017
19093
  // src/work/pool.ts
19018
19094
  function runPool(opts) {
19019
19095
  const limit = Math.min(MAX_PARALLEL, Math.max(1, Math.floor(Number.isFinite(opts.parallel) ? opts.parallel : 1)));
19020
- return new Promise((resolve17, reject) => {
19096
+ return new Promise((resolve18, reject) => {
19021
19097
  let running = 0;
19022
19098
  let filling = false;
19023
19099
  let again = false;
@@ -19057,7 +19133,7 @@ function runPool(opts) {
19057
19133
  const stopping = empty || failure !== void 0 || opts.signal?.aborted === true;
19058
19134
  if (stopping && running === 0 && !again) {
19059
19135
  if (failure) reject(failure.error);
19060
- else resolve17();
19136
+ else resolve18();
19061
19137
  return;
19062
19138
  }
19063
19139
  } while (again);
@@ -19157,7 +19233,7 @@ var init_agent3 = __esm({
19157
19233
  });
19158
19234
 
19159
19235
  // src/commands/work/box.ts
19160
- import { resolve as resolve16, sep as sep2 } from "node:path";
19236
+ import { resolve as resolve17, sep as sep2 } from "node:path";
19161
19237
  function invalidToken(message) {
19162
19238
  return new KensoError({ code: "invalid_token_format", message, exitCode: ExitCode.Usage, field: "token-stdin" });
19163
19239
  }
@@ -19184,7 +19260,7 @@ function requireSharedRunsDir(ctx, out) {
19184
19260
  if (!root2) {
19185
19261
  throw usageError("--agent-user needs KENSO_RUNS_DIR: the job folders go there, where the agent user's group can reach them.", { field: "agent-user" });
19186
19262
  }
19187
- if (out !== void 0 && !resolve16(out).startsWith(resolve16(root2) + sep2)) {
19263
+ if (out !== void 0 && !resolve17(out).startsWith(resolve17(root2) + sep2)) {
19188
19264
  throw usageError(`--out must be inside KENSO_RUNS_DIR (${root2}) with --agent-user.`, { field: "out" });
19189
19265
  }
19190
19266
  }
@@ -20381,13 +20457,13 @@ var init_invoked = __esm({
20381
20457
 
20382
20458
  // src/core/update-notice.ts
20383
20459
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync13, realpathSync as realpathSync2, renameSync as renameSync4, writeFileSync as writeFileSync7 } from "node:fs";
20384
- import { dirname as dirname5, join as join25, sep as sep3 } from "node:path";
20460
+ import { dirname as dirname5, join as join26, sep as sep3 } from "node:path";
20385
20461
  function installKind(script = process.argv[1], execPath = process.execPath, platform = process.platform) {
20386
20462
  try {
20387
20463
  if (!script) return "npm";
20388
20464
  const bundle = realpathSync2(script);
20389
20465
  const lib = dirname5(dirname5(dirname5(bundle)));
20390
- if (execPath !== join25(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
20466
+ if (execPath !== join26(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
20391
20467
  return bundle.includes(`${sep3}Cellar${sep3}kenso${sep3}`) ? "homebrew" : "standalone";
20392
20468
  } catch {
20393
20469
  return "npm";
@@ -20447,7 +20523,7 @@ function startUpdateNotice(argv, opts = {}) {
20447
20523
  const stderr = opts.stderr ?? process.stderr;
20448
20524
  const wanted = (opts.stderrIsTTY ?? process.stderr.isTTY === true) && detectAgent(env) === null && env.CI === void 0 && !env.KENSO_NO_UPDATE_NOTIFIER && RELEASE.test(version) && !argv.some((word) => QUIET_COMMANDS.has(word));
20449
20525
  if (!wanted) return done;
20450
- const file = join25(configDir(env), UPDATE_CHECK_FILE);
20526
+ const file = join26(configDir(env), UPDATE_CHECK_FILE);
20451
20527
  const now = (opts.now ?? Date.now)();
20452
20528
  const cached = readCheck(file);
20453
20529
  const checkedAt = Date.parse(cached?.checkedAt ?? "");