kenso 0.1.42 → 0.1.44

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
@@ -2413,7 +2413,7 @@ var VERSION;
2413
2413
  var init_version = __esm({
2414
2414
  "src/core/version.ts"() {
2415
2415
  "use strict";
2416
- VERSION = true ? "0.1.42" : "0.0.0-dev";
2416
+ VERSION = true ? "0.1.44" : "0.0.0-dev";
2417
2417
  }
2418
2418
  });
2419
2419
 
@@ -3639,9 +3639,9 @@ async function readRunDir(dir) {
3639
3639
  return null;
3640
3640
  }
3641
3641
  if (!raw) return null;
3642
- const { runId, command: command33, createdAt, status } = raw;
3642
+ const { runId, command: command35, createdAt, status } = raw;
3643
3643
  if (typeof runId !== "string" || !RUN_ID_PATTERN.test(runId)) return null;
3644
- if (typeof command33 !== "string" || typeof createdAt !== "string") return null;
3644
+ if (typeof command35 !== "string" || typeof createdAt !== "string") return null;
3645
3645
  if (typeof status !== "string" || !STATUSES.includes(status)) return null;
3646
3646
  let chunksDone = chunkList(raw.chunksDone) ?? [];
3647
3647
  try {
@@ -3652,7 +3652,7 @@ async function readRunDir(dir) {
3652
3652
  const record = {
3653
3653
  ...raw,
3654
3654
  runId,
3655
- command: command33,
3655
+ command: command35,
3656
3656
  args: asRecord3(raw.args) ?? {},
3657
3657
  createdAt,
3658
3658
  status,
@@ -3707,11 +3707,11 @@ async function loadRun(runId, env = process.env) {
3707
3707
  }
3708
3708
  return run;
3709
3709
  }
3710
- async function findIdentical(command33, args, inputSha256, env, workspaceId, anyWorkspace = false) {
3710
+ async function findIdentical(command35, args, inputSha256, env, workspaceId, anyWorkspace = false) {
3711
3711
  const identity = argsIdentity(args);
3712
3712
  const runs = await listRuns(env);
3713
3713
  return runs.filter(
3714
- (run) => run.command === command33 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
3714
+ (run) => run.command === command35 && (run.inputSha256 || void 0) === (inputSha256 || void 0) && (anyWorkspace || (run.workspaceId || void 0) === (workspaceId || void 0)) && argsIdentity(run.args) === identity
3715
3715
  );
3716
3716
  }
3717
3717
  function isOtherLiveProcess(pid) {
@@ -6808,8 +6808,8 @@ function idValue(value, field) {
6808
6808
  function shellQuote3(arg) {
6809
6809
  return /^[A-Za-z0-9_./:=@%+,-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
6810
6810
  }
6811
- function commandLine2(ctx, command33, args, extra = []) {
6812
- const parts = ["kenso", ...command33.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
6811
+ function commandLine2(ctx, command35, args, extra = []) {
6812
+ const parts = ["kenso", ...command35.split(" "), ...(args.positionals ?? []).map(shellQuote3)];
6813
6813
  for (const [name, value] of Object.entries(args.flags)) {
6814
6814
  if (value === void 0 || value === false) continue;
6815
6815
  if (value === true) parts.push(`--${name}`);
@@ -7109,7 +7109,7 @@ var init_accounts = __esm({
7109
7109
  var agents_default;
7110
7110
  var init_agents = __esm({
7111
7111
  "docs/agents.md"() {
7112
- agents_default = '# Coding agents\n\nThe CLI is built to be driven by a coding agent: Claude Code, Codex, Cursor, Gemini CLI or anything else that runs shell commands. An agent learns it from the Agent Skill, `kenso --help` and `kenso describe`, and never needs these web pages.\n\n## Set up an agent in three steps\n\n1. Install the CLI where the agent runs: `npm i -g kenso` (Node 22 or newer). Without a global install, `npx -y kenso@latest <command>` runs any command.\n2. Give it a key. Either set `KENSO_API_KEY` (and `KENSO_WORKSPACE_ID` when the key reaches several workspaces) in the agent\'s environment, or log in once on that machine:\n\n```bash\nkenso auth login\nkenso workspace use 1234\n```\n\n3. Install the Agent Skill and connect the Kenso MCP server in one step, then check everything:\n\n```bash\nkenso agent setup\nkenso agent setup -y\nkenso doctor\n```\n\nTo hand the whole setup to an agent, give it https://ken.so/get-started.md: it runs these steps and stops only where a person has to act.\n\n## kenso agent setup\n\n`kenso agent setup` installs the `kenso-cli` skill (as `kenso skill install` does) and registers the Kenso MCP server, `https://mcp.ken.so/mcp`, with each coding agent:\n\n| Agent | `--client` | MCP server added with |\n|---|---|---|\n| Claude Code | `claude-code` | `claude mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| Codex | `codex` | `codex mcp add kenso --url https://mcp.ken.so/mcp` |\n| Cursor | `cursor` | a `kenso` entry in `~/.cursor/mcp.json` |\n| Gemini CLI | `gemini` | `gemini mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| OpenCode | `opencode` | a `kenso` entry in `~/.config/opencode/opencode.json` |\n\n```bash\nkenso agent setup --client claude-code -y\nkenso agent setup --client all -y\nkenso agent setup --status --json\n```\n\n- Without `--client`, it sets up the agent that runs it, else every agent found on the machine (its command on `PATH` or its config folder present).\n- Without `-y` it prints the plan and changes nothing; the plan\'s `next` applies it. `--status` reports, for every agent, whether the skill is `installed`, `missing` or `different` and whether the MCP server is `registered`, `missing`, in `conflict` or `unknown` (a config file it cannot read as JSON), and changes nothing. `--json` prints JSON on a terminal too.\n- An MCP entry with the Kenso URL under another name (such as `ken-ai` from the plugin) counts as registered, and nothing is added. A `kenso` entry pointing at another URL is left alone (`conflict`). A config file that is not plain JSON (it has comments) is left alone (`skipped`), and so is an agent whose command is not on `PATH`: their `next` is the command or edit to make by hand.\n- A different `SKILL.md` in the way stops the run before any change (exit 7) until you add `--force`.\n- It exits 1 when any agent was not fully set up. The MCP server signs in with your Kenso account in the browser the first time the agent uses it; each agent\'s `next` says how (in Claude Code, `/mcp`).\n\n## An AGENTS.md section for your repo\n\nPaste this into the `AGENTS.md` (or `CLAUDE.md`) of a repo whose agents work in Kenso:\n\n```markdown\n## Kenso\n\n- Kenso is our outbound platform. One record or a question: use the Kenso MCP server (https://mcp.ken.so/mcp). A file or more than about 50 records: use the `kenso` CLI.\n- Setup: `npm i -g kenso`, `kenso auth login` (a person approves in the browser), `kenso agent setup -y`, `kenso doctor`.\n- Every write runs first with `--dry-run`; apply with the plan\'s `next`. Never put an API key in a flag, a file or the chat: use `KENSO_API_KEY`.\n- Code that calls the API: send `Authorization: Bearer $KENSO_API_KEY`, `Ken-Version` and `X-Ken-Workspace-Id`. Reference: https://ken.so/docs.md; the kenso-api skill: https://ken.so/.well-known/skills/index.json.\n```\n\n## The Agent Skill\n\n`kenso skill install` writes the skill `kenso-cli` (one `SKILL.md`) where each agent looks for skills:\n\n| Agent | `--client` | Folder |\n|---|---|---|\n| Claude Code | `claude-code` | `~/.claude/skills/kenso-cli/` |\n| Codex | `codex` | `~/.agents/skills/kenso-cli/` |\n| Cursor | `cursor` | `~/.cursor/skills/kenso-cli/` |\n| Gemini CLI | `gemini` | `~/.gemini/skills/kenso-cli/` |\n| OpenCode | `opencode` | `~/.config/opencode/skills/kenso-cli/` |\n\nClaude Code\'s folder follows `CLAUDE_CONFIG_DIR` when that is set. Without `--client`, it installs for the agent that runs it when that is Claude Code, Codex or Cursor (detected from the environment, see below), else for all five. It prints what it wrote:\n\n```json\n{"installed":[{"client":"claude-code","path":"/home/you/.claude/skills/kenso-cli/SKILL.md","status":"created"}]}\n```\n\n```bash\nkenso skill install --client claude-code\nkenso skill install --client all\nkenso skill install --dir .claude/skills/kenso-cli\nkenso skill install --force\n```\n\n- `--dir` writes the skill into that folder instead, for example a project\'s own skills folder. Name the folder `kenso-cli`, as agents expect the folder to match the skill name.\n- A different `SKILL.md` already in a target folder is replaced only with `--force`; without it the command exits 7, writes nothing, and its `next` adds `--force`. The same file is left alone (`"status":"unchanged"`).\n- `--dry-run` writes nothing and exits 0. It prints each target\'s status (`replaced` marks a different file there) and a `next` that applies it, with `--force` when a file would be replaced.\n- Cursor also reads `~/.claude/skills/` and `~/.agents/skills/` (Gemini CLI and OpenCode read `~/.agents/skills/` too), so after a default install for all of them an agent may list `kenso-cli` more than once. To avoid that, install with `--client cursor` only, or remove the copies you do not need.\n\nThe skill also ships in the Kenso plugin for Claude Code (`Ken-Technology/ken-ai-plugin`), so `npx skills add Ken-Technology/ken-ai-plugin` installs it along with the MCP skills. The plugin\'s copy is this file byte for byte. To read it without installing, open `skill/kenso-cli/SKILL.md` in the package.\n\n## Rules the skill teaches\n\n- **Data is on stdout, as JSON when piped.** Progress, warnings and errors are on stderr. Parse stdout; read stderr when the exit code is not 0.\n- **Plan, then apply.** Run a write with `--dry-run`, read the plan, then run the exact command in its `next` (the same command with `--yes`). A command with no dry run refuses `--dry-run` with `usage_error` and does nothing.\n- **Pass files, not rows.** Never paste a CSV into the conversation. Write the file, pass its path with `--file`, and read the summary.\n- **Read failures only.** If the summary\'s `failed`, `notFound` and `invalid` are 0, the work is done. Otherwise read just the problem rows from `results.csv` or `invalid.csv`.\n- **Follow `next`.** Every error with a known fix carries the exact command to run.\n- **Branch on the exit code:** 0 ok, 2 fix the command, 3 fix the key, 5 some rows failed, 6 wait or raise a limit, 130 resume.\n- **Look things up, do not guess.** `kenso describe <resource> <action>` prints any command\'s flags and body schema as JSON.\n\n## The token-saving pattern\n\nAdding 5,000 leads through the MCP sends every lead through the model, hundreds of thousands of tokens. Through the CLI it is two commands and two short JSON objects:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThen, only if the summary shows failures:\n\n```bash\ngrep -E \'^[0-9]+,(failed|not_found|invalid),\' ~/.kenso/runs/r_tdi5cdnx/results.csv | head -50\n```\n\n## Environment variables\n\n| Variable | What it does |\n|---|---|\n| `KENSO_API_KEY` | The API key. Wins over any saved profile |\n| `KENSO_WORKSPACE_ID` | The workspace for every command. `--workspace` wins over it |\n| `KENSO_PROFILE` | The saved profile to use. `--profile` wins over it |\n| `KENSO_API_URL` | The API, default `https://api.ken.so` |\n| `KENSO_CONFIG_DIR` | Where the config file and cache live, default `~/.kenso` |\n| `KENSO_RUNS_DIR` | Where run folders live, default `<config dir>/runs` |\n| `KENSO_MCP_URL` | The MCP for `kenso mcp`, default `https://mcp.ken.so/mcp` |\n\n## Cloud sandboxes\n\nCloud agents (Claude Code on the web, Codex cloud, Cursor background agents and similar) often run with a network allowlist. Allow:\n\n- `api.ken.so`: every command\n- `mcp.ken.so`: only `kenso mcp tools` and `kenso mcp call`\n- `registry.npmjs.org`: to install the CLI with npm\n\nStore the key as the platform\'s secret and expose it as `KENSO_API_KEY`. Run `kenso doctor` as the first command: it checks Node, the config, that the API is reachable and that the key works, and exits 0 when all four pass.\n\n```bash\nkenso doctor\n```\n\nPoint the run folders at the workspace if the home folder does not persist between sessions: `KENSO_RUNS_DIR=./.kenso-runs`. Keep that folder out of git.\n\n## How Kenso knows an agent ran a command\n\nThe CLI checks these environment variables, in this order: `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` (Claude Code), `CODEX_SANDBOX` and `CODEX_THREAD_ID` (Codex), `CURSOR_AGENT` (Cursor), `GEMINI_CLI` (Gemini CLI), `OPENCODE` (OpenCode), then `AI_AGENT`, a free-form name any other agent can set. When one is set:\n\n- every request carries `X-Ken-Client: Kenso CLI via <agent>`, and writes carry `X-Ken-Actor: agent`, so Kenso shows the change as made by you through that agent;\n- help ends with a short "For agents" block;\n- browser login never opens a browser itself: it prints the link for you to open.\n\n`kenso doctor` shows the agent it detected.\n\n## MCP-only tools\n\nA few Kenso MCP tools have no API route, such as the skills Kenso\'s own agents use. Reach them from the shell with the same key:\n\n```bash\nkenso mcp tools\nkenso mcp call list_skills\nkenso mcp call load_skill --args \'{"name":"create-campaign"}\'\nkenso mcp call contacts_read --operation list --args \'{"limit":5}\'\n```\n\n`mcp call` prints the tool\'s structured result, else its text parsed as JSON, else the text. A tool error exits 1 with `mcp_tool_error`.\n';
7112
+ agents_default = '# Coding agents\n\nThe CLI is built to be driven by a coding agent: Claude Code, Codex, Cursor, Gemini CLI or anything else that runs shell commands. An agent learns it from the Agent Skill, `kenso --help` and `kenso describe`, and never needs these web pages.\n\n## Set up an agent in three steps\n\n1. Install the CLI where the agent runs: `npm i -g kenso` (Node 22 or newer). Without a global install, `npx -y kenso@latest <command>` runs any command.\n2. Give it a key. Either set `KENSO_API_KEY` (and `KENSO_WORKSPACE_ID` when the key reaches several workspaces) in the agent\'s environment, or log in once on that machine:\n\n```bash\nkenso auth login\nkenso workspace use 1234\n```\n\n3. Install the Agent Skill and connect the Kenso MCP server in one step, then check everything:\n\n```bash\nkenso agent setup\nkenso agent setup -y\nkenso doctor\n```\n\nTo hand the whole setup to an agent, give it [ken.so/get-started.md](https://ken.so/get-started.md): it runs these steps and stops only where a person has to act.\n\n## kenso agent setup\n\n`kenso agent setup` installs the `kenso-cli` skill (as `kenso skill install` does) and registers the Kenso MCP server, `https://mcp.ken.so/mcp`, with each coding agent:\n\n| Agent | `--client` | MCP server added with |\n|---|---|---|\n| Claude Code | `claude-code` | `claude mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| Codex | `codex` | `codex mcp add kenso --url https://mcp.ken.so/mcp` |\n| Cursor | `cursor` | a `kenso` entry in `~/.cursor/mcp.json` |\n| Gemini CLI | `gemini` | `gemini mcp add --scope user --transport http kenso https://mcp.ken.so/mcp` |\n| OpenCode | `opencode` | a `kenso` entry in `~/.config/opencode/opencode.json` |\n\n```bash\nkenso agent setup --client claude-code -y\nkenso agent setup --client all -y\nkenso agent setup --status --json\n```\n\n- Without `--client`, it sets up the agent that runs it, else every agent found on the machine (its command on `PATH` or its config folder present).\n- Without `-y` it prints the plan and changes nothing; the plan\'s `next` applies it. `--status` reports, for every agent, whether the skill is `installed`, `missing` or `different` and whether the MCP server is `registered`, `missing`, in `conflict` or `unknown` (a config file it cannot read as JSON), and changes nothing. `--json` prints JSON on a terminal too.\n- An MCP entry with the Kenso URL under another name (such as `ken-ai` from the plugin) counts as registered, and nothing is added. A `kenso` entry pointing at another URL is left alone (`conflict`). A config file that is not plain JSON (it has comments) is left alone (`skipped`), and so is an agent whose command is not on `PATH`: their `next` is the command or edit to make by hand.\n- A different `SKILL.md` in the way stops the run before any change (exit 7) until you add `--force`.\n- It exits 1 when any agent was not fully set up. The MCP server signs in with your Kenso account in the browser the first time the agent uses it; each agent\'s `next` says how (in Claude Code, `/mcp`).\n\n## An AGENTS.md section for your repo\n\nPaste this into the `AGENTS.md` (or `CLAUDE.md`) of a repo whose agents work in Kenso:\n\n```markdown\n## Kenso\n\n- Kenso is our outbound platform. One record or a question: use the Kenso MCP server (https://mcp.ken.so/mcp). A file or more than about 50 records: use the `kenso` CLI.\n- Setup: `npm i -g kenso`, `kenso auth login` (a person approves in the browser), `kenso agent setup -y`, `kenso doctor`.\n- Every write runs first with `--dry-run`; apply with the plan\'s `next`. Never put an API key in a flag, a file or the chat: use `KENSO_API_KEY`.\n- Code that calls the API: send `Authorization: Bearer $KENSO_API_KEY`, `Ken-Version` and `X-Ken-Workspace-Id`. Reference: ken.so/docs.md; the kenso-api skill is listed at ken.so/.well-known/skills/index.json.\n```\n\n## The Agent Skill\n\n`kenso skill install` writes the skill `kenso-cli` (one `SKILL.md`) where each agent looks for skills:\n\n| Agent | `--client` | Folder |\n|---|---|---|\n| Claude Code | `claude-code` | `~/.claude/skills/kenso-cli/` |\n| Codex | `codex` | `~/.agents/skills/kenso-cli/` |\n| Cursor | `cursor` | `~/.cursor/skills/kenso-cli/` |\n| Gemini CLI | `gemini` | `~/.gemini/skills/kenso-cli/` |\n| OpenCode | `opencode` | `~/.config/opencode/skills/kenso-cli/` |\n\nClaude Code\'s folder follows `CLAUDE_CONFIG_DIR` when that is set. Without `--client`, it installs for the agent that runs it when that is Claude Code, Codex or Cursor (detected from the environment, see below), else for all five. It prints what it wrote:\n\n```json\n{"installed":[{"client":"claude-code","path":"/home/you/.claude/skills/kenso-cli/SKILL.md","status":"created"}]}\n```\n\n```bash\nkenso skill install --client claude-code\nkenso skill install --client all\nkenso skill install --dir .claude/skills/kenso-cli\nkenso skill install --force\n```\n\n- `--dir` writes the skill into that folder instead, for example a project\'s own skills folder. Name the folder `kenso-cli`, as agents expect the folder to match the skill name.\n- A different `SKILL.md` already in a target folder is replaced only with `--force`; without it the command exits 7, writes nothing, and its `next` adds `--force`. The same file is left alone (`"status":"unchanged"`).\n- `--dry-run` writes nothing and exits 0. It prints each target\'s status (`replaced` marks a different file there) and a `next` that applies it, with `--force` when a file would be replaced.\n- Cursor also reads `~/.claude/skills/` and `~/.agents/skills/` (Gemini CLI and OpenCode read `~/.agents/skills/` too), so after a default install for all of them an agent may list `kenso-cli` more than once. To avoid that, install with `--client cursor` only, or remove the copies you do not need.\n\nThe skill also ships in the Kenso plugin for Claude Code (`Ken-Technology/ken-ai-plugin`), so `npx skills add Ken-Technology/ken-ai-plugin` installs it along with the MCP skills. The plugin\'s copy is this file byte for byte. To read it without installing, open `skill/kenso-cli/SKILL.md` in the package.\n\n## Rules the skill teaches\n\n- **Data is on stdout, as JSON when piped.** Progress, warnings and errors are on stderr. Parse stdout; read stderr when the exit code is not 0.\n- **Plan, then apply.** Run a write with `--dry-run`, read the plan, then run the exact command in its `next` (the same command with `--yes`). A command with no dry run refuses `--dry-run` with `usage_error` and does nothing.\n- **Pass files, not rows.** Never paste a CSV into the conversation. Write the file, pass its path with `--file`, and read the summary.\n- **Read failures only.** If the summary\'s `failed`, `notFound` and `invalid` are 0, the work is done. Otherwise read just the problem rows from `results.csv` or `invalid.csv`.\n- **Follow `next`.** Every error with a known fix carries the exact command to run.\n- **Branch on the exit code:** 0 ok, 2 fix the command, 3 fix the key, 5 some rows failed, 6 wait or raise a limit, 130 resume.\n- **Look things up, do not guess.** `kenso describe <resource> <action>` prints any command\'s flags and body schema as JSON.\n\n## The token-saving pattern\n\nAdding 5,000 leads through the MCP sends every lead through the model, hundreds of thousands of tokens. Through the CLI it is two commands and two short JSON objects:\n\n```bash\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\nThen, only if the summary shows failures:\n\n```bash\ngrep -E \'^[0-9]+,(failed|not_found|invalid),\' ~/.kenso/runs/r_tdi5cdnx/results.csv | head -50\n```\n\n## Environment variables\n\n| Variable | What it does |\n|---|---|\n| `KENSO_API_KEY` | The API key. Wins over any saved profile |\n| `KENSO_WORKSPACE_ID` | The workspace for every command. `--workspace` wins over it |\n| `KENSO_PROFILE` | The saved profile to use. `--profile` wins over it |\n| `KENSO_API_URL` | The API, default `https://api.ken.so` |\n| `KENSO_CONFIG_DIR` | Where the config file and cache live, default `~/.kenso` |\n| `KENSO_RUNS_DIR` | Where run folders live, default `<config dir>/runs` |\n| `KENSO_MCP_URL` | The MCP for `kenso mcp`, default `https://mcp.ken.so/mcp` |\n\n## Cloud sandboxes\n\nCloud agents (Claude Code on the web, Codex cloud, Cursor background agents and similar) often run with a network allowlist. Allow:\n\n- `api.ken.so`: every command\n- `mcp.ken.so`: only `kenso mcp tools` and `kenso mcp call`\n- `registry.npmjs.org`: to install the CLI with npm\n\nStore the key as the platform\'s secret and expose it as `KENSO_API_KEY`. Run `kenso doctor` as the first command: it checks Node, the config, that the API is reachable and that the key works, and exits 0 when all four pass.\n\n```bash\nkenso doctor\n```\n\nPoint the run folders at the workspace if the home folder does not persist between sessions: `KENSO_RUNS_DIR=./.kenso-runs`. Keep that folder out of git.\n\n## How Kenso knows an agent ran a command\n\nThe CLI checks these environment variables, in this order: `CLAUDECODE` and `CLAUDE_CODE_ENTRYPOINT` (Claude Code), `CODEX_SANDBOX` and `CODEX_THREAD_ID` (Codex), `CURSOR_AGENT` (Cursor), `GEMINI_CLI` (Gemini CLI), `OPENCODE` (OpenCode), then `AI_AGENT`, a free-form name any other agent can set. When one is set:\n\n- every request carries `X-Ken-Client: Kenso CLI via <agent>`, and writes carry `X-Ken-Actor: agent`, so Kenso shows the change as made by you through that agent;\n- help ends with a short "For agents" block;\n- browser login never opens a browser itself: it prints the link for you to open.\n\n`kenso doctor` shows the agent it detected.\n\n## MCP-only tools\n\nA few Kenso MCP tools have no API route, such as the skills Kenso\'s own agents use. Reach them from the shell with the same key:\n\n```bash\nkenso mcp tools\nkenso mcp call list_skills\nkenso mcp call load_skill --args \'{"name":"create-campaign"}\'\nkenso mcp call contacts_read --operation list --args \'{"limit":5}\'\n```\n\n`mcp call` prints the tool\'s structured result, else its text parsed as JSON, else the text. A tool error exits 1 with `mcp_tool_error`.\n';
7113
7113
  }
7114
7114
  });
7115
7115
 
@@ -7157,7 +7157,7 @@ var init_output_and_errors = __esm({
7157
7157
  var README_default;
7158
7158
  var init_README = __esm({
7159
7159
  "docs/README.md"() {
7160
- README_default = '# Kenso CLI\n\nThe Kenso CLI (`kenso`) is the command line for Kenso. It does bulk work in your Kenso workspace from files: add thousands of leads to a campaign, update or clean them up, import accounts and people, and build Studio templates. It is made for coding agents (Claude Code, Codex, Cursor) and the people who drive them: JSON on stdout, fixed exit codes, a dry run before every bulk write, and runs you can resume.\n\nEvery API operation a workspace member can call is also a command, such as `kenso campaigns list` or `kenso tags create`. So the CLI reaches what the Kenso MCP reaches, straight against `https://api.ken.so`.\n\n## Install\n\nYou need Node 22 or newer.\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`.\n\n## 60-second quickstart\n\n1. Create an API key in app.ken.so at Settings > Integrations > API keys.\n2. Save the key, pick a workspace, then plan and apply a CSV import:\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --limit 5\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`workspace list` and `workspace use` are only needed when your key reaches more than one workspace.\n\nThe dry run reads the file, maps the columns, checks every row, asks Kenso for a credit estimate, and writes nothing. It prints the plan, with the exact apply command in `next`:\n\n```json\n{"run":"r_tdi5cdnx","dryRun":true,"command":"contacts import","rows":4,"valid":2,"invalid":2,"chunks":1,"chunkSize":1000,"campaignId":812,"mapping":{"Email":"email","First Name":"firstName","Last Name":"lastName","Company":"companyName","Pain Point":"customVariables.pain_point"},"customVariableKeys":["pain_point"],"estimate":{"kind":"leads","totalMillicredits":2000,"availableMillicredits":500000,"sufficient":true},"credits":{"needed":2,"available":500,"sufficient":true},"next":"kenso contacts import --campaign 812 --file leads.csv --yes","plan":"/home/you/.kenso/runs/r_tdi5cdnx/plan.json","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv"}\n```\n\nThe apply sends the rows and prints one summary. Every input row has one line in `results.csv`:\n\n```json\n{"run":"r_tdi5cdnx","rows":4,"ok":0,"created":1,"updated":0,"skipped":{"duplicate":1},"failed":0,"notFound":0,"invalid":2,"changed":1,"results":"/home/you/.kenso/runs/r_tdi5cdnx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_tdi5cdnx/results.ndjson","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv","resumed":false,"durationMs":1840,"campaignId":812,"notSendable":0}\n```\n\nThis run exits 5 because two rows were invalid: open `invalid.csv` to see why, fix those rows, and import them again. Running the same command again is safe: an email that is already in the campaign comes back `updated` or `skipped`, never as a second lead.\n\n## CLI or MCP\n\n- **Use the CLI for volume:** anything that starts from a file, anything over about 50 records, anything you may need to rerun or resume. Records never pass through the model\'s context: the agent passes a file path and reads a short summary.\n- **Use the MCP for conversation and single records:** look up a campaign, draft a reply, read a report. The MCP is at `https://mcp.ken.so/mcp`, signs in with OAuth and needs no install ([connection guide](https://ken.so/mcp)).\n- **Both use the same API and the same permissions.** `kenso mcp call` reaches MCP-only tools, such as skills, from the shell.\n\n## Docs\n\nEvery page is in the package and prints offline with `kenso docs <topic>`.\n\n| Page | Topic | What it covers |\n|---|---|---|\n| [Authentication](auth.md) | `auth` | API keys, browser login, profiles, workspaces, `doctor` |\n| [Leads](leads.md) | `leads` | Import, update, remove, pause, tag and export leads, with recipes |\n| [Batch runs](batch.md) | `batch` | Dry run and apply, run folders, results files, resume, rate limits, `--each` |\n| [Output and errors](output-and-errors.md) | `output-and-errors` | The output contract, error JSON, error codes, exit codes |\n| [CRM (beta)](crm.md) | `crm` | Accounts, people, opportunities and CRM sync |\n| [Studio (beta)](studio.md) | `studio` | Pull, push, validate, preview and fill templates |\n| [Agent work (beta)](work.md) | `work` | My agent: your own coding agent writes Kenso AI work with `kenso work run`, or pull and submit |\n| [Coding agents](agents.md) | `agents` | Claude Code, Codex, Cursor, the Agent Skill, environment variables, sandboxes |\n| Command reference | `reference` | Every command with its flags, generated from the CLI at build time: `kenso docs reference`, or `docs/reference.md` in the installed package |\n\n```bash\nkenso docs\nkenso docs leads\n```\n\nFor machine-readable help, run `kenso describe`: it prints every command, its flags and its body schema as JSON.\n';
7160
+ README_default = '# Kenso CLI\n\nThe Kenso CLI (`kenso`) is the command line for Kenso. It does bulk work in your Kenso workspace from files: add thousands of leads to a campaign, update or clean them up, import accounts and people, and build Studio templates. It is made for coding agents (Claude Code, Codex, Cursor) and the people who drive them: JSON on stdout, fixed exit codes, a dry run before every bulk write, and runs you can resume.\n\nEvery API operation a workspace member can call is also a command, such as `kenso campaigns list` or `kenso tags create`. So the CLI reaches what the Kenso MCP reaches, straight against `https://api.ken.so`.\n\n## Install\n\nYou need Node 22 or newer.\n\n```bash\nnpm i -g kenso\nkenso --version\n```\n\nTo run it once without installing, use `npx kenso --version`.\n\n## 60-second quickstart\n\n1. Create an API key in app.ken.so at Settings > Integrations > API keys.\n2. Save the key, pick a workspace, then plan and apply a CSV import:\n\n```bash\necho $KEY | kenso auth login --with-key\nkenso workspace list --search acme\nkenso workspace use 1234\nkenso campaigns list --limit 5\nkenso contacts import --campaign 812 --file leads.csv --dry-run\nkenso contacts import --campaign 812 --file leads.csv --yes\n```\n\n`workspace list` and `workspace use` are only needed when your key reaches more than one workspace.\n\nThe dry run reads the file, maps the columns, checks every row, asks Kenso for a credit estimate, and writes nothing. It prints the plan, with the exact apply command in `next`:\n\n```json\n{"run":"r_tdi5cdnx","dryRun":true,"command":"contacts import","rows":4,"valid":2,"invalid":2,"chunks":1,"chunkSize":1000,"campaignId":812,"mapping":{"Email":"email","First Name":"firstName","Last Name":"lastName","Company":"companyName","Pain Point":"customVariables.pain_point"},"customVariableKeys":["pain_point"],"estimate":{"kind":"leads","totalMillicredits":2000,"availableMillicredits":500000,"sufficient":true},"credits":{"needed":2,"available":500,"sufficient":true},"next":"kenso contacts import --campaign 812 --file leads.csv --yes","plan":"/home/you/.kenso/runs/r_tdi5cdnx/plan.json","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv"}\n```\n\nThe apply sends the rows and prints one summary. Every input row has one line in `results.csv`:\n\n```json\n{"run":"r_tdi5cdnx","rows":4,"ok":0,"created":1,"updated":0,"skipped":{"duplicate":1},"failed":0,"notFound":0,"invalid":2,"changed":1,"results":"/home/you/.kenso/runs/r_tdi5cdnx/results.csv","resultsNdjson":"/home/you/.kenso/runs/r_tdi5cdnx/results.ndjson","invalidRows":"/home/you/.kenso/runs/r_tdi5cdnx/invalid.csv","resumed":false,"durationMs":1840,"campaignId":812,"notSendable":0}\n```\n\nThis run exits 5 because two rows were invalid: open `invalid.csv` to see why, fix those rows, and import them again. Running the same command again is safe: an email that is already in the campaign comes back `updated` or `skipped`, never as a second lead.\n\n## CLI or MCP\n\n- **Use the CLI for volume:** anything that starts from a file, anything over about 50 records, anything you may need to rerun or resume. Records never pass through the model\'s context: the agent passes a file path and reads a short summary.\n- **Use the MCP for conversation and single records:** look up a campaign, draft a reply, read a report. The MCP is at `https://mcp.ken.so/mcp`, signs in with OAuth and needs no install ([connection guide](https://ken.so/mcp)).\n- **Both use the same API and the same permissions.** `kenso mcp call` reaches MCP-only tools, such as skills, from the shell.\n\n## Docs\n\nEvery page is in the package and prints offline with `kenso docs <topic>`.\n\n| Page | Topic | What it covers |\n|---|---|---|\n| [Authentication](auth.md) | `auth` | API keys, browser login, profiles, workspaces, `doctor` |\n| [Leads](leads.md) | `leads` | Import, update, remove, pause, tag and export leads, with recipes |\n| [Batch runs](batch.md) | `batch` | Dry run and apply, run folders, results files, resume, rate limits, `--each` |\n| [Output and errors](output-and-errors.md) | `output-and-errors` | The output contract, error JSON, error codes, exit codes |\n| [CRM (beta)](crm.md) | `crm` | Accounts, people, opportunities and CRM sync |\n| [Studio (beta)](studio.md) | `studio` | Pull, push, validate, preview and fill templates |\n| [Agent work (beta)](work.md) | `work` | My agent: your own coding agent writes Kenso AI work with `kenso work run`, or pull and submit |\n| [Webhooks](webhooks.md) | `webhooks` | Build a webhook handler locally: `kenso webhooks listen --forward-to`, `trigger`, the signature |\n| [Coding agents](agents.md) | `agents` | Claude Code, Codex, Cursor, the Agent Skill, environment variables, sandboxes |\n| Command reference | `reference` | Every command with its flags, generated from the CLI at build time: `kenso docs reference`, or `docs/reference.md` in the installed package |\n\n```bash\nkenso docs\nkenso docs leads\n```\n\nFor machine-readable help, run `kenso describe`: it prints every command, its flags and its body schema as JSON.\n';
7161
7161
  }
7162
7162
  });
7163
7163
 
@@ -7169,6 +7169,14 @@ var init_studio = __esm({
7169
7169
  }
7170
7170
  });
7171
7171
 
7172
+ // docs/webhooks.md
7173
+ var webhooks_default;
7174
+ var init_webhooks = __esm({
7175
+ "docs/webhooks.md"() {
7176
+ webhooks_default = '# Webhooks: listen and trigger\n\nBuild and test a webhook handler on your own machine, with no public tunnel and no webhook endpoint in Kenso. `kenso webhooks listen` streams your workspace\'s events, prints each one as JSON and forwards it to your handler, signed the way Kenso signs its deliveries. `kenso webhooks trigger` sends a sample event through the running listener.\n\n| Command | What it does |\n|---|---|\n| `webhooks listen --forward-to <url>` | Streams events, prints one JSON line each, and POSTs each to your handler |\n| `webhooks listen --print-secret` | Prints the local signing secret and exits |\n| `webhooks trigger <event-type>` | Sends that type\'s sample through the running listener |\n\n## Quick start\n\nIn one terminal:\n\n```bash\nkenso webhooks listen --forward-to http://localhost:3000/hook\n```\n\nIt prints its signing secret on stderr:\n\n```\nReady. Forwarding events to http://localhost:3000/hook.\nSigning secret: whsec_... (the same on every run; kept in ~/.kenso/webhooks/signing-secret).\n```\n\nPut that secret in your handler\'s config (for example `KENSO_WEBHOOK_SECRET`). In another terminal:\n\n```bash\nkenso webhooks trigger reply.received\n```\n\nThe listener prints the event and your handler receives it. `kenso webhook-event-types list` lists every type with its sample body.\n\n## What your handler receives\n\nEach forward is a `POST` with a JSON body shaped like a webhook delivery (no envelope, `eventType` at the top) and the headers a Kenso delivery carries. How full the body is depends on where the event came from:\n\n- **A trigger** sends the type\'s full sample body, the same shape a webhook endpoint receives in production.\n- **A live event** is sparse. The event log keeps only part of each delivery, so the body has `eventType`, `eventId`, `timestamp` and `clientId`, plus the ids, statuses and `links` at their delivery paths (`contact.id`, `campaign.id`, `reply.classification`, ...). Names, emails, reply text and the other fields are not there: read them with the API, or build that part of the handler against a trigger\'s sample.\n\nThe headers:\n\n| Header | Value |\n|---|---|\n| `svix-id` | The event\'s id. Dedupe on it |\n| `svix-timestamp` | Unix seconds of the send |\n| `svix-signature` | `v1,` and the base64 HMAC-SHA256 of `{svix-id}.{svix-timestamp}.{body}`, keyed by the secret |\n| `content-type` | `application/json` |\n\nSo the verification code you write for production works unchanged: the Svix libraries (`svix` for Node, Python, Go and others) and the check in the Webhooks section of the Kenso API docs accept these deliveries. Only the secret differs. The listener\'s secret is local: it is made on your machine the first time you run `listen`, stays the same on every run, and is never a real endpoint\'s secret. In production, use your endpoint\'s secret from `kenso webhook-endpoints get-signing-secret --webhook-endpoint-id <webhookEndpointId>`.\n\nFor scripts, take the secret without starting a listener:\n\n```bash\nexport KENSO_WEBHOOK_SECRET=$(kenso webhooks listen --print-secret)\n```\n\n## Output\n\nstdout gets one JSON line per event, for `jq` or an agent:\n\n```json\n{"eventId":"0b6f...","type":"reply.received","timestamp":"2026-11-15T10:00:00Z","source":"live","forward":{"url":"http://localhost:3000/hook","status":200,"ms":12},"data":{"eventType":"reply.received","...":"..."}}\n```\n\n- `source` is `live` for a real event and `trigger` for a sample.\n- `forward` is what your handler answered: `status`, or `error` (`ECONNREFUSED` when nothing listens there). It is absent without `--forward-to`.\n- `data` is the body your handler received (or would receive, without `--forward-to`).\n\nThe ready line, the secret and the summary at Ctrl-C go to stderr.\n\n## Live events\n\n`listen` reads the workspace\'s event log (`GET /v1/event-occurrences`), so it receives the types with `mcp: true` in `kenso webhook-event-types list` that your seat can see. It polls the log, so a real event arrives within about 30 s; a trigger arrives at once. `--events reply.received,meeting.booked` (or `--events` repeated) narrows the types.\n\nThe event log is not on for every workspace yet. Where it is off, `listen` says so in a warning and still forwards everything you trigger, so you can build the handler first.\n\n## Triggers\n\n`trigger` takes the type\'s sample from `GET /v1/webhook-event-types`, gives it a new `eventId` (`evt_test_...`) and the current `timestamp`, and hands it to the listener for this workspace, which prints and forwards it like a live event. It sends nothing to Kenso\'s event log, to your webhook endpoints or to anyone else. It exits 1 with `forward_failed` when your handler did not answer 2xx, and with `listener_not_running` when no listener runs for the workspace.\n\nTo send a sample to a real, deployed endpoint instead, use `kenso webhook-endpoints test --webhook-endpoint-id <webhookEndpointId> --event-type reply.received`.\n\n## Stopping\n\nCtrl-C stops the listener. `listen` creates no webhook endpoint, no event subscription and no tunnel, so there is nothing to delete in Kenso. Its polls do keep the workspace\'s event log recording: the log stops on its own 7 days after the last poll. A poll that fails (a network error, a 5xx) prints a warning and is tried again a minute later; a bad key or a refused request ends the listener. It removes its local state file (the address `trigger` uses) on the way out.\n';
7177
+ }
7178
+ });
7179
+
7172
7180
  // docs/work.md
7173
7181
  var work_default;
7174
7182
  var init_work = __esm({
@@ -7203,6 +7211,7 @@ var init_embedded = __esm({
7203
7211
  init_output_and_errors();
7204
7212
  init_README();
7205
7213
  init_studio();
7214
+ init_webhooks();
7206
7215
  init_work();
7207
7216
  init_SKILL();
7208
7217
  DOCS = {
@@ -7214,6 +7223,7 @@ var init_embedded = __esm({
7214
7223
  "crm.md": crm_default,
7215
7224
  "studio.md": studio_default,
7216
7225
  "work.md": work_default,
7226
+ "webhooks.md": webhooks_default,
7217
7227
  "agents.md": agents_default
7218
7228
  };
7219
7229
  SKILL = SKILL_default;
@@ -7250,6 +7260,7 @@ var init_content = __esm({
7250
7260
  { topic: "crm", file: "crm.md", title: "CRM (beta)", description: "Accounts, people, opportunities and CRM sync" },
7251
7261
  { topic: "studio", file: "studio.md", title: "Studio (beta)", description: "Pull, push, validate, preview and fill templates" },
7252
7262
  { topic: "work", file: "work.md", title: "Agent work (beta)", description: "My agent: your own coding agent writes Kenso AI work with kenso work run, or pull and submit" },
7263
+ { topic: "webhooks", file: "webhooks.md", title: "Webhooks", description: "Build a webhook handler locally: kenso webhooks listen --forward-to, trigger, the signature" },
7253
7264
  { topic: "agents", file: "agents.md", title: "Coding agents", description: "kenso agent setup for Claude Code, Codex, Cursor, Gemini CLI and OpenCode, the Agent Skill, environment variables, sandboxes" },
7254
7265
  { topic: "reference", file: "reference.md", title: "Command reference", description: "Every command with its flags, generated from the CLI at build time" }
7255
7266
  ];
@@ -8235,8 +8246,8 @@ var init_browser_login = __esm({
8235
8246
  defaultDeps = {
8236
8247
  sleep: (ms, signal) => delay2(ms, void 0, signal ? { signal } : void 0),
8237
8248
  now: () => Date.now(),
8238
- spawn: (command33, args) => {
8239
- const child = nodeSpawn(command33, args, { detached: true, stdio: "ignore" });
8249
+ spawn: (command35, args) => {
8250
+ const child = nodeSpawn(command35, args, { detached: true, stdio: "ignore" });
8240
8251
  child.on("error", () => {
8241
8252
  });
8242
8253
  child.unref();
@@ -8516,9 +8527,9 @@ function stringFlag2(flags, name) {
8516
8527
  const text3 = value.trim();
8517
8528
  return text3 === "" ? void 0 : text3;
8518
8529
  }
8519
- function requireFlag(flags, name, command33, hint) {
8530
+ function requireFlag(flags, name, command35, hint) {
8520
8531
  const value = stringFlag2(flags, name);
8521
- if (value === void 0) throw usageError(`--${name} is required for ${command33}.`, { field: name, next: `${command33} --help`, ...hint ? { hint } : {} });
8532
+ if (value === void 0) throw usageError(`--${name} is required for ${command35}.`, { field: name, next: `${command35} --help`, ...hint ? { hint } : {} });
8522
8533
  return value;
8523
8534
  }
8524
8535
  function positiveId(value) {
@@ -8527,8 +8538,8 @@ function positiveId(value) {
8527
8538
  const id = Number(text3);
8528
8539
  return Number.isSafeInteger(id) && id > 0 ? id : void 0;
8529
8540
  }
8530
- function idFlag(flags, name, command33) {
8531
- const raw = requireFlag(flags, name, command33);
8541
+ function idFlag(flags, name, command35) {
8542
+ const raw = requireFlag(flags, name, command35);
8532
8543
  const id = positiveId(raw);
8533
8544
  if (id === void 0) throw usageError(`--${name} must be a positive whole number (got "${raw}").`, { field: name });
8534
8545
  return id;
@@ -8548,8 +8559,8 @@ function isDryRun(ctx) {
8548
8559
  function shellQuote4(value) {
8549
8560
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8550
8561
  }
8551
- function sameCommand2(command33, flags, ctx, extra = []) {
8552
- const parts = [command33];
8562
+ function sameCommand2(command35, flags, ctx, extra = []) {
8563
+ const parts = [command35];
8553
8564
  for (const [name, value] of Object.entries(flags)) {
8554
8565
  if (value === void 0 || value === false) continue;
8555
8566
  if (value === true) parts.push(`--${name}`);
@@ -9686,12 +9697,12 @@ import { join as join11 } from "node:path";
9686
9697
  function whereDir(env) {
9687
9698
  return join11(runsRoot(env), WHERE_DIR);
9688
9699
  }
9689
- async function unfinishedWhereIds(ctx, command33, args) {
9700
+ async function unfinishedWhereIds(ctx, command35, args) {
9690
9701
  const dir = whereDir(ctx.env);
9691
9702
  const identity = argsIdentity(args);
9692
9703
  const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
9693
9704
  for (const run of await listRuns(ctx.env)) {
9694
- if (run.command !== command33 || run.status === "done" || run.status === "planned") continue;
9705
+ if (run.command !== command35 || run.status === "done" || run.status === "planned") continue;
9695
9706
  if ((run.workspaceId || void 0) !== (workspaceId || void 0) || argsIdentity(run.args) !== identity) continue;
9696
9707
  if (run.inputPath?.startsWith(`${dir}/`) && existsSync5(run.inputPath)) return run.inputPath;
9697
9708
  }
@@ -9837,14 +9848,14 @@ async function idsFromRun(ctx, runId) {
9837
9848
  return { ...idItems(ids2), source: "run" };
9838
9849
  }
9839
9850
  async function collectIds(ctx, flags, kind, dryRun2) {
9840
- const command33 = `kenso contacts ${kind}`;
9851
+ const command35 = `kenso contacts ${kind}`;
9841
9852
  const ids2 = stringFlag2(flags, "ids");
9842
9853
  const where = kind === "restore" ? void 0 : stringFlag2(flags, "where");
9843
9854
  const run = kind === "restore" ? stringFlag2(flags, "run") : void 0;
9844
9855
  const given = [ids2, where, run].filter((v) => v !== void 0).length;
9845
9856
  if (given !== 1) {
9846
9857
  const choices = kind === "restore" ? "--ids <file|-> or --run <runId>" : "--ids <file|-> or --where '<json>'";
9847
- throw usageError(`${command33} needs exactly one of ${choices}.`, { field: "ids", next: `${command33} --help` });
9858
+ throw usageError(`${command35} needs exactly one of ${choices}.`, { field: "ids", next: `${command35} --help` });
9848
9859
  }
9849
9860
  if (ids2 !== void 0) return idsFromFile(ctx, ids2);
9850
9861
  if (where !== void 0) return idsFromWhere(ctx, kind, flags, where, dryRun2);
@@ -12050,17 +12061,367 @@ var init_studio2 = __esm({
12050
12061
  }
12051
12062
  });
12052
12063
 
12053
- // src/commands/work/common.ts
12054
- import { randomUUID } from "node:crypto";
12064
+ // src/commands/webhooks/local.ts
12065
+ import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
12066
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
12055
12067
  import { join as join15 } from "node:path";
12068
+ function webhooksDir(env) {
12069
+ const dir = join15(configDir(env), "webhooks");
12070
+ mkdirSync4(dir, { recursive: true, mode: 448 });
12071
+ return dir;
12072
+ }
12073
+ function signingSecretPath(env) {
12074
+ return join15(webhooksDir(env), "signing-secret");
12075
+ }
12076
+ function signingSecret(env) {
12077
+ const file = signingSecretPath(env);
12078
+ try {
12079
+ const saved = readFileSync10(file, "utf8").trim();
12080
+ if (/^whsec_[A-Za-z0-9+/]{32,}={0,2}$/.test(saved)) return saved;
12081
+ } catch {
12082
+ }
12083
+ const secret = `whsec_${randomBytes2(24).toString("base64")}`;
12084
+ writeFileSync4(file, `${secret}
12085
+ `, { mode: 384 });
12086
+ return secret;
12087
+ }
12088
+ function signatureHeaders(secret, id, body, nowMs = Date.now()) {
12089
+ const timestamp = String(Math.floor(nowMs / 1e3));
12090
+ const key = Buffer.from(secret.slice("whsec_".length), "base64");
12091
+ const signature = createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest("base64");
12092
+ return { "svix-id": id, "svix-timestamp": timestamp, "svix-signature": `v1,${signature}` };
12093
+ }
12094
+ function forwardUrl(text3) {
12095
+ const trimmed = text3.trim();
12096
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
12097
+ let url;
12098
+ try {
12099
+ url = new URL(withScheme);
12100
+ } catch {
12101
+ throw usageError(`--forward-to "${text3}" is not a URL.`, { field: "forward-to", hint: "Use the URL of your handler, for example http://localhost:3000/hook." });
12102
+ }
12103
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
12104
+ throw usageError(`--forward-to must be an http or https URL, not ${url.protocol}`, { field: "forward-to" });
12105
+ }
12106
+ return url.toString();
12107
+ }
12108
+ async function forward(url, event, secret, signal) {
12109
+ const started = Date.now();
12110
+ try {
12111
+ const res = await fetch(url, {
12112
+ method: "POST",
12113
+ headers: { "content-type": "application/json", "user-agent": `kenso-cli/${VERSION} (webhooks listen)`, ...signatureHeaders(secret, event.eventId, event.body) },
12114
+ body: event.body,
12115
+ signal: AbortSignal.any([signal, AbortSignal.timeout(FORWARD_TIMEOUT_MS)])
12116
+ });
12117
+ await res.arrayBuffer();
12118
+ return { url, status: res.status, ms: Date.now() - started };
12119
+ } catch (err) {
12120
+ const cause = err.cause?.code;
12121
+ return { url, ms: Date.now() - started, error: cause ?? (err instanceof Error ? err.message : String(err)) };
12122
+ }
12123
+ }
12124
+ function statePath(env, workspaceId) {
12125
+ return join15(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
12126
+ }
12127
+ function writeListenerState(env, workspaceId, state) {
12128
+ writeFileSync4(statePath(env, workspaceId), `${JSON.stringify(state)}
12129
+ `, { mode: 384 });
12130
+ }
12131
+ function readListenerState(env, workspaceId) {
12132
+ try {
12133
+ const state = JSON.parse(readFileSync10(statePath(env, workspaceId), "utf8"));
12134
+ return typeof state.url === "string" && typeof state.token === "string" ? state : void 0;
12135
+ } catch {
12136
+ return void 0;
12137
+ }
12138
+ }
12139
+ function removeListenerState(env, workspaceId, token) {
12140
+ if (readListenerState(env, workspaceId)?.token === token) rmSync2(statePath(env, workspaceId), { force: true });
12141
+ }
12142
+ var FORWARD_TIMEOUT_MS;
12143
+ var init_local = __esm({
12144
+ "src/commands/webhooks/local.ts"() {
12145
+ "use strict";
12146
+ init_config();
12147
+ init_errors();
12148
+ init_version();
12149
+ FORWARD_TIMEOUT_MS = 15e3;
12150
+ }
12151
+ });
12152
+
12153
+ // src/commands/webhooks/listen.ts
12154
+ var listen_exports = {};
12155
+ __export(listen_exports, {
12156
+ default: () => listen_default,
12157
+ liveBody: () => liveBody
12158
+ });
12159
+ import { randomBytes as randomBytes3 } from "node:crypto";
12056
12160
  import { setTimeout as delay6 } from "node:timers/promises";
12161
+ function eventTypes(value) {
12162
+ const list2 = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
12163
+ return list2.flatMap((item) => item.split(",")).map((item) => item.trim()).filter((item) => item !== "");
12164
+ }
12165
+ function liveBody(event, workspaceId) {
12166
+ const data = event.data !== null && typeof event.data === "object" && !Array.isArray(event.data) ? event.data : {};
12167
+ const clientId = workspaceId && /^\d+$/.test(workspaceId) ? { clientId: Number(workspaceId) } : {};
12168
+ const envelope = { eventType: event.name ?? "", eventId: event.eventId ?? "", timestamp: event.timestamp ?? "", ...clientId };
12169
+ return { ...envelope, ...data, ...envelope };
12170
+ }
12171
+ function survivable(err) {
12172
+ if (!(err instanceof KensoError)) return false;
12173
+ const fatal = [ExitCode.Auth, ExitCode.Usage, ExitCode.NotFound];
12174
+ return !fatal.includes(err.exitCode);
12175
+ }
12176
+ async function poll2(ctx, types, cursor2) {
12177
+ const res = await ctx.client.request({ method: "GET", path: "/v1/event-occurrences", query: { cursor: cursor2, types: types.length > 0 ? types.join(",") : void 0 } });
12178
+ return unwrap(res.body) ?? {};
12179
+ }
12180
+ function readBody(req) {
12181
+ return new Promise((resolve16, reject) => {
12182
+ let size = 0;
12183
+ const chunks = [];
12184
+ req.on("data", (chunk) => {
12185
+ size += chunk.length;
12186
+ if (size > MAX_TRIGGER_BYTES) req.destroy(new Error("too large"));
12187
+ else chunks.push(chunk);
12188
+ });
12189
+ req.on("end", () => resolve16(Buffer.concat(chunks).toString("utf8")));
12190
+ req.on("error", reject);
12191
+ });
12192
+ }
12193
+ function reply(res, status, body) {
12194
+ res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
12195
+ }
12196
+ var MIN_POLL_MS, MAX_POLL_MS, MAX_TRIGGER_BYTES, command26, listen_default;
12197
+ var init_listen = __esm({
12198
+ "src/commands/webhooks/listen.ts"() {
12199
+ "use strict";
12200
+ init_errors();
12201
+ init_exit_codes();
12202
+ init_http();
12203
+ init_local();
12204
+ MIN_POLL_MS = 1e3;
12205
+ MAX_POLL_MS = 6e4;
12206
+ MAX_TRIGGER_BYTES = 1e6;
12207
+ command26 = {
12208
+ resource: "webhooks",
12209
+ action: "listen",
12210
+ summary: "Stream the workspace's events and forward them, signed, to a local handler",
12211
+ brief: "--forward-to",
12212
+ description: "Polls GET /v1/event-occurrences and prints each event as one JSON line. With --forward-to it also POSTs each event to your handler with the svix-id, svix-timestamp and svix-signature headers a Kenso delivery carries, signed with a local whsec_ secret the documented verifier accepts. The secret is printed at start and stays the same on every run. A live event's body is sparse: the delivery's eventType, eventId, timestamp and clientId, and only the ids, statuses and links the event log keeps, at their delivery paths (no names, emails or reply text). kenso webhooks trigger <event-type> sends a full sample body through the running listener. No webhook endpoint, subscription or tunnel is created.",
12213
+ flags: {
12214
+ "forward-to": { type: "string", description: "Your handler's URL, for example http://localhost:3000/hook (http:// is assumed)" },
12215
+ events: { type: "string", multiple: true, description: "Only these event types (repeat or comma-separate). Default: every type you can receive" },
12216
+ "print-secret": { type: "boolean", description: "Print the signing secret and exit" }
12217
+ },
12218
+ examples: [
12219
+ "kenso webhooks listen --forward-to http://localhost:3000/hook",
12220
+ "kenso webhooks listen --forward-to localhost:3000/hook --events reply.received,meeting.booked",
12221
+ "kenso webhooks listen --print-secret"
12222
+ ],
12223
+ helpFooter: ["Stop with Ctrl-C. Real events arrive within about 30 s (the poll interval); a trigger arrives at once."],
12224
+ operationIds: ["event-occurrences.poll"],
12225
+ dryRun: true,
12226
+ async run(ctx, { flags }) {
12227
+ const secret = signingSecret(ctx.env);
12228
+ if (flags["print-secret"] === true) {
12229
+ ctx.output.writeRaw(`${secret}
12230
+ `);
12231
+ return ExitCode.Ok;
12232
+ }
12233
+ const target = typeof flags["forward-to"] === "string" ? forwardUrl(flags["forward-to"]) : void 0;
12234
+ const types = eventTypes(flags.events);
12235
+ const workspaceId = ctx.auth.workspaceId;
12236
+ if (ctx.flags.dryRun) {
12237
+ const next = ["kenso webhooks listen", target ? `--forward-to ${target}` : "", types.length > 0 ? `--events ${types.join(",")}` : ""];
12238
+ ctx.output.object({ dryRun: true, forwardTo: target ?? null, events: types.length > 0 ? types : "all", secretFile: signingSecretPath(ctx.env), next: next.filter((p) => p).join(" ") });
12239
+ return ExitCode.Ok;
12240
+ }
12241
+ const counts2 = { events: 0, forwarded: 0, failed: 0 };
12242
+ const deliver = async (event) => {
12243
+ const result = target ? await forward(target, event, secret, ctx.signal) : void 0;
12244
+ counts2.events++;
12245
+ if (result?.status !== void 0 && result.status < 300) counts2.forwarded++;
12246
+ else if (result) counts2.failed++;
12247
+ const line = { eventId: event.eventId, type: event.type, timestamp: event.timestamp, source: event.source, ...result ? { forward: result } : {}, data: JSON.parse(event.body) };
12248
+ ctx.output.writeRaw(`${JSON.stringify(line)}
12249
+ `);
12250
+ return result;
12251
+ };
12252
+ let live = true;
12253
+ let cursor2;
12254
+ try {
12255
+ cursor2 = (await poll2(ctx, types, void 0)).cursor;
12256
+ } catch (err) {
12257
+ if (err instanceof KensoError && err.httpStatus === 404 && err.field === void 0) {
12258
+ live = false;
12259
+ ctx.output.warn(`Live events are not on for this workspace (${err.message}). Samples from kenso webhooks trigger still come through.`);
12260
+ } else if (!ctx.signal.aborted && survivable(err)) {
12261
+ ctx.output.warn(`Polling failed (${err.message}); trying again.`);
12262
+ } else {
12263
+ throw err;
12264
+ }
12265
+ }
12266
+ const token = randomBytes3(32).toString("base64url");
12267
+ const { createServer } = await import("node:http");
12268
+ const server = createServer((req, res) => {
12269
+ if (req.method !== "POST" || req.url !== "/events") return reply(res, 404, { error: "not_found" });
12270
+ if (req.headers.authorization !== `Bearer ${token}`) return reply(res, 401, { error: "unauthorized" });
12271
+ readBody(req).then(async (text3) => {
12272
+ const sent = JSON.parse(text3);
12273
+ const result = await deliver({ eventId: sent.eventId, type: sent.type, timestamp: sent.timestamp, source: "trigger", body: JSON.stringify(sent.data) });
12274
+ reply(res, 200, { forward: result ?? null });
12275
+ }).catch(() => reply(res, 400, { error: "invalid_event" }));
12276
+ });
12277
+ await new Promise((resolve16) => server.listen(0, "127.0.0.1", resolve16));
12278
+ const url = `http://127.0.0.1:${server.address().port}/events`;
12279
+ writeListenerState(ctx.env, workspaceId, { pid: process.pid, url, token, forwardTo: target, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
12280
+ try {
12281
+ ctx.output.info(`Ready. ${target ? `Forwarding events to ${target}.` : "Printing events (add --forward-to to send them to your handler)."}`);
12282
+ ctx.output.info(`Signing secret: ${secret} (the same on every run; kept in ${signingSecretPath(ctx.env)}).`);
12283
+ ctx.output.info(`Send a sample: kenso webhooks trigger reply.received. Stop with Ctrl-C.`);
12284
+ while (!ctx.signal.aborted) {
12285
+ let waitMs = MAX_POLL_MS;
12286
+ if (live) {
12287
+ try {
12288
+ const page = await poll2(ctx, types, cursor2);
12289
+ for (const event of page.events ?? []) {
12290
+ const body = JSON.stringify(liveBody(event, workspaceId));
12291
+ await deliver({ eventId: event.eventId ?? "", type: event.name ?? "", timestamp: event.timestamp ?? "", source: "live", body });
12292
+ }
12293
+ cursor2 = page.cursor ?? cursor2;
12294
+ waitMs = page.hasMore ? 0 : Math.min(MAX_POLL_MS, Math.max(MIN_POLL_MS, page.nextPollMs ?? MAX_POLL_MS));
12295
+ } catch (err) {
12296
+ if (ctx.signal.aborted || !survivable(err)) throw err;
12297
+ ctx.output.warn(`Polling failed (${err.message}); trying again in ${MAX_POLL_MS / 1e3} s.`);
12298
+ }
12299
+ }
12300
+ await delay6(waitMs, void 0, { signal: ctx.signal }).catch(() => void 0);
12301
+ }
12302
+ } catch (err) {
12303
+ if (!ctx.signal.aborted) throw err;
12304
+ } finally {
12305
+ server.close();
12306
+ server.closeAllConnections();
12307
+ removeListenerState(ctx.env, workspaceId, token);
12308
+ ctx.output.info(`Stopped: ${counts2.events} events, ${counts2.forwarded} forwarded, ${counts2.failed} failed. No endpoint or subscription was created.`);
12309
+ }
12310
+ return ExitCode.Ok;
12311
+ }
12312
+ };
12313
+ listen_default = command26;
12314
+ }
12315
+ });
12316
+
12317
+ // src/commands/webhooks/trigger.ts
12318
+ var trigger_exports = {};
12319
+ __export(trigger_exports, {
12320
+ default: () => trigger_default
12321
+ });
12322
+ import { randomUUID } from "node:crypto";
12323
+ function notRunning() {
12324
+ return new KensoError({
12325
+ code: "listener_not_running",
12326
+ message: "No kenso webhooks listen is running for this workspace.",
12327
+ exitCode: ExitCode.Error,
12328
+ hint: "Start the listener in another terminal, then trigger again.",
12329
+ next: LISTEN_NEXT
12330
+ });
12331
+ }
12332
+ var LISTEN_NEXT, command27, trigger_default;
12333
+ var init_trigger = __esm({
12334
+ "src/commands/webhooks/trigger.ts"() {
12335
+ "use strict";
12336
+ init_errors();
12337
+ init_exit_codes();
12338
+ init_http();
12339
+ init_local();
12340
+ LISTEN_NEXT = "kenso webhooks listen --forward-to http://localhost:3000/hook";
12341
+ command27 = {
12342
+ resource: "webhooks",
12343
+ action: "trigger",
12344
+ summary: "Send a sample event of one type through the running kenso webhooks listen",
12345
+ description: "Takes the event type's sample body from GET /v1/webhook-event-types, gives it a new eventId and the current timestamp, and hands it to the kenso webhooks listen running for this workspace, which prints it and forwards it, signed, like a live event. Nothing is sent to anyone else. Exit 1 when the handler did not answer 2xx.",
12346
+ flags: {},
12347
+ positionals: [{ name: "event-type", required: true, description: "An event type, for example reply.received (kenso webhook-event-types list)" }],
12348
+ examples: ["kenso webhooks trigger reply.received", "kenso webhooks trigger meeting.booked"],
12349
+ operationIds: ["webhook-event-types.list"],
12350
+ dryRun: true,
12351
+ async run(ctx, { positionals }) {
12352
+ const type = (positionals[0] ?? "").trim();
12353
+ if (type === "") throw usageError("Name the event type.", { field: "event-type", next: "kenso webhook-event-types list" });
12354
+ const listener = readListenerState(ctx.env, ctx.auth.workspaceId);
12355
+ if (!listener) throw notRunning();
12356
+ const res = await ctx.client.request({ method: "GET", path: "/v1/webhook-event-types" });
12357
+ const types = unwrap(res.body) ?? [];
12358
+ const found = types.find((t) => t.name === type);
12359
+ if (!found) {
12360
+ const names = types.map((t) => t.name).filter((n) => typeof n === "string");
12361
+ throw usageError(`Unknown event type "${type}".`, { field: "event-type", hint: `Types: ${names.join(", ")}.`, next: "kenso webhook-event-types list" });
12362
+ }
12363
+ const eventId = `evt_test_${randomUUID()}`;
12364
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
12365
+ const sample = found.sample !== null && typeof found.sample === "object" && !Array.isArray(found.sample) ? found.sample : void 0;
12366
+ const data = sample ? { ...sample, ..."eventId" in sample ? { eventId } : {}, ..."timestamp" in sample ? { timestamp } : {} } : found.sample;
12367
+ if (ctx.flags.dryRun) {
12368
+ ctx.output.object({ dryRun: true, eventId, type, listener: listener.url, forwardTo: listener.forwardTo ?? null, data, next: `kenso webhooks trigger ${type}` });
12369
+ return ExitCode.Ok;
12370
+ }
12371
+ let answer;
12372
+ try {
12373
+ const sent = await fetch(listener.url, {
12374
+ method: "POST",
12375
+ headers: { "content-type": "application/json", authorization: `Bearer ${listener.token}` },
12376
+ body: JSON.stringify({ eventId, type, timestamp, data }),
12377
+ signal: ctx.signal
12378
+ });
12379
+ if (!sent.ok) throw notRunning();
12380
+ answer = await sent.json();
12381
+ } catch (err) {
12382
+ if (err instanceof KensoError || ctx.signal.aborted) throw err;
12383
+ throw notRunning();
12384
+ }
12385
+ ctx.output.object({ eventId, type, forward: answer.forward });
12386
+ const forwarded = answer.forward;
12387
+ if (forwarded && (forwarded.status === void 0 || forwarded.status >= 300)) {
12388
+ throw new KensoError({
12389
+ code: "forward_failed",
12390
+ message: `Your handler at ${forwarded.url} answered ${forwarded.status ?? forwarded.error ?? "nothing"}.`,
12391
+ exitCode: ExitCode.Error,
12392
+ hint: "The listener's output has the event; fix the handler and trigger again."
12393
+ });
12394
+ }
12395
+ return ExitCode.Ok;
12396
+ }
12397
+ };
12398
+ trigger_default = command27;
12399
+ }
12400
+ });
12401
+
12402
+ // src/commands/webhooks/index.ts
12403
+ var actions15;
12404
+ var init_webhooks2 = __esm({
12405
+ "src/commands/webhooks/index.ts"() {
12406
+ "use strict";
12407
+ actions15 = {
12408
+ listen: () => Promise.resolve().then(() => (init_listen(), listen_exports)).then((m) => m.default),
12409
+ trigger: () => Promise.resolve().then(() => (init_trigger(), trigger_exports)).then((m) => m.default)
12410
+ };
12411
+ }
12412
+ });
12413
+
12414
+ // src/commands/work/common.ts
12415
+ import { randomUUID as randomUUID2 } from "node:crypto";
12416
+ import { join as join16 } from "node:path";
12417
+ import { setTimeout as delay7 } from "node:timers/promises";
12057
12418
  function unavailable(err) {
12058
12419
  return err instanceof KensoError && (err.code === "network_error" || err.httpStatus === 502 || err.httpStatus === 503 || err.httpStatus === 504);
12059
12420
  }
12060
12421
  async function pause2(ms, signal) {
12061
12422
  if (signal.aborted) return false;
12062
12423
  try {
12063
- await delay6(ms, void 0, { signal });
12424
+ await delay7(ms, void 0, { signal });
12064
12425
  return true;
12065
12426
  } catch {
12066
12427
  return false;
@@ -12124,7 +12485,7 @@ function shellQuote5(value) {
12124
12485
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
12125
12486
  }
12126
12487
  function submitCommand(dir) {
12127
- return `kenso work submit ${shellQuote5(join15(dir, "/"))}*.answers.json`;
12488
+ return `kenso work submit ${shellQuote5(join16(dir, "/"))}*.answers.json`;
12128
12489
  }
12129
12490
  function explainNotFound(err) {
12130
12491
  if (!(err instanceof KensoError) || err.httpStatus !== 404 || err.hint !== void 0) return err;
@@ -12144,7 +12505,7 @@ async function claimWork(ctx, req, headers, waitSignal) {
12144
12505
  const body = { limit: req.limit, leaseMinutes: req.leaseMinutes };
12145
12506
  if (req.kinds) body.kinds = req.kinds;
12146
12507
  if (req.campaignId !== void 0) body.campaignId = req.campaignId;
12147
- const key = randomUUID();
12508
+ const key = randomUUID2();
12148
12509
  let res;
12149
12510
  try {
12150
12511
  res = await untilAvailable(
@@ -12230,14 +12591,14 @@ var status_exports2 = {};
12230
12591
  __export(status_exports2, {
12231
12592
  default: () => status_default2
12232
12593
  });
12233
- var command26, status_default2;
12594
+ var command28, status_default2;
12234
12595
  var init_status2 = __esm({
12235
12596
  "src/commands/work/status.ts"() {
12236
12597
  "use strict";
12237
12598
  init_exit_codes();
12238
12599
  init_http();
12239
12600
  init_common3();
12240
- command26 = {
12601
+ command28 = {
12241
12602
  resource: "work",
12242
12603
  action: "status",
12243
12604
  summary: "Show the Kenso AI work waiting for your own agent, per kind",
@@ -12270,13 +12631,13 @@ var init_status2 = __esm({
12270
12631
  return ExitCode.Ok;
12271
12632
  }
12272
12633
  };
12273
- status_default2 = command26;
12634
+ status_default2 = command28;
12274
12635
  }
12275
12636
  });
12276
12637
 
12277
12638
  // src/work/files.ts
12278
- import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync as readFileSync10, writeFileSync as writeFileSync4 } from "node:fs";
12279
- import { join as join16 } from "node:path";
12639
+ import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
12640
+ import { join as join17 } from "node:path";
12280
12641
  function agentName(value) {
12281
12642
  if (typeof value !== "string") return void 0;
12282
12643
  const name = value.trim().slice(0, MAX_AGENT_NAME);
@@ -12295,10 +12656,10 @@ function workFileName(claimId) {
12295
12656
  function writeWorkFile(dir, work, mode = 384) {
12296
12657
  const name = workFileName(work.claimId);
12297
12658
  if (!isPlainFileName(work.answersFile)) throw new Error("answersFile is not a plain file name");
12298
- const path = join16(dir, name);
12659
+ const path = join17(dir, name);
12299
12660
  const fd = openSync(path, "wx", mode);
12300
12661
  try {
12301
- writeFileSync4(fd, JSON.stringify(work, null, 2) + "\n", "utf8");
12662
+ writeFileSync5(fd, JSON.stringify(work, null, 2) + "\n", "utf8");
12302
12663
  fchmodSync(fd, mode);
12303
12664
  } finally {
12304
12665
  closeSync(fd);
@@ -12313,7 +12674,7 @@ function readRegularFile(path, what) {
12313
12674
  const stat3 = fstatSync(fd);
12314
12675
  if (!stat3.isFile()) return notPlain;
12315
12676
  if (stat3.size > MAX_ANSWERS_FILE_BYTES) return { ok: false, error: `the ${what} is too large` };
12316
- return readFileSync10(fd, "utf8");
12677
+ return readFileSync11(fd, "utf8");
12317
12678
  } finally {
12318
12679
  closeSync(fd);
12319
12680
  }
@@ -12400,11 +12761,11 @@ var init_files = __esm({
12400
12761
 
12401
12762
  // src/work/agent-user.ts
12402
12763
  import { execFile, spawnSync as spawnSync2 } from "node:child_process";
12403
- import { readFileSync as readFileSync11 } from "node:fs";
12764
+ import { readFileSync as readFileSync12 } from "node:fs";
12404
12765
  import { isAbsolute as isAbsolute2 } from "node:path";
12405
- function sudoArgs(user, command33, args, keep = [], set = {}) {
12766
+ function sudoArgs(user, command35, args, keep = [], set = {}) {
12406
12767
  const assignments = Object.entries(set).map(([name, value]) => `${name}=${value}`);
12407
- return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command33, ...args];
12768
+ return ["-n", "-u", user, "-H", ...keep.length > 0 ? [`--preserve-env=${keep.join(",")}`] : [], ...assignments, "--", command35, ...args];
12408
12769
  }
12409
12770
  function agentKensoEnv(opts) {
12410
12771
  return {
@@ -12414,12 +12775,12 @@ function agentKensoEnv(opts) {
12414
12775
  AI_AGENT: opts.agentName
12415
12776
  };
12416
12777
  }
12417
- function sudoExec(user, command33, args, opts = {}) {
12778
+ function sudoExec(user, command35, args, opts = {}) {
12418
12779
  const [sudo = "/usr/bin/sudo", ...lead] = user.sudo;
12419
12780
  return new Promise((resolve16) => {
12420
12781
  execFile(
12421
12782
  sudo,
12422
- [...lead, ...sudoArgs(user.name, command33, args)],
12783
+ [...lead, ...sudoArgs(user.name, command35, args)],
12423
12784
  { env: { PATH: SUDO_PATH }, cwd: "/", timeout: opts.timeoutMs ?? PROBE_TIMEOUT_MS, maxBuffer: opts.maxBuffer ?? 1024 * 1024, encoding: "utf8", windowsHide: true, shell: false },
12424
12785
  (err, stdout, stderr) => {
12425
12786
  const code = err ? err.code : 0;
@@ -12457,7 +12818,7 @@ function ids(status, field) {
12457
12818
  }
12458
12819
  function sudoGids(groupFile) {
12459
12820
  const gids = /* @__PURE__ */ new Set([0]);
12460
- for (const line of readFileSync11(groupFile, "utf8").split("\n")) {
12821
+ for (const line of readFileSync12(groupFile, "utf8").split("\n")) {
12461
12822
  const [group, , gid] = line.split(":");
12462
12823
  if (group !== void 0 && SUDO_GROUPS.has(group) && /^\d+$/.test(gid ?? "")) gids.add(Number(gid));
12463
12824
  }
@@ -12519,7 +12880,7 @@ var init_agent_user = __esm({
12519
12880
  // src/commands/work/folder.ts
12520
12881
  import { existsSync as existsSync8 } from "node:fs";
12521
12882
  import { appendFile as appendFile3, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
12522
- import { dirname as dirname3, join as join17, resolve as resolve13 } from "node:path";
12883
+ import { dirname as dirname3, join as join18, resolve as resolve13 } from "node:path";
12523
12884
  var WorkRunFolder;
12524
12885
  var init_folder2 = __esm({
12525
12886
  "src/commands/work/folder.ts"() {
@@ -12529,9 +12890,9 @@ var init_folder2 = __esm({
12529
12890
  init_redact();
12530
12891
  init_agent_user();
12531
12892
  WorkRunFolder = class {
12532
- constructor(ctx, command33, args, outDir, shared = false) {
12893
+ constructor(ctx, command35, args, outDir, shared = false) {
12533
12894
  this.ctx = ctx;
12534
- this.command = command33;
12895
+ this.command = command35;
12535
12896
  this.args = args;
12536
12897
  this.outDir = outDir;
12537
12898
  this.shared = shared;
@@ -12561,12 +12922,12 @@ var init_folder2 = __esm({
12561
12922
  const makeDir = (path) => this.shared ? ensureDir(path, SHARED_DIR_MODE) : ensurePrivateDir2(path);
12562
12923
  let dir;
12563
12924
  if (this.outDir === void 0) {
12564
- dir = join17(root2, this.runId);
12925
+ dir = join18(root2, this.runId);
12565
12926
  if (!this.shared) ensurePrivateDir2(root2);
12566
12927
  makeDir(dir);
12567
12928
  } else {
12568
12929
  dir = resolve13(this.outDir);
12569
- const existing = existsSync8(join17(dir, "run.json")) ? await readRunDir(dir) : null;
12930
+ const existing = existsSync8(join18(dir, "run.json")) ? await readRunDir(dir) : null;
12570
12931
  if (existing && !existing.command.startsWith("work ")) {
12571
12932
  throw usageError(`${dir} already holds run ${existing.runId} (${existing.command}).`, {
12572
12933
  field: "out",
@@ -12574,17 +12935,17 @@ var init_folder2 = __esm({
12574
12935
  });
12575
12936
  }
12576
12937
  makeDir(dir);
12577
- for (const name of ["results.ndjson", "summary.json"]) await unlink3(join17(dir, name)).catch(() => void 0);
12938
+ for (const name of ["results.ndjson", "summary.json"]) await unlink3(join18(dir, name)).catch(() => void 0);
12578
12939
  try {
12579
12940
  if (!this.shared) ensurePrivateDir2(root2);
12580
- await symlink2(dir, join17(root2, this.runId), "junction");
12941
+ await symlink2(dir, join18(root2, this.runId), "junction");
12581
12942
  } catch (err) {
12582
12943
  this.ctx.output.warn(`Could not link ${dir} into ${root2} (${err.message}): kenso runs will not list this run.`);
12583
12944
  }
12584
12945
  }
12585
12946
  this.dir = dir;
12586
12947
  if (this.shared) {
12587
- this.tmpDir = join17(dir, "tmp");
12948
+ this.tmpDir = join18(dir, "tmp");
12588
12949
  ensureDir(this.tmpDir, JOB_DIR_MODE);
12589
12950
  }
12590
12951
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -12611,7 +12972,7 @@ var init_folder2 = __esm({
12611
12972
  * writes (3770) under a jobs folder it can only pass through (2750).
12612
12973
  */
12613
12974
  async jobDir(claimId) {
12614
- const dir = join17(await this.ensure(), "jobs", claimId);
12975
+ const dir = join18(await this.ensure(), "jobs", claimId);
12615
12976
  if (this.shared) {
12616
12977
  ensureDir(dirname3(dir), SHARED_DIR_MODE);
12617
12978
  ensureDir(dir, JOB_DIR_MODE);
@@ -12627,13 +12988,13 @@ var init_folder2 = __esm({
12627
12988
  async append(line) {
12628
12989
  if (!this.dir) return;
12629
12990
  const json = JSON.stringify(line, (_key, value) => typeof value === "string" ? redact(value) : value);
12630
- await appendFile3(join17(this.dir, "results.ndjson"), `${json}
12991
+ await appendFile3(join18(this.dir, "results.ndjson"), `${json}
12631
12992
  `, { mode: 384 });
12632
12993
  }
12633
12994
  /** summary.json, and run.json with the final status, the claims (chunkCount) and the items (rows). */
12634
12995
  async finish(status, claims, items, summary) {
12635
12996
  if (!this.dir || !this.record) return;
12636
- await writeJsonAtomic(join17(this.dir, "summary.json"), summary);
12997
+ await writeJsonAtomic(join18(this.dir, "summary.json"), summary);
12637
12998
  this.record = { ...this.record, status, chunkCount: claims, rows: items, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
12638
12999
  await writeRunRecord(this.record);
12639
13000
  }
@@ -12646,7 +13007,7 @@ var pull_exports2 = {};
12646
13007
  __export(pull_exports2, {
12647
13008
  default: () => pull_default2
12648
13009
  });
12649
- var MAX_FILES, command27, pull_default2;
13010
+ var MAX_FILES, command29, pull_default2;
12650
13011
  var init_pull2 = __esm({
12651
13012
  "src/commands/work/pull.ts"() {
12652
13013
  "use strict";
@@ -12655,7 +13016,7 @@ var init_pull2 = __esm({
12655
13016
  init_common3();
12656
13017
  init_folder2();
12657
13018
  MAX_FILES = 100;
12658
- command27 = {
13019
+ command29 = {
12659
13020
  resource: "work",
12660
13021
  action: "pull",
12661
13022
  summary: "Claim waiting work into local work files, to answer by hand",
@@ -12731,14 +13092,14 @@ var init_pull2 = __esm({
12731
13092
  return interrupted6 ? ExitCode.Interrupted : ExitCode.Ok;
12732
13093
  }
12733
13094
  };
12734
- pull_default2 = command27;
13095
+ pull_default2 = command29;
12735
13096
  }
12736
13097
  });
12737
13098
 
12738
13099
  // src/commands/work/answers.ts
12739
- import { randomUUID as randomUUID2 } from "node:crypto";
13100
+ import { randomUUID as randomUUID3 } from "node:crypto";
12740
13101
  import { existsSync as existsSync9 } from "node:fs";
12741
- import { basename as basename4, dirname as dirname4, join as join18 } from "node:path";
13102
+ import { basename as basename4, dirname as dirname4, join as join19 } from "node:path";
12742
13103
  function zeroTotals() {
12743
13104
  return { accepted: 0, rejected: 0, expired: 0, duplicate: 0, dropped: 0 };
12744
13105
  }
@@ -12767,7 +13128,7 @@ async function sendAnswers(ctx, claimId, answers, agent, headers, waitSignal) {
12767
13128
  const chunk = pending.slice(at, at + MAX_ANSWERS_PER_CALL);
12768
13129
  const body = { answers: chunk };
12769
13130
  if (agent.cli !== void 0 || agent.model !== void 0) body.agent = agent;
12770
- const key = randomUUID2();
13131
+ const key = randomUUID3();
12771
13132
  let res;
12772
13133
  try {
12773
13134
  res = await untilAvailable(
@@ -12810,7 +13171,7 @@ function droppedResult(d) {
12810
13171
  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, " ")}.` };
12811
13172
  }
12812
13173
  async function writeResults(answersPath, claimId, results, totals) {
12813
- const path = join18(dirname4(answersPath), `${claimId}.results.json`);
13174
+ const path = join19(dirname4(answersPath), `${claimId}.results.json`);
12814
13175
  await writeJsonAtomic(path, { version: 1, claimId, submittedAt: (/* @__PURE__ */ new Date()).toISOString(), ...totals, results });
12815
13176
  return path;
12816
13177
  }
@@ -12839,7 +13200,7 @@ function workFileNextTo(answersPath) {
12839
13200
  hint: "Write the answers to <claimId>.answers.json next to its <claimId>.work.json, as the work file's rules say."
12840
13201
  });
12841
13202
  }
12842
- const workPath = join18(dirname4(answersPath), `${claimId}.work.json`);
13203
+ const workPath = join19(dirname4(answersPath), `${claimId}.work.json`);
12843
13204
  if (!existsSync9(workPath)) {
12844
13205
  throw usageError(`${workPath} is missing: kenso work submit reads it next to the answers file.`, { field: "answers-file" });
12845
13206
  }
@@ -12873,7 +13234,7 @@ __export(submit_exports, {
12873
13234
  default: () => submit_default
12874
13235
  });
12875
13236
  import { resolve as resolve14 } from "node:path";
12876
- var command28, submit_default;
13237
+ var command30, submit_default;
12877
13238
  var init_submit = __esm({
12878
13239
  "src/commands/work/submit.ts"() {
12879
13240
  "use strict";
@@ -12882,7 +13243,7 @@ var init_submit = __esm({
12882
13243
  init_files();
12883
13244
  init_answers();
12884
13245
  init_common3();
12885
- command28 = {
13246
+ command30 = {
12886
13247
  resource: "work",
12887
13248
  action: "submit",
12888
13249
  summary: "Send answers files to Kenso and write each one's results",
@@ -12914,7 +13275,7 @@ var init_submit = __esm({
12914
13275
  return totals.rejected > 0 ? ExitCode.Partial : ExitCode.Ok;
12915
13276
  }
12916
13277
  };
12917
- submit_default = command28;
13278
+ submit_default = command30;
12918
13279
  }
12919
13280
  });
12920
13281
 
@@ -12935,7 +13296,7 @@ function claimIdOf(arg) {
12935
13296
  if (!CLAIM_ID.test(arg)) throw usageError(`"${arg}" is neither a claim id nor a work file.`, { field: "claim", hint: "Claim ids look like awc_8fK2..." });
12936
13297
  return arg;
12937
13298
  }
12938
- var CLAIM_ID, command29, release_default;
13299
+ var CLAIM_ID, command31, release_default;
12939
13300
  var init_release = __esm({
12940
13301
  "src/commands/work/release.ts"() {
12941
13302
  "use strict";
@@ -12944,7 +13305,7 @@ var init_release = __esm({
12944
13305
  init_files();
12945
13306
  init_common3();
12946
13307
  CLAIM_ID = /^[A-Za-z0-9_-]{1,64}$/;
12947
- command29 = {
13308
+ command31 = {
12948
13309
  resource: "work",
12949
13310
  action: "release",
12950
13311
  summary: "Give claimed work back to the queue now",
@@ -12963,16 +13324,16 @@ var init_release = __esm({
12963
13324
  return ExitCode.Ok;
12964
13325
  }
12965
13326
  };
12966
- release_default = command29;
13327
+ release_default = command31;
12967
13328
  }
12968
13329
  });
12969
13330
 
12970
13331
  // src/work/job.ts
12971
13332
  import { spawn as nodeSpawn2 } from "node:child_process";
12972
- import { rmSync as rmSync2, statSync as statSync2 } from "node:fs";
13333
+ import { rmSync as rmSync3, statSync as statSync2 } from "node:fs";
12973
13334
  import { access, constants as constants2 } from "node:fs/promises";
12974
- import { delimiter as delimiter2, join as join19 } from "node:path";
12975
- import { setTimeout as delay7 } from "node:timers/promises";
13335
+ import { delimiter as delimiter2, join as join20 } from "node:path";
13336
+ import { setTimeout as delay8 } from "node:timers/promises";
12976
13337
  function childEnv(parent, adapter, extra) {
12977
13338
  const scrub = new Set(adapter.scrubEnv.map((name) => name.toUpperCase()));
12978
13339
  const env = {};
@@ -13008,7 +13369,7 @@ async function resolveBinary(adapter, env, override2) {
13008
13369
  }
13009
13370
  for (const dir of pathDirs(env)) {
13010
13371
  for (const ext of extensions) {
13011
- const candidate = join19(dir, name + ext);
13372
+ const candidate = join20(dir, name + ext);
13012
13373
  if (await isExecutableFile(candidate)) return candidate;
13013
13374
  }
13014
13375
  }
@@ -13065,7 +13426,7 @@ async function groupGone(pid, runAs) {
13065
13426
  while (Date.now() < deadline) {
13066
13427
  if (runAs) {
13067
13428
  if (!await sudoKill(runAs, "SIGKILL", pid)) return;
13068
- await delay7(100);
13429
+ await delay8(100);
13069
13430
  continue;
13070
13431
  }
13071
13432
  try {
@@ -13073,7 +13434,7 @@ async function groupGone(pid, runAs) {
13073
13434
  } catch {
13074
13435
  return;
13075
13436
  }
13076
- await delay7(25);
13437
+ await delay8(25);
13077
13438
  }
13078
13439
  }
13079
13440
  function runChild(spawnFn, bin, built, job, env, signal, runAs) {
@@ -13174,13 +13535,13 @@ async function runAgentJob(adapter, job, deps) {
13174
13535
  }
13175
13536
  let work;
13176
13537
  try {
13177
- work = readWorkFile(join19(job.cwd, job.workFile));
13538
+ work = readWorkFile(join20(job.cwd, job.workFile));
13178
13539
  } catch (err) {
13179
13540
  return result("fatal", null, `the work file could not be read: ${err.message}`);
13180
13541
  }
13181
- const answersPath = join19(job.cwd, job.answersFile);
13542
+ const answersPath = join20(job.cwd, job.answersFile);
13182
13543
  try {
13183
- rmSync2(answersPath, { force: true });
13544
+ rmSync3(answersPath, { force: true });
13184
13545
  } catch (err) {
13185
13546
  return result("fatal", null, `the answers path could not be cleared: ${err.message}`);
13186
13547
  }
@@ -13302,12 +13663,12 @@ function plain(text3) {
13302
13663
  return text3.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
13303
13664
  }
13304
13665
  function runStatus(bin, args, env, adapter, runAs) {
13305
- const command33 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
13666
+ const command35 = runAs ? runAs.sudo[0] ?? "/usr/bin/sudo" : bin;
13306
13667
  const commandArgs2 = runAs ? [...runAs.sudo.slice(1), ...sudoArgs(runAs.name, bin, args)] : args;
13307
13668
  const options = runAs ? { env: { PATH: SUDO_PATH }, cwd: "/" } : { env: childEnv(env, adapter) };
13308
13669
  return new Promise((resolve16) => {
13309
13670
  execFile2(
13310
- command33,
13671
+ command35,
13311
13672
  commandArgs2,
13312
13673
  { ...options, timeout: STATUS_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
13313
13674
  (err, stdout, stderr) => {
@@ -13588,7 +13949,7 @@ ${out.stderr}`;
13588
13949
  });
13589
13950
 
13590
13951
  // src/work/adapters/opencode.ts
13591
- import { basename as basename5, join as join20 } from "node:path";
13952
+ import { basename as basename5, join as join21 } from "node:path";
13592
13953
  var opencode;
13593
13954
  var init_opencode = __esm({
13594
13955
  "src/work/adapters/opencode.ts"() {
@@ -13632,7 +13993,7 @@ ${out.stderr}`);
13632
13993
  if (job.model) args.push("--model", job.model);
13633
13994
  args.push(job.instruction);
13634
13995
  const env = { OPENCODE_CONFIG_CONTENT: JSON.stringify(config) };
13635
- if (job.tmpDir !== void 0) env.OPENCODE_DB = join20(job.tmpDir, `opencode-${basename5(job.cwd)}.db`);
13996
+ if (job.tmpDir !== void 0) env.OPENCODE_DB = join21(job.tmpDir, `opencode-${basename5(job.cwd)}.db`);
13636
13997
  return { args, env };
13637
13998
  },
13638
13999
  classify: classifyByExit
@@ -13675,7 +14036,7 @@ var init_adapters = __esm({
13675
14036
  });
13676
14037
 
13677
14038
  // src/work/scan.ts
13678
- import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
14039
+ import { createHmac as createHmac2, randomBytes as randomBytes4 } from "node:crypto";
13679
14040
  function fold(text3) {
13680
14041
  return text3.normalize("NFKC").replace(/[^A-Za-z0-9]/g, "").toLowerCase();
13681
14042
  }
@@ -13791,7 +14152,7 @@ var init_scan = __esm({
13791
14152
  TOKEN_RUN = /[A-Za-z0-9+/=_.-]{16,}/g;
13792
14153
  LINK = /^\W*(?:[a-z][a-z0-9+.-]*:\/\/|www\.)|^[^/]*\.[a-z]{2,}\//i;
13793
14154
  CredentialIndex = class {
13794
- key = randomBytes2(32);
14155
+ key = randomBytes4(32);
13795
14156
  exact = /* @__PURE__ */ new Set();
13796
14157
  folded = /* @__PURE__ */ new Set();
13797
14158
  /** Adds a credential file's text: its JSON string values (keys skipped), or the whole text when it is not JSON. */
@@ -13820,7 +14181,7 @@ var init_scan = __esm({
13820
14181
  return this.anyWindow(fold(reading), this.folded);
13821
14182
  }
13822
14183
  hash(window) {
13823
- return createHmac("sha256", this.key).update(window).digest("base64url");
14184
+ return createHmac2("sha256", this.key).update(window).digest("base64url");
13824
14185
  }
13825
14186
  addWindows(text3, into) {
13826
14187
  for (let i = 0; i + WINDOW <= text3.length; i++) into.add(this.hash(text3.slice(i, i + WINDOW)));
@@ -13835,7 +14196,7 @@ var init_scan = __esm({
13835
14196
 
13836
14197
  // src/work/credentials.ts
13837
14198
  import { createHash as createHash9 } from "node:crypto";
13838
- import { join as join21 } from "node:path";
14199
+ import { join as join22 } from "node:path";
13839
14200
  function unreadable(why) {
13840
14201
  return new KensoError({
13841
14202
  code: "credentials_unreadable",
@@ -13923,7 +14284,7 @@ var init_credentials = __esm({
13923
14284
  }
13924
14285
  }
13925
14286
  async read(rel) {
13926
- const r = await sudoExec(this.user, CAT, [join21(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
14287
+ const r = await sudoExec(this.user, CAT, [join22(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
13927
14288
  if (r.exitCode !== 0) return /No such file or directory/.test(r.stderr) ? "missing" : "unreadable";
13928
14289
  const digest = createHash9("sha256").update(r.stdout).digest("hex");
13929
14290
  if (this.seen.get(rel) !== digest) {
@@ -13937,8 +14298,8 @@ var init_credentials = __esm({
13937
14298
  });
13938
14299
 
13939
14300
  // src/work/guide.ts
13940
- import { closeSync as closeSync2, fchmodSync as fchmodSync2, openSync as openSync2, writeFileSync as writeFileSync5 } from "node:fs";
13941
- import { join as join22 } from "node:path";
14301
+ import { closeSync as closeSync2, fchmodSync as fchmodSync2, openSync as openSync2, writeFileSync as writeFileSync6 } from "node:fs";
14302
+ import { join as join23 } from "node:path";
13942
14303
  function agentGuide(opts) {
13943
14304
  const browser = opts.browser ?? findOperation("browser-runs", "create") !== void 0;
13944
14305
  const parts = opts.kensoKey ? [JOB, KENSO, ...browser ? [BROWSER] : [], NEVER] : [JOB, NO_KENSO, NEVER];
@@ -13946,9 +14307,9 @@ function agentGuide(opts) {
13946
14307
  }
13947
14308
  function writeAgentGuide(dir, text3, mode = WORK_FILE_MODE) {
13948
14309
  for (const name of GUIDE_FILES) {
13949
- const fd = openSync2(join22(dir, name), "wx", mode);
14310
+ const fd = openSync2(join23(dir, name), "wx", mode);
13950
14311
  try {
13951
- writeFileSync5(fd, text3, "utf8");
14312
+ writeFileSync6(fd, text3, "utf8");
13952
14313
  fchmodSync2(fd, mode);
13953
14314
  } finally {
13954
14315
  closeSync2(fd);
@@ -14387,7 +14748,7 @@ var run_exports = {};
14387
14748
  __export(run_exports, {
14388
14749
  default: () => run_default
14389
14750
  });
14390
- var FAILURES_IN_A_ROW, command30, run_default;
14751
+ var FAILURES_IN_A_ROW, command32, run_default;
14391
14752
  var init_run = __esm({
14392
14753
  "src/commands/work/run.ts"() {
14393
14754
  "use strict";
@@ -14408,7 +14769,7 @@ var init_run = __esm({
14408
14769
  init_folder2();
14409
14770
  init_stop();
14410
14771
  FAILURES_IN_A_ROW = 3;
14411
- command30 = {
14772
+ command32 = {
14412
14773
  resource: "work",
14413
14774
  action: "run",
14414
14775
  summary: "Run your own coding agent on the waiting work until the queue is empty",
@@ -14731,16 +15092,16 @@ var init_run = __esm({
14731
15092
  return exitCodeFor(reason, totals.rejected > 0 || jobsFailed > 0);
14732
15093
  }
14733
15094
  };
14734
- run_default = command30;
15095
+ run_default = command32;
14735
15096
  }
14736
15097
  });
14737
15098
 
14738
15099
  // src/commands/work/index.ts
14739
- var actions15;
15100
+ var actions16;
14740
15101
  var init_work2 = __esm({
14741
15102
  "src/commands/work/index.ts"() {
14742
15103
  "use strict";
14743
- actions15 = {
15104
+ actions16 = {
14744
15105
  status: () => Promise.resolve().then(() => (init_status2(), status_exports2)).then((m) => m.default),
14745
15106
  pull: () => Promise.resolve().then(() => (init_pull2(), pull_exports2)).then((m) => m.default),
14746
15107
  submit: () => Promise.resolve().then(() => (init_submit(), submit_exports)).then((m) => m.default),
@@ -14764,14 +15125,14 @@ function parseLimit(value) {
14764
15125
  }
14765
15126
  return limit;
14766
15127
  }
14767
- var MAX_LIMIT, command31, list_default2;
15128
+ var MAX_LIMIT, command33, list_default2;
14768
15129
  var init_list2 = __esm({
14769
15130
  "src/commands/workspace/list.ts"() {
14770
15131
  "use strict";
14771
15132
  init_errors();
14772
15133
  init_exit_codes();
14773
15134
  MAX_LIMIT = 200;
14774
- command31 = {
15135
+ command33 = {
14775
15136
  resource: "workspace",
14776
15137
  action: "list",
14777
15138
  summary: "List the workspaces your key can use",
@@ -14799,7 +15160,7 @@ var init_list2 = __esm({
14799
15160
  return ExitCode.Ok;
14800
15161
  }
14801
15162
  };
14802
- list_default2 = command31;
15163
+ list_default2 = command33;
14803
15164
  }
14804
15165
  });
14805
15166
 
@@ -14808,7 +15169,7 @@ var use_exports = {};
14808
15169
  __export(use_exports, {
14809
15170
  default: () => use_default
14810
15171
  });
14811
- var command32, use_default;
15172
+ var command34, use_default;
14812
15173
  var init_use = __esm({
14813
15174
  "src/commands/workspace/use.ts"() {
14814
15175
  "use strict";
@@ -14816,7 +15177,7 @@ var init_use = __esm({
14816
15177
  init_errors();
14817
15178
  init_exit_codes();
14818
15179
  init_http();
14819
- command32 = {
15180
+ command34 = {
14820
15181
  resource: "workspace",
14821
15182
  action: "use",
14822
15183
  summary: "Set the profile's default workspace",
@@ -14873,16 +15234,16 @@ var init_use = __esm({
14873
15234
  return ExitCode.Ok;
14874
15235
  }
14875
15236
  };
14876
- use_default = command32;
15237
+ use_default = command34;
14877
15238
  }
14878
15239
  });
14879
15240
 
14880
15241
  // src/commands/workspace/index.ts
14881
- var actions16;
15242
+ var actions17;
14882
15243
  var init_workspace = __esm({
14883
15244
  "src/commands/workspace/index.ts"() {
14884
15245
  "use strict";
14885
- actions16 = {
15246
+ actions17 = {
14886
15247
  list: () => Promise.resolve().then(() => (init_list2(), list_exports2)).then((m) => m.default),
14887
15248
  use: () => Promise.resolve().then(() => (init_use(), use_exports)).then((m) => m.default)
14888
15249
  };
@@ -14916,6 +15277,7 @@ var init_registry = __esm({
14916
15277
  init_runs2();
14917
15278
  init_skill();
14918
15279
  init_studio2();
15280
+ init_webhooks2();
14919
15281
  init_work2();
14920
15282
  init_workspace();
14921
15283
  handWritten = {
@@ -14935,9 +15297,10 @@ var init_registry = __esm({
14935
15297
  runs: actions12,
14936
15298
  skill: actions13,
14937
15299
  studio: actions14,
15300
+ webhooks: actions15,
14938
15301
  whoami: topLevel("whoami", actions4.status, "kenso auth status"),
14939
- work: actions15,
14940
- workspace: actions16
15302
+ work: actions16,
15303
+ workspace: actions17
14941
15304
  };
14942
15305
  resourceAliases = { leads: "contacts" };
14943
15306
  }
@@ -15074,8 +15437,8 @@ async function renderTopHelp(opts) {
15074
15437
  names.push(withPositionals(spec, spec.action));
15075
15438
  groups.set(hint, names);
15076
15439
  }
15077
- const actions17 = [...groups.entries()].map(([hint, names]) => `${names.join(", ")}${hint}`);
15078
- if (actions17.length > 0) rows.push([resource, actions17.join(", ")]);
15440
+ const actions18 = [...groups.entries()].map(([hint, names]) => `${names.join(", ")}${hint}`);
15441
+ if (actions18.length > 0) rows.push([resource, actions18.join(", ")]);
15079
15442
  }
15080
15443
  const at = 4 + Math.min(22, Math.max(0, ...rows.map(([left]) => left.length)));
15081
15444
  lines.push(
@@ -15088,7 +15451,7 @@ async function renderTopHelp(opts) {
15088
15451
  const [area = "", action = ""] = name.split(" ");
15089
15452
  byArea.set(area, [...byArea.get(area) ?? [], action]);
15090
15453
  }
15091
- const named = [...byArea.entries()].map(([area, actions17]) => `${area} ${actions17.join("|")}`);
15454
+ const named = [...byArea.entries()].map(([area, actions18]) => `${area} ${actions18.join("|")}`);
15092
15455
  lines.push(wrap(`Beta, hidden here but they run (the server decides): ${named.join(", ")}.`, " "));
15093
15456
  }
15094
15457
  const generated = await listGenerated({ features: opts.allCommands ? [] : getFeatures, env: opts.env });
@@ -15096,13 +15459,13 @@ async function renderTopHelp(opts) {
15096
15459
  if (visible.length > 0) {
15097
15460
  const byResource = /* @__PURE__ */ new Map();
15098
15461
  for (const g of visible) {
15099
- const actions17 = byResource.get(g.resource) ?? [];
15100
- actions17.push(`${g.action}${g.beta ? " (beta)" : ""}`);
15101
- byResource.set(g.resource, actions17);
15462
+ const actions18 = byResource.get(g.resource) ?? [];
15463
+ actions18.push(`${g.action}${g.beta ? " (beta)" : ""}`);
15464
+ byResource.set(g.resource, actions18);
15102
15465
  }
15103
15466
  const sorted = [...byResource.entries()].sort(([a], [b]) => a.localeCompare(b));
15104
15467
  if (opts.allCommands) {
15105
- const generatedRows = sorted.map(([resource, actions17]) => [resource, actions17.sort().join(", ")]);
15468
+ const generatedRows = sorted.map(([resource, actions18]) => [resource, actions18.sort().join(", ")]);
15106
15469
  lines.push("", "API resources (kenso <resource> <action>):", columns(generatedRows));
15107
15470
  } else {
15108
15471
  const names = new Set(sorted.map(([resource]) => resource));
@@ -15364,9 +15727,9 @@ function normalizeBooleans(argv, names, strict) {
15364
15727
  async function knownCommands() {
15365
15728
  const commands = /* @__PURE__ */ new Set();
15366
15729
  for (const [resource, area] of Object.entries(handWritten)) {
15367
- const actions17 = Object.keys(area);
15368
- if (actions17.length > 0) commands.add(resource);
15369
- for (const action of actions17) commands.add(action ? `${resource} ${action}` : resource);
15730
+ const actions18 = Object.keys(area);
15731
+ if (actions18.length > 0) commands.add(resource);
15732
+ for (const action of actions18) commands.add(action ? `${resource} ${action}` : resource);
15370
15733
  }
15371
15734
  for (const g of await listGenerated({ features: [] })) {
15372
15735
  commands.add(g.resource);
@@ -15378,7 +15741,8 @@ async function unknownCommand(tokens, resource) {
15378
15741
  const typed = [resource, ...tokens.slice(1)].join(" ");
15379
15742
  const all = await knownCommands();
15380
15743
  const scoped = tokens.length > 1 && all.has(resource) ? [...all].filter((c) => c.startsWith(`${resource} `)) : [...all];
15381
- const best = closest(typed, scoped);
15744
+ const asAction = all.has(resource) ? [] : [...all].filter((c) => c.endsWith(` ${resource}`));
15745
+ const best = asAction.length === 1 ? asAction[0] : closest(typed, scoped);
15382
15746
  const related = all.has(resource) ? [] : [...all].filter((c) => !c.includes(" ") && c !== best && (c.includes(resource) || c.length >= 4 && resource.includes(c))).sort().slice(0, 6);
15383
15747
  const hints = [best ? `did you mean "kenso ${best}"?` : "", related.length ? `Resources named like it: ${related.join(", ")}.` : ""];
15384
15748
  return new KensoError({