Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Changelog

## 0.2.0

### Breaking: `agents` is now GTM agents

`cleanlist agents` now means GTM agents, as in the Cleanlist app. The AI-column
commands moved to `cleanlist smart-agents`, with the same flags:

| 0.1.0 | 0.2.0 |
|---|---|
| `cleanlist agents run <list> --column ... --prompt ...` | `cleanlist smart-agents run <list> --column ... --prompt ...` |
| `cleanlist agents list --list <id>` | `cleanlist smart-agents list --list <id>` |
| `cleanlist agents results <id>` | `cleanlist smart-agents results <id>` |

`agents run` and `agents results`, and the old flags on `agents list`, now exit 2
and name the new command.

**`cleanlist agents list --json` changed shape without an error.** A script that
reads it gets a different JSON document and keeps running. Switch it to
`cleanlist smart-agents list --json` to keep the old output.

Before (0.1.0), an object with smart-agent (AI column) runs:

```json
{
"task_id": "task_9f2c1a",
"timestamp_ms": 1751404800000,
"agent_instructions": null,
"usage": null,
"message": null,
"runs": [
{
"task_id": "run_7c2a91",
"list_id": "9c1f7e2a-4b6d-4f21-9a3e-2b7c8d1e5f04",
"column_name": "Fit Research",
"agent_type": "custom_ai",
"status": "completed",
"total": 100,
"processed": 100,
"failed": 2,
"created_at": "2026-07-01T20:40:00Z"
}
],
"total": 1
}
```

After (0.2.0), a JSON array of GTM agents, newest first (fields abridged):

```json
[
{
"id": "8f0c2d6e-...",
"name": "Inbound follow-up",
"description": null,
"status": "paused",
"playIds": ["..."],
"triggers": [],
"nextRunAt": null,
"lastRunAt": "2026-11-10T14:00:00Z",
"createdAt": "2026-11-01T09:00:00Z",
"modifiedAt": "2026-11-10T14:05:00Z"
}
]
```

### Added

These call the v2 public actions and GTM agent routes. They return 404 until the
Cleanlist API turns them on for your workspace.

- `smart-agents run|list|results`: the AI-column commands, under their new name.
- `agents list|get|create|update|off|runs`: GTM agents. `plays results <run_id>`
shows a run's status and records, with what each step wrote (`--wait` to wait
for it).
- `actions list|run|confirm`: every Clu action your key and plan can use, by group
(`lists`, `agents`, `plays`, `skills`, `sequences`, `crm`). An action that spends,
sends, deletes or writes to a CRM returns a card and runs nothing until
confirmed: `--yes` confirms it, a terminal asks, anything else exits 7 with the
card. `--max-credits` caps it.
- `webhooks list|add|remove`: subscribe a public https URL to events. The signing
secret is shown once.
- `mcp install claude-code|claude-desktop|cursor|codex`: add the Cleanlist MCP
server to an AI app, hosted with sign-in by default or locally with `--api-key`.
It shows the config change and writes it once confirmed.
- Refusals say who can act and where. `person_required` (turning an agent on,
running it now, its limits) says a person does it in the Cleanlist app.
`opt_in_scope_required` names the scope (`lists:delete`, `sequences:write`,
`crm:write`) to tick on the key in Settings → API keys. Both exit 3.

There is no command to turn an agent on, run an agent or play now, or set its
limits: the API leaves those to a person in the Cleanlist app.

### Changed

- Retries: only a GET is retried, up to 3 tries, on 502, 503 or 504 (or when no
response came back). A POST, PATCH or DELETE is sent once and never resent,
since a resent write could run twice. 0.1.0 also retried writes, and 429s; a 429
now exits 6 straight away.
- `mcp install` updates an existing Cleanlist entry in place, never removing it
first, and leaves every other server and setting as it was. For Claude Code it
edits the user config (`~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`)
instead of running `claude mcp remove` then `claude mcp add`. Each config is
written to a temporary file and renamed over the old one, so a failed write
leaves it as it was.
- `--max-credits` must be a number (`1000`); anything else exits 2 instead of
being ignored.

## 0.1.0

First release.
64 changes: 58 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Cleanlist CLI

Find B2B people, enrich CSVs and lead lists with verified work emails and phones,
run AI columns, and export, from your terminal. Built for developers working in
run AI columns, manage GTM agents, and export, from your terminal. Built for developers working in
Claude Code, Cursor and Codex: output is JSON when piped, nothing prompts without
a terminal, and every paid action shows a quote first.

Expand Down Expand Up @@ -45,7 +45,20 @@ cleanlist lists export "Q4 ABM" -o q4.csv
cleanlist lists rows "Q4 ABM" --all --format jsonl

# Fill an AI column on the first 10 rows
cleanlist agents run "Q4 ABM" --column Hook --prompt "One-line opener about {{company}}" --rows 10 --yes --wait
cleanlist smart-agents run "Q4 ABM" --column Hook --prompt "One-line opener about {{company}}" --rows 10 --yes --wait

# GTM agents: list them, read a run's records, turn one off
cleanlist agents list
cleanlist agents runs <agent_id>
cleanlist plays results <run_id> --wait
cleanlist agents off <agent_id>

# Anything Clu can do: list the actions, run one
cleanlist actions list
cleanlist actions run agents.get --args '{"agent_id":"..."}' --json

# Get events at your own URL (the signing secret is shown once)
cleanlist webhooks add https://example.com/hooks/cleanlist --events play_run.completed,reply.received

# Credits and usage
cleanlist credits
Expand All @@ -55,9 +68,25 @@ cleanlist usage --group-by tool
Run `cleanlist --help` for every command and `cleanlist <command> --help` for flags
and examples. Lists can be named by id or exact name.

| Group | Commands |
|---|---|
| Account | `login`, `logout`, `whoami`, `profiles`, `credits`, `credits estimate`, `usage` |
| People | `people search`, `people filters`, `people compile` |
| Enrich | `enrich person`, `enrich company`, `enrich list`, `enrich task`, `enrich csv`, `enrich status` |
| Lists | `lists`, `lists get`, `lists create`, `lists rename`, `lists delete`, `lists rows`, `lists add`, `lists remove`, `lists import`, `lists export` |
| Smart agents (AI columns) | `smart-agents run`, `smart-agents list`, `smart-agents results` |
| GTM agents | `agents list`, `agents get`, `agents create`, `agents update`, `agents off`, `agents runs`, `plays results` |
| Actions (Clu tools) | `actions list`, `actions run`, `actions confirm` |
| Webhooks | `webhooks list`, `webhooks add`, `webhooks remove` |
| Agent setup | `skill`, `mcp install` |

Turning an agent on, running it now and changing its limits are a person's to
do in the Cleanlist app. The API refuses them from code (exit 3,
`person_required`), so the CLI has no command for them.

## Paying for things

Commands that spend credits (`enrich *`, `agents run`) first ask the API for a
Commands that spend credits (`enrich *`, `smart-agents run`) first ask the API for a
signed quote and show it:

- in a terminal, you're asked `Spend 1,240 credits? [y/N]`;
Expand All @@ -69,6 +98,14 @@ signed quote and show it:

Credits are charged exactly as through the API.

`actions run` works the same way with a card instead of a quote: an action that
spends, sends, deletes or writes to a CRM returns a card and runs nothing. `--yes`
(or a yes at the prompt) confirms it; otherwise it exits 7 with the card, and
`cleanlist actions confirm <card_id> --session <session_id>` runs it after the user
approves. Deletes, sends and CRM writes also need the key's opt-in scope
(`lists:delete`, `sequences:write`, `crm:write`), ticked per key in Settings → API
keys; without it they exit 3 with `opt_in_scope_required` and the scope's name.

## Output and exit codes

Tables in a terminal, JSON when piped (`--json`, `--format jsonl|csv` to choose).
Expand All @@ -80,14 +117,18 @@ when piped, with a `fix` hint.
| 0 | OK |
| 1 | Unexpected or server error |
| 2 | Bad input (flags, validation, ambiguous list name) |
| 3 | Not signed in, revoked, or the plan has no API access |
| 3 | Not signed in, revoked, the plan has no API access, or a person must do it (`person_required`, `opt_in_scope_required`) |
| 4 | Not found |
| 5 | Not enough credits, or the quote is above `--max-credits` |
| 6 | Rate limited (after retries) |
| 6 | Rate limited |
| 7 | Confirmation required: re-run with `--yes` once the cost is approved |
| 8 | `--wait` timed out; the job is still running (the error shows how to resume) |

`--wait` polls with backoff and honors `Retry-After`; `--timeout 10m` caps it.
`--wait` polls with backoff; `--timeout 10m` caps it.

Retries: only a GET is retried, up to 3 tries, on 502, 503 or 504 (or no response),
honoring `Retry-After`. A POST, PATCH or DELETE is sent once and never resent, so a
write can't run twice; when one gets no response, check before running it again.

## Coding agents

Expand All @@ -104,6 +145,17 @@ conversation, and branch on exit codes.
The CLI and the [Cleanlist MCP server](https://docs.cleanlist.ai/mcp) work well
together: use the MCP to explore in chat, and the CLI to move data in bulk.

```bash
cleanlist mcp install claude-code # hosted server, sign in from the app
cleanlist mcp install cursor --api-key - # local server with a key (hidden prompt)
cleanlist mcp install claude-desktop
cleanlist mcp install codex
```

`mcp install` shows the change to the app's config file and writes it once you
confirm (`--yes` without a terminal). Running it again updates the existing
Cleanlist entry in place and leaves every other server and setting as it was.

## Environment

| Variable | Use |
Expand Down
33 changes: 27 additions & 6 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ export interface ApiResult<T = any> {
data: T;
}

const RETRYABLE = new Set([429, 502, 503, 504]);
/**
* Only a GET is ever retried, and only on a gateway error (or no response at
* all). A POST, PATCH or DELETE is sent once: there are no idempotency keys
* yet, so a resent write could run twice.
*/
const RETRYABLE = new Set([502, 503, 504]);
const MAX_TRIES = 3;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/** Thin client for the public v2 API. Bodies go out and come back as the API defines them. */
Expand Down Expand Up @@ -61,6 +67,7 @@ export class Api {
if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
}

const retries = method.toUpperCase() === 'GET';
let refreshed = false;
for (let attempt = 0; ; attempt++) {
const token = await this.token(); // outside the try: a missing credential isn't a network error
Expand All @@ -77,11 +84,15 @@ export class Api {
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
});
} catch (e) {
if (attempt < 2) {
if (retries && attempt + 1 < MAX_TRIES) {
await sleep(1000 * 2 ** attempt);
continue;
}
throw new CliError(EXIT.ERROR, `Couldn't reach ${url.origin}: ${(e as Error).message}`);
throw new CliError(
EXIT.ERROR,
`Couldn't reach ${url.origin}: ${(e as Error).message}`,
retries ? undefined : 'It was not resent. The write may still have gone through: check before running it again.',
);
}

const text = await res.text();
Expand All @@ -93,13 +104,14 @@ export class Api {
}
if (res.ok) return { status: res.status, data };

// A stored OAuth token can be revoked or expire early: refresh once.
// A stored OAuth token can be revoked or expire early: refresh once. The
// server refused before doing anything, so this resend is safe for writes too.
if (res.status === 401 && this.cred?.type === 'oauth' && !refreshed) {
refreshed = true;
await this.refresh();
continue;
}
if (RETRYABLE.has(res.status) && attempt < 3) {
if (retries && RETRYABLE.has(res.status) && attempt + 1 < MAX_TRIES) {
const retryAfter = Number(res.headers.get('retry-after')) || data?.error?.retry_after_ms / 1000 || 2 ** attempt;
await sleep(Math.min(retryAfter, 30) * 1000);
continue;
Expand All @@ -109,6 +121,15 @@ export class Api {
}
}

/** Refusals the CLI can't work around: say who can do it, and where. */
const REFUSAL_FIX: Record<string, (env: any) => string> = {
person_required: () => 'Only a person can do this, in the Cleanlist app (or through the MCP, where the app asks them). It cannot be done from the CLI.',
opt_in_scope_required: (env) => {
const scope = env?.details?.required_scope ?? env?.required_scope;
return `This API key needs the ${scope ? `"${scope}"` : 'matching'} scope. In the Cleanlist portal open Settings → API keys, edit this key and tick ${scope ? `"${scope}"` : 'that scope'}, then run it again.`;
},
};

/** Map an API error body (`{error: {code, problem, fix}}` or FastAPI `{detail}`) to a CliError. */
export function toError(status: number, data: any): CliError {
const env = data?.error;
Expand All @@ -124,6 +145,6 @@ export function toError(status: number, data: any): CliError {
(Array.isArray(detail) ? detail.map((d: any) => `${(d.loc ?? []).slice(1).join('.')}: ${d.msg}`).join('; ') : '') ||
`HTTP ${status}`;
const body = typeof data === 'object' && data ? data : { error: { message: String(data) } };
const fix = env?.fix ?? (status === 401 ? 'Run `cleanlist login`, or check CLEANLIST_API_KEY.' : undefined);
const fix = REFUSAL_FIX[env?.code]?.(env) ?? env?.fix ?? (status === 401 ? 'Run `cleanlist login`, or check CLEANLIST_API_KEY.' : undefined);
return new CliError(exitCodeForStatus(status, env?.code), message, fix, body);
}
46 changes: 40 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,30 @@ import { CliError, EXIT } from './errors.js';
import { type Format, print } from './output.js';
import { VERSION } from './version.js';
import { accountCommands } from './commands/account.js';
import { actionCommands } from './commands/actions.js';
import { agentCommands } from './commands/agents.js';
import { enrichCommands } from './commands/enrich.js';
import { listCommands } from './commands/lists.js';
import { mcpCommands } from './commands/mcp.js';
import { peopleCommands } from './commands/people.js';
import { playCommands } from './commands/plays.js';
import { skillCommands } from './commands/skill.js';

const COMMANDS: Command[] = [...accountCommands, ...peopleCommands, ...enrichCommands, ...listCommands, ...agentCommands, ...skillCommands];
import { smartAgentCommands } from './commands/smart-agents.js';
import { webhookCommands } from './commands/webhooks.js';

const COMMANDS: Command[] = [
...accountCommands,
...peopleCommands,
...enrichCommands,
...listCommands,
...smartAgentCommands,
...agentCommands,
...playCommands,
...actionCommands,
...webhookCommands,
...skillCommands,
...mcpCommands,
];

const GLOBAL: Record<string, OptSpec> = {
json: { type: 'boolean', desc: 'Same as --format json.' },
Expand All @@ -35,10 +52,23 @@ const GROUPS: [string, string][] = [
['People', 'people'],
['Enrich', 'enrich'],
['Lists', 'lists'],
['Smart agents', 'agents'],
['Agent setup', 'skill'],
['Smart agents (AI columns)', 'smart-agents'],
['GTM agents', 'agents plays'],
['Actions (Clu tools)', 'actions'],
['Webhooks', 'webhooks'],
['Agent setup', 'skill mcp'],
];

/** 0.2.0 gave `agents` to GTM agents; the AI-column commands kept their flags under `smart-agents`. */
const MOVED = 'AI columns moved to `cleanlist smart-agents run|list|results` in 0.2.0; `agents` is now GTM agents.';
const PERSON_ONLY = 'Turning an agent on and running it now are done by a person in the Cleanlist app, not from the CLI.';
/** `agents <sub>` that no longer exist, or never will from code: say where they went. */
const AGENT_REDIRECTS: Record<string, [string, string]> = {
run: ['There is no `agents run` in 0.2.0.', `For an AI column: \`cleanlist smart-agents run\`. ${PERSON_ONLY}`],
results: ['`agents results` moved.', MOVED],
on: ['`agents on` is not available from the CLI.', PERSON_ONLY],
};

function toParseOptions(specs: Record<string, OptSpec>): any {
return Object.fromEntries(
Object.entries(specs).map(([k, s]) => [k, { type: s.type, ...(s.short ? { short: s.short } : {}), ...(s.multiple ? { multiple: true } : {}) }]),
Expand Down Expand Up @@ -93,7 +123,7 @@ function mainHelp(): string {
const cmds = COMMANDS.filter((c) => names.split(' ').some((n) => c.name === n || c.name.startsWith(n + ' ')));
return `${title}:\n${cmds.map((c) => ` ${c.name.padEnd(22)} ${c.summary}`).join('\n')}`;
});
return `Cleanlist CLI ${VERSION}: find people, enrich CSVs and lists, run smart agents, export.
return `Cleanlist CLI ${VERSION}: find people, enrich CSVs and lists, run smart agents, manage GTM agents, export.

Usage: cleanlist <command> [flags]

Expand Down Expand Up @@ -138,6 +168,8 @@ async function main(argv: string[]): Promise<void> {
const prefix = loose.positionals[1];
return void process.stdout.write(target ? commandHelp(target) : prefix ? groupHelp(prefix) : mainHelp());
}
const redirect = first === 'agents' && !g.help ? AGENT_REDIRECTS[loose.positionals[1]] : undefined;
if (redirect) throw new CliError(EXIT.USAGE, ...redirect);
if (first && COMMANDS.some((c) => c.name.startsWith(first + ' '))) {
process.stdout.write(groupHelp(first));
if (!g.help) process.exit(EXIT.USAGE);
Expand All @@ -158,7 +190,9 @@ async function main(argv: string[]): Promise<void> {
allowPositionals: true,
}).values;
} catch (e) {
throw new CliError(EXIT.USAGE, (e as Error).message.replace(/\. To specify.*$/s, '.'), `Run \`cleanlist ${cmd.name} --help\`.`);
// 0.1.0's `agents list --list X --limit N` was the AI-column list.
const old = cmd.name.startsWith('agents ') && argv.some((a) => /^--(column|prompt|template|rows|all|overwrite|type|list|limit|wait)(=|$)/.test(a));
throw new CliError(EXIT.USAGE, (e as Error).message.replace(/\. To specify.*$/s, '.'), old ? MOVED : `Run \`cleanlist ${cmd.name} --help\`.`);
}
format = values.json ? 'json' : (values.format ?? format);
if (!['table', 'json', 'jsonl', 'csv'].includes(format)) throw new CliError(EXIT.USAGE, `--format must be table, json, jsonl or csv.`);
Expand Down
Loading
Loading