diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..96a50a5 --- /dev/null +++ b/CHANGELOG.md @@ -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 --column ... --prompt ...` | `cleanlist smart-agents run --column ... --prompt ...` | +| `cleanlist agents list --list ` | `cleanlist smart-agents list --list ` | +| `cleanlist agents results ` | `cleanlist smart-agents results ` | + +`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 ` + 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. diff --git a/README.md b/README.md index d4856e1..14a3ef3 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 +cleanlist plays results --wait +cleanlist agents off + +# 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 @@ -55,9 +68,25 @@ cleanlist usage --group-by tool Run `cleanlist --help` for every command and `cleanlist --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]`; @@ -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 --session ` 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). @@ -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 @@ -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 | diff --git a/src/api.ts b/src/api.ts index 7077b6b..fb079c7 100644 --- a/src/api.ts +++ b/src/api.ts @@ -10,7 +10,13 @@ export interface ApiResult { 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. */ @@ -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 @@ -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(); @@ -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; @@ -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> = { + 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; @@ -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); } diff --git a/src/cli.ts b/src/cli.ts index b14604e..c46c699 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -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 = { json: { type: 'boolean', desc: 'Same as --format json.' }, @@ -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 ` that no longer exist, or never will from code: say where they went. */ +const AGENT_REDIRECTS: Record = { + 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): any { return Object.fromEntries( Object.entries(specs).map(([k, s]) => [k, { type: s.type, ...(s.short ? { short: s.short } : {}), ...(s.multiple ? { multiple: true } : {}) }]), @@ -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 [flags] @@ -138,6 +168,8 @@ async function main(argv: string[]): Promise { 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); @@ -158,7 +190,9 @@ async function main(argv: string[]): Promise { 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.`); diff --git a/src/commands/account.ts b/src/commands/account.ts index 7f49593..10c0672 100644 --- a/src/commands/account.ts +++ b/src/commands/account.ts @@ -1,37 +1,9 @@ import { Api } from '../api.js'; import { type Credential, deleteCredential, loadConfig, loadCredential, removeProfile, saveCredential, saveProfile } from '../config.js'; -import { type Command, confirmSpend, DryRun, intOpt, list, readInput, resolveList } from '../context.js'; +import { type Command, confirmSpend, DryRun, intOpt, list, readKey, resolveList } from '../context.js'; import { CliError, EXIT } from '../errors.js'; import { loginDevice, loginLoopback, revoke } from '../oauth.js'; -/** Read one line from the terminal without echoing it. */ -function askSecret(prompt: string): Promise { - process.stderr.write(prompt); - const stdin = process.stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.setEncoding('utf8'); - return new Promise((resolve, reject) => { - let value = ''; - const done = (fn: () => void) => { - stdin.setRawMode(false); - stdin.pause(); - stdin.off('data', onData); - process.stderr.write('\n'); - fn(); - }; - const onData = (chunk: string) => { - for (const ch of chunk) { - if (ch === '\r' || ch === '\n') return done(() => resolve(value.trim())); - if (ch === '\u0003') return done(() => reject(new CliError(EXIT.USAGE, 'Cancelled.'))); - if (ch === '\u007f' || ch === '\b') value = value.slice(0, -1); - else value += ch; - } - }; - stdin.on('data', onData); - }); -} - export const accountCommands: Command[] = [ { name: 'login', @@ -50,8 +22,7 @@ export const accountCommands: Command[] = [ let cred: Credential; const key = ctx.opts['api-key']; if (key) { - // `-`: a hidden prompt in a terminal (ends on Enter), else read the pipe. - const value = key !== '-' ? String(key) : process.stdin.isTTY ? await askSecret('Paste your Cleanlist API key: ') : readInput('-').trim(); + const value = await readKey(key); if (!value.startsWith('clapi_')) throw new CliError(EXIT.USAGE, 'That is not a Cleanlist API key (they start with clapi_).'); cred = { type: 'api_key', key: value }; } else { diff --git a/src/commands/actions.ts b/src/commands/actions.ts new file mode 100644 index 0000000..a9036eb --- /dev/null +++ b/src/commands/actions.ts @@ -0,0 +1,108 @@ +import { ask, type Command, type Ctx, interactive, jsonOpt, maxCredits, requireArg } from '../context.js'; +import { CliError, EXIT } from '../errors.js'; + +const enc = encodeURIComponent; + +interface ActionResult { + action: string; + session_id: string; + kind: 'result' | 'card'; + result?: unknown; + card?: { card_id: string; title: string; summary: string; credits_required: number | null; expires_at: string }; +} + +/** + * An action that ran and failed answers 200 with `{error, message}` as its + * result (a confirm also says `status: failed`). Exit non-zero with it, so a + * script or agent doesn't read a failure as done. + */ +function okOrThrow(data: T, extra: Record = {}): T { + const r = data?.result as { error?: unknown; message?: unknown } | undefined; + const code = r && typeof r === 'object' && r.error ? String(r.error) : undefined; + if (!code && data?.status !== 'failed') return data; + const message = typeof r?.message === 'string' && r.message ? r.message : code ?? 'The action failed.'; + const exit = code === 'insufficient_credits' ? EXIT.CREDITS : code === 'plan_required' ? EXIT.AUTH : EXIT.ERROR; + throw new CliError(exit, message, undefined, { error: { code: code ?? 'action_failed', message }, ...extra, ...data }); +} + +const confirmCard = async (ctx: Ctx, cardId: string, sessionId: string) => + okOrThrow((await ctx.api.post('/api/v2/actions/confirm', { card_id: cardId, session_id: sessionId })).data, { session_id: sessionId }); + +/** + * A card runs nothing until confirmed. Same rules as confirmSpend: over + * --max-credits exits 5; --yes confirms; a TTY asks; otherwise exit 7 with + * the card on stdout and the `actions confirm` command to run after a yes. + */ +async function settleCard(ctx: Ctx, res: ActionResult): Promise { + const card = res.card!; + const cost = card.credits_required; + const line = `${card.title}: ${card.summary}${cost == null ? '' : ` Cost: ${cost.toLocaleString()} credits.`}`; + const max = maxCredits(ctx); + if (max !== undefined && cost != null && cost > max) { + throw new CliError(EXIT.CREDITS, `Card costs ${cost} credits, above --max-credits ${max}. Nothing ran.`, 'Raise --max-credits, or narrow the job.', { card: res }); + } + if (ctx.opts.yes) { + ctx.log(line); + return confirmCard(ctx, card.card_id, res.session_id); + } + if (interactive(ctx.opts)) { + ctx.log(line); + if (await ask('Run it?')) return confirmCard(ctx, card.card_id, res.session_id); + throw new CliError(EXIT.CONFIRM, 'Cancelled. Nothing ran.'); + } + throw new CliError( + EXIT.CONFIRM, + `Confirmation required: ${line}`, + `Show this to the user. After they say yes: cleanlist actions confirm ${card.card_id} --session ${res.session_id}`, + { card: res }, + ); +} + +export const actionCommands: Command[] = [ + { + name: 'actions list', + summary: 'Every Clu action your key and plan can use, with its group and input schema.', + examples: ['cleanlist actions list', `cleanlist actions list --json | jq '.actions[] | select(.group == "lists") | .name'`], + view: { rows: (d) => d.actions, columns: ['name', 'group', 'effect', 'card', 'scope', 'title'] }, + async run(ctx) { + return (await ctx.api.get('/api/v2/actions')).data; + }, + }, + { + name: 'actions run', + args: '', + summary: 'Run one action. One that spends, sends, deletes or writes to a CRM returns a card and runs nothing until confirmed.', + paid: true, + options: { + args: { type: 'string', desc: 'Arguments as a JSON object (see `actions list --json` for each input_schema).' }, + session: { type: 'string', desc: 'session_id from an earlier call, to keep the same conversation.' }, + }, + examples: [ + `cleanlist actions run agents.get --args '{"agent_id":"..."}' --json`, + `cleanlist actions run lists.delete --args '{"list_id":"..."}' # a card: exit 7 until confirmed`, + ], + async run(ctx) { + const name = requireArg(ctx, 'action name, e.g. agents.get', 'actions list'); + if (ctx.opts['dry-run']) throw new CliError(EXIT.USAGE, '--dry-run is not supported here.', 'Run without --yes: an action that spends or sends returns a card and runs nothing.'); + const body = { arguments: jsonOpt(ctx.opts.args, 'args') ?? {}, session_id: ctx.opts.session }; + const { data } = await ctx.api.post(`/api/v2/actions/${enc(name)}`, body); + if (data.kind !== 'card') return okOrThrow(data); + return { action: data.action, session_id: data.session_id, ...((await settleCard(ctx, data)) as object) }; + }, + }, + { + name: 'actions confirm', + args: '', + summary: 'Run a card the user approved. It runs once, with the arguments the server holds.', + options: { session: { type: 'string', desc: 'session_id the card came with (required).' } }, + examples: ['cleanlist actions confirm --session '], + async run(ctx) { + const cardId = requireArg(ctx, 'card_id'); + if (!ctx.opts.session) throw new CliError(EXIT.USAGE, 'Pass --session, the session_id the card came with.'); + if (ctx.opts['dry-run']) throw new CliError(EXIT.USAGE, '--dry-run is not supported here: confirm runs the card.', 'Run it without --dry-run to run the approved card.'); + // The server doesn't show a card's cost at confirm; `actions run` does, and checks the cap there. + if (ctx.opts['max-credits'] !== undefined) throw new CliError(EXIT.USAGE, '--max-credits applies at `actions run`, which shows the card\'s cost. Nothing ran.', 'Run `actions run ... --max-credits N` for a new card with its cost checked, review it, then confirm that card.'); + return confirmCard(ctx, cardId, ctx.opts.session); + }, + }, +]; diff --git a/src/commands/agents.ts b/src/commands/agents.ts index e939cf9..4a7ede7 100644 --- a/src/commands/agents.ts +++ b/src/commands/agents.ts @@ -1,85 +1,93 @@ -import { type Command, type Ctx, confirmSpend, intOpt, isTerminal, poll, resolveList } from '../context.js'; +import { type Command, type Ctx, jsonOpt, requireArg } from '../context.js'; import { CliError, EXIT } from '../errors.js'; const enc = encodeURIComponent; -const TYPES = ['custom_ai', 'cold_intro_email', 'title_normalizer', 'company_intel', 'pain_point_hypothesis']; +const agentId = (ctx: Ctx) => requireArg(ctx, 'agent id', 'agents list'); -function waitForAgent(ctx: Ctx, id: string) { - return poll( - ctx, - async () => (await ctx.api.get(`/api/v2/smart-agents/${enc(id)}`)).data, - (d: any) => isTerminal(d.status), - `cleanlist agents results ${id} --wait`, - (d: any) => `Agent ${d.status}: ${d.progress ?? 0}/${d.total ?? '?'}.`, - ); -} - -const RESULT_VIEW = { rows: (d: any) => d.results, columns: ['lead_id', 'value', 'error'] }; +/** `--schedule null` removes the schedule; anything else must be a JSON object. */ +const schedule = (v: unknown) => (v === 'null' ? null : jsonOpt(v, 'schedule')); +/** + * GTM agents, as in the portal. Turning one on, running it now and setting its + * limits are a person's to do in the Cleanlist app: the API refuses them from + * code (403 person_required), so there is no command for them. + */ export const agentCommands: Command[] = [ { - name: 'agents run', - args: '', - summary: 'Run a smart agent (AI column) over a list. Paid: shows a quote first.', - paid: true, + name: 'agents list', + summary: 'Your GTM agents, newest first.', + examples: ['cleanlist agents list', `cleanlist agents list --json | jq '.[] | {id, name, status}'`], + view: { rows: (d) => d, columns: ['id', 'name', 'status', 'nextRunAt', 'lastRunAt', 'modifiedAt'] }, + async run(ctx) { + return (await ctx.api.get('/api/v2/gtm-agents')).data; + }, + }, + { + name: 'agents get', + args: '', + summary: 'One agent, with its plays and status.', + examples: ['cleanlist agents get --json'], + async run(ctx) { + return (await ctx.api.get(`/api/v2/gtm-agents/${enc(agentId(ctx))}`)).data; + }, + }, + { + name: 'agents create', + summary: 'Create an agent. It starts off, with no play; a person turns it on in Cleanlist.', + options: { + name: { type: 'string', desc: 'Agent name (required).' }, + description: { type: 'string', desc: 'What it is for.' }, + settings: { type: 'string', desc: 'Settings as a JSON object (instructions, skillRefs, knowledge, triggers...). Not limits.' }, + }, + examples: ['cleanlist agents create --name "Inbound follow-up"'], + async run(ctx) { + if (!ctx.opts.name) throw new CliError(EXIT.USAGE, 'Pass --name.'); + const body = { name: ctx.opts.name, description: ctx.opts.description, settings: jsonOpt(ctx.opts.settings, 'settings') }; + return (await ctx.api.post('/api/v2/gtm-agents', body)).data; + }, + }, + { + name: 'agents update', + args: '', + summary: "Change an agent's name, description, settings or schedule. Settings and schedule only change while it is off.", options: { - type: { type: 'string', desc: `Agent: ${TYPES.join(', ')} (default custom_ai).` }, - prompt: { type: 'string', desc: 'Instructions, for custom_ai. Reference fields like {{company}}.' }, - column: { type: 'string', desc: 'Name of the column to write results into.' }, - template: { type: 'string', desc: 'Saved prompt template id.' }, - rows: { type: 'string', desc: 'Only the first N rows.' }, - all: { type: 'boolean', desc: 'Every row in the list.' }, - overwrite: { type: 'boolean', desc: 'Replace existing values in the column.' }, - wait: { type: 'boolean', desc: 'Block until the run finishes.' }, - timeout: { type: 'string', desc: 'Give up waiting after this long (default 30m).' }, + name: { type: 'string', desc: 'New name.' }, + description: { type: 'string', desc: 'New description.' }, + settings: { type: 'string', desc: 'Settings as a JSON object. Not limits: a person sets the budget.' }, + schedule: { type: 'string', desc: 'Schedule as a JSON object (frequency, time, weekday, timezone), or null to remove it.' }, + play: { type: 'string', desc: 'playbook_id of the play to change, when the agent has several.' }, }, - view: RESULT_VIEW, - examples: [ - 'cleanlist agents run "Q4 ABM" --column "Hook" --prompt "One-line opener about {{company}}" --rows 10 --dry-run', - 'cleanlist agents run "Q4 ABM" --type company_intel --column Intel --all --yes --wait', - ], + examples: ['cleanlist agents update --name "Inbound follow-up v2"', `cleanlist agents update --schedule '{"frequency":"daily","time":"09:00"}'`], async run(ctx) { - const type = ctx.opts.type ?? 'custom_ai'; - if (!TYPES.includes(type)) throw new CliError(EXIT.USAGE, `--type must be one of ${TYPES.join(', ')}.`); - if (!ctx.opts.column) throw new CliError(EXIT.USAGE, 'Pass --column, the name of the column to fill.'); - if (type === 'custom_ai' && !ctx.opts.prompt && !ctx.opts.template) throw new CliError(EXIT.USAGE, 'custom_ai needs --prompt or --template.'); - const listId = await resolveList(ctx, ctx.args[0]); - const rows = intOpt(ctx.opts.rows, 'rows'); - const body = { - list_id: listId, - agent_type: type, - column_name: ctx.opts.column, - prompt: ctx.opts.prompt, - template_id: ctx.opts.template, - lead_scope: ctx.opts.all ? 'all' : 'subset', - max_rows: ctx.opts.all ? undefined : rows, - overwrite: Boolean(ctx.opts.overwrite), + const id = agentId(ctx); + const body: Record = { + name: ctx.opts.name, + description: ctx.opts.description, + settings: jsonOpt(ctx.opts.settings, 'settings'), + schedule: ctx.opts.schedule === undefined ? undefined : schedule(ctx.opts.schedule), }; - const q = await confirmSpend(ctx, { tool: 'run_smart_agent', ...body }, `Run ${type}`); - const { data } = await ctx.api.post('/api/v2/smart-agents/run', { ...body, quote_id: q.quote_id }); - return ctx.opts.wait ? waitForAgent(ctx, data.smart_agent_task_id) : data; + if (Object.values(body).every((v) => v === undefined)) throw new CliError(EXIT.USAGE, 'Pass --name, --description, --settings or --schedule.'); + body.playbook_id = ctx.opts.play; + return (await ctx.api.request('PATCH', `/api/v2/gtm-agents/${enc(id)}`, { body })).data; }, }, { - name: 'agents list', - summary: 'Recent smart-agent runs.', - options: { list: { type: 'string', desc: 'Only runs on this list.' }, limit: { type: 'string', desc: 'How many (default 20).' } }, - view: { rows: (d) => d.runs, columns: ['task_id', 'column_name', 'agent_type', 'status', 'processed', 'total', 'created_at'] }, + name: 'agents off', + args: '', + summary: 'Turn an agent off: its triggers and schedule stop. Turning one on is done in Cleanlist.', + examples: ['cleanlist agents off '], async run(ctx) { - const listId = ctx.opts.list ? await resolveList(ctx, ctx.opts.list) : undefined; - return (await ctx.api.get('/api/v2/smart-agents', { list_id: listId, limit: ctx.opts.limit })).data; + return (await ctx.api.post(`/api/v2/gtm-agents/${enc(agentId(ctx))}/status`, { status: 'off' })).data; }, }, { - name: 'agents results', - args: '', - summary: 'Status and output of a smart-agent run.', - options: { wait: { type: 'boolean', desc: 'Block until it finishes.' }, timeout: { type: 'string', desc: 'Default 30m.' } }, - view: RESULT_VIEW, + name: 'agents runs', + args: '', + summary: "An agent's runs, newest first. `plays results ` shows one run's records.", + examples: ['cleanlist agents runs '], + view: { rows: (d) => d, columns: ['id', 'status', 'recordsTotal', 'recordsCompleted', 'recordsFailed', 'creditsUsed', 'createdAt'] }, async run(ctx) { - const id = ctx.args[0]; - if (!id) throw new CliError(EXIT.USAGE, 'Pass the smart_agent_task_id.'); - return ctx.opts.wait ? waitForAgent(ctx, id) : (await ctx.api.get(`/api/v2/smart-agents/${enc(id)}`)).data; + return (await ctx.api.get(`/api/v2/gtm-agents/${enc(agentId(ctx))}/runs`)).data; }, }, ]; diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts new file mode 100644 index 0000000..38213ab --- /dev/null +++ b/src/commands/mcp.ts @@ -0,0 +1,269 @@ +import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { type Command, confirmAction, type Ctx, readKey } from '../context.js'; +import { CliError, EXIT } from '../errors.js'; + +export const MCP_URL = 'https://mcp.cleanlist.ai/v1/mcp'; +/** The stdio server (`cleanlist-mcp` in @cleanlist-ai/mcp), run through npx so there's nothing to install. */ +const STDIO = { command: 'npx', args: ['-y', '--package', '@cleanlist-ai/mcp', 'cleanlist-mcp'] }; +const HOSTS = ['claude-code', 'claude-desktop', 'cursor', 'codex'] as const; +type Host = (typeof HOSTS)[number]; + +export function desktopConfigPath(platform = process.platform, home = homedir(), env = process.env): string { + if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'); + if (platform === 'win32') return join(env.APPDATA || join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json'); + return join(env.XDG_CONFIG_HOME || join(home, '.config'), 'Claude', 'claude_desktop_config.json'); +} + +/** Every API key in `s` cut to its start and end, so a key already in a config doesn't print either. */ +const mask = (s: string) => s.replace(/clapi_[^\s"'\\]+/g, (k) => `${k.slice(0, 10)}…${k.slice(-4)}`); + +/** + * Claude Code's user-scope config, where `claude mcp add --scope user` writes: + * `$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json`. + */ +export function claudeCodeConfigPath(home = homedir(), env = process.env): string { + return join(env.CLAUDE_CONFIG_DIR || home, '.claude.json'); +} + +/** + * `{"mcpServers": {"cleanlist": entry}}` merged into a JSON config: an + * existing cleanlist entry is replaced where it is, every other key and server + * is left as it was. Returns the new text and the entry it replaced. + */ +export function mergeJsonConfig(existing: string | undefined, entry: Record, path: string): { next: string; previous: unknown } { + let cfg: any = {}; + if (existing?.trim()) { + try { + cfg = JSON.parse(existing); + } catch (e) { + throw new CliError(EXIT.USAGE, `${path} is not valid JSON: ${(e as Error).message}`, 'Fix or move that file, then run this again.'); + } + if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new CliError(EXIT.USAGE, `${path} is not a JSON object.`); + } + const previous = cfg.mcpServers?.cleanlist; + cfg.mcpServers = { ...(cfg.mcpServers ?? {}), cleanlist: entry }; + return { next: JSON.stringify(cfg, null, 2) + '\n', previous }; +} + +const tomlString = (s: string) => JSON.stringify(s); // a TOML basic string has JSON's escapes + +const TOML_ESCAPES: Record = { b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', e: '\x1b', '"': '"', '\\': '\\' }; + +/** A quoted TOML key's value, or undefined when it isn't valid (then it's not ours). */ +function tomlBasicString(quoted: string): string | undefined { + try { + return quoted.slice(1, -1).replace(/\\(?:u([0-9A-Fa-f]{4})|U([0-9A-Fa-f]{8})|(.))/g, (_m, u, U, c) => { + if (u || U) return String.fromCodePoint(parseInt(u ?? U, 16)); + if (!(c in TOML_ESCAPES)) throw new Error('bad escape'); + return TOML_ESCAPES[c]; + }); + } catch { + return undefined; + } +} + +/** True for `[mcp_servers.cleanlist]` and its sub-tables, however the header quotes or spaces its keys. */ +function isCleanlistTable(raw: string): boolean { + const parts = (raw.match(/"(?:[^"\\]|\\.)*"|'[^']*'|[^."'\s]+/g) ?? []).map((p) => + p.startsWith('"') ? tomlBasicString(p) : p.startsWith("'") ? p.slice(1, -1) : p + ); + return parts[0] === 'mcp_servers' && parts[1] === 'cleanlist'; +} + +type Multiline = '"""' | "'''" | undefined; + +/** + * The multiline string still open after `line`, given the one open before it. + * Comments, single-line strings and escapes are skipped, so a delimiter inside + * any of them doesn't count. + */ +export function multilineOpenAfter(line: string, open: Multiline): Multiline { + let i = 0; + while (i < line.length) { + if (open) { + if (open === '"""' && line[i] === '\\') i += 2; + else if (line.startsWith(open, i)) { + // Up to two more quotes right before the close belong to the value. + let end = i + 3; + while (end < i + 5 && line[end] === open[0]) end++; + open = undefined; + i = end; + } + else i++; + continue; + } + const c = line[i]; + if (c === '#') break; + if (line.startsWith('"""', i) || line.startsWith("'''", i)) { + open = line.slice(i, i + 3) as Multiline; + i += 3; + } else if (c === '"') { + for (i++; i < line.length && line[i] !== '"'; i += line[i] === '\\' ? 2 : 1); + i++; + } else if (c === "'") { + const end = line.indexOf("'", i + 1); + i = end < 0 ? line.length : end + 1; + } else i++; + } + return open; +} + +/** + * Replace the `[mcp_servers.cleanlist]` table (and its sub-tables) in a Codex + * config.toml where it stands, keeping everything else; append it when there is none. + */ +export function mergeCodexConfig(existing: string | undefined, block: string): string { + const lines = (existing ?? '').split('\n'); + const out: string[] = []; + let skipping = false; + let at = -1; + // The delimiter of a multiline string open at the start of the line: a + // header-shaped line inside one is string content, not a table. + let open: Multiline; + for (const line of lines) { + const header = open ? null : /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/.exec(line); + if (header) skipping = isCleanlistTable(header[1]); + open = multilineOpenAfter(line, open); + if (skipping && at < 0) at = out.length; + if (!skipping) out.push(line); + } + if (at >= 0) { + const tail = out.slice(at).join('\n').replace(/^\n+/, ''); + const head = out.slice(0, at).join('\n').replace(/\n+$/, ''); + return (head ? head + '\n\n' : '') + block + (tail ? '\n' + tail : ''); + } + const kept = out.join('\n').replace(/\n+$/, ''); + return (kept ? kept + '\n\n' : '') + block; +} + +export function codexBlock(key?: string): string { + if (!key) return `[mcp_servers.cleanlist]\nurl = ${tomlString(MCP_URL)}\n`; + return [ + '[mcp_servers.cleanlist]', + `command = ${tomlString(STDIO.command)}`, + `args = [${STDIO.args.map(tomlString).join(', ')}]`, + `env = { CLEANLIST_API_KEY = ${tomlString(key)} }`, + '', + ].join('\n'); +} + +/** A line diff (LCS), enough to show a config change before it's written. */ +export function lineDiff(before: string, after: string): string { + const a = before ? before.replace(/\n$/, '').split('\n') : []; + const b = after.replace(/\n$/, '').split('\n'); + const dp = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]); + const out: string[] = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) out.push(` ${a[i++]}`), j++; + else if (j < b.length && (i >= a.length || dp[i][j + 1] >= dp[i + 1][j])) out.push(`+ ${b[j++]}`); + else out.push(`- ${a[i++]}`); + } + return out.join('\n') + '\n'; +} + +/** Write next to the file and rename over it, so a failed write never leaves a half-written config. */ +function writeConfig(path: string, content: string, key?: string): void { + mkdirSync(dirname(path), { recursive: true }); + const target = existsSync(path) ? realpathSync(path) : path; + const tmp = `${target}.cleanlist-${process.pid}.tmp`; + // A key may be in it: keep the file private to this user. + writeFileSync(tmp, content, { mode: key ? 0o600 : existsSync(target) ? statSync(target).mode & 0o777 : 0o600 }); + renameSync(tmp, target); +} + +const AFTER: Record string> = { + 'claude-code': (key) => (key ? 'Start a new Claude Code session to use it.' : 'In Claude Code, run /mcp and sign in to Cleanlist.'), + cursor: () => 'Restart Cursor (or reload MCP servers) and sign in to Cleanlist when it asks.', + 'claude-desktop': () => 'Restart Claude Desktop.', + codex: (key) => (key ? 'Start a new Codex session.' : 'Run `codex mcp login cleanlist` to sign in.'), +}; + +function configPath(host: Host): string { + if (host === 'claude-code') return claudeCodeConfigPath(); + if (host === 'codex') return join(homedir(), '.codex', 'config.toml'); + return host === 'cursor' ? join(homedir(), '.cursor', 'mcp.json') : desktopConfigPath(); +} + +function jsonEntry(host: Exclude, key: string | undefined): Record { + const stdio = { command: STDIO.command, args: STDIO.args, env: { CLEANLIST_API_KEY: key } }; + if (host === 'claude-code') return key ? { type: 'stdio', ...stdio } : { type: 'http', url: MCP_URL }; + if (key) return stdio; + // Claude Desktop's config file only runs local servers; mcp-remote bridges the hosted one and its sign-in. + return host === 'cursor' ? { url: MCP_URL } : { command: 'npx', args: ['-y', 'mcp-remote', MCP_URL] }; +} + +/** + * Write the server into the app's config file, show the diff, and write it + * once confirmed. An existing Cleanlist entry is updated in place, so there is + * never a moment without one, and a failed write leaves the old one as it was. + */ +async function install(ctx: Ctx, host: Host, key: string | undefined): Promise<{ path: string; changed: boolean }> { + const path = configPath(host); + const exists = existsSync(path); + if (host === 'claude-code' && !exists) { + throw new CliError(EXIT.ERROR, `Claude Code's config (${path}) isn't here.`, 'Install Claude Code and start it once, then run this again.'); + } + const before = exists ? readFileSync(path, 'utf8') : ''; + let next: string; + let diff: string; + if (host === 'codex') { + next = mergeCodexConfig(before, codexBlock(key)); + if (before === next) return unchanged(ctx, path); + diff = lineDiff(before, next); + } else { + const entry = jsonEntry(host, key); + const merged = mergeJsonConfig(before, entry, path); + if (JSON.stringify(merged.previous) === JSON.stringify(entry)) return unchanged(ctx, path); + next = merged.next; + // ~/.claude.json holds all of Claude Code's state: show only the entry. + const show = (v: unknown) => (v === undefined ? '' : JSON.stringify({ cleanlist: v }, null, 2) + '\n'); + diff = host === 'claude-code' ? lineDiff(show(merged.previous), show(entry)) : lineDiff(before, next); + } + ctx.log(`${exists ? 'Changes to' : 'New file'} ${path}:\n${mask(diff)}`); + await confirmAction(ctx, `Write ${path}?`); + // The app may have rewritten it while we waited: writing our copy would drop that. + if ((existsSync(path) ? readFileSync(path, 'utf8') : '') !== before) { + throw new CliError(EXIT.ERROR, `${path} changed while waiting for confirmation. Nothing was written.`, 'Run this again.'); + } + writeConfig(path, next, key); + ctx.log(`Wrote ${path}. ${AFTER[host](key)}`); + return { path, changed: true }; +} + +function unchanged(ctx: Ctx, path: string) { + ctx.log(`${path} already has this Cleanlist server.`); + return { path, changed: false }; +} + +export const mcpCommands: Command[] = [ + { + name: 'mcp install', + args: '', + summary: 'Add the Cleanlist MCP server to an AI app. Hosted with sign-in by default; --api-key runs it locally with a key.', + noAuth: true, + options: { + oauth: { type: 'boolean', desc: 'Use the hosted server and sign in from the app (default).' }, + }, + examples: [ + 'cleanlist mcp install claude-code', + 'cleanlist mcp install cursor --yes', + 'cleanlist mcp install claude-desktop --api-key - # paste the key at a hidden prompt', + 'printenv CLEANLIST_API_KEY | cleanlist mcp install cursor --api-key - --yes', + 'cleanlist mcp install codex', + ], + async run(ctx) { + const host = ctx.args[0] as Host; + if (!HOSTS.includes(host)) throw new CliError(EXIT.USAGE, `Pick the app: ${HOSTS.join(', ')}.`); + if (ctx.opts['api-key'] !== undefined && ctx.opts.oauth) throw new CliError(EXIT.USAGE, 'Pass --api-key or --oauth, not both.'); + const key = ctx.opts['api-key'] === undefined ? undefined : await readKey(ctx.opts['api-key']); + if (key !== undefined && !String(key).startsWith('clapi_')) throw new CliError(EXIT.USAGE, 'That is not a Cleanlist API key (they start with clapi_).'); + const { path, changed } = await install(ctx, host, key); + return { host, mode: key ? 'api_key' : 'oauth', path, installed: true, changed }; + }, + }, +]; diff --git a/src/commands/plays.ts b/src/commands/plays.ts new file mode 100644 index 0000000..7c8adb2 --- /dev/null +++ b/src/commands/plays.ts @@ -0,0 +1,35 @@ +import { type Command, type Ctx, isTerminal, poll, requireArg } from '../context.js'; + +const enc = encodeURIComponent; + +/** Wait for a play run (an agent run is a play run) to finish. */ +function waitForRun(ctx: Ctx, runId: string) { + return poll( + ctx, + async () => (await ctx.api.get(`/api/v2/gtm-runs/${enc(runId)}`)).data, + (d: any) => isTerminal(d.status), + `cleanlist plays results ${runId} --wait`, + (d: any) => `Run ${d.status}.`, + ); +} + +export const playCommands: Command[] = [ + { + name: 'plays results', + args: '', + summary: "Status and records of a play or agent run, with what each step wrote. Runs start in Cleanlist.", + options: { + limit: { type: 'string', desc: 'Records per page (max 500, default 100).' }, + cursor: { type: 'string', desc: "Next page: the last answer's records.nextCursor." }, + wait: { type: 'boolean', desc: 'Block until the run finishes, then print its records.' }, + timeout: { type: 'string', desc: 'Give up waiting after this long (default 30m); exit 8.' }, + }, + examples: ['cleanlist plays results --wait', 'cleanlist plays results --limit 500 --json > run.json'], + async run(ctx) { + const id = requireArg(ctx, 'run_id', 'agents runs '); + const run = ctx.opts.wait ? await waitForRun(ctx, id) : (await ctx.api.get(`/api/v2/gtm-runs/${enc(id)}`)).data; + const records = (await ctx.api.get(`/api/v2/gtm-runs/${enc(id)}/records`, { limit: ctx.opts.limit, cursor: ctx.opts.cursor, include: 'outputs' })).data; + return { run, records }; + }, + }, +]; diff --git a/src/commands/skill.ts b/src/commands/skill.ts index f5f6578..e6cb2a5 100644 --- a/src/commands/skill.ts +++ b/src/commands/skill.ts @@ -18,7 +18,9 @@ ask the user to run \`cleanlist login\` or set CLEANLIST_API_KEY). then save: \`cleanlist lists add "" --from-task \` - Export a list: \`cleanlist lists export "" -o out.csv\` - Read a list: \`cleanlist lists rows "" --all --format jsonl\` -- AI column: \`cleanlist agents run "" --column Hook --prompt "..." --rows 10 --dry-run\` +- AI column: \`cleanlist smart-agents run "" --column Hook --prompt "..." --rows 10 --dry-run\` +- GTM agents: \`cleanlist agents list\`, \`cleanlist agents runs \`, \`cleanlist plays results \` +- Any Clu action: \`cleanlist actions list --json\`, then \`cleanlist actions run --args '{...}'\` - Credits: \`cleanlist credits --json\` ## Rules @@ -34,6 +36,12 @@ ask the user to run \`cleanlist login\` or set CLEANLIST_API_KEY). - Exit codes: 0 ok, 2 bad input, 3 auth/plan, 4 not found, 5 credits, 6 rate limited, 7 needs --yes, 8 still running (the error prints a resume command). - People search has a daily cap per API key: don't loop \`--all\`. +- An action that spends, sends, deletes or writes to a CRM returns a card and + exits 7: show the user the card, and confirm it only after they say yes. +- Exit 3 with \`person_required\` (turning an agent on, running it now, its + limits): only the person can do that, in the Cleanlist app. Don't work around it. + With \`opt_in_scope_required\`, the key needs the named scope ticked in + Settings → API keys. - Lists can be named by id or exact name. - \`cleanlist --help\` lists every flag. `; @@ -65,9 +73,18 @@ export const skillCommands: Command[] = [ } const target = TARGETS[t]; if (!target) throw new CliError(EXIT.USAGE, `--target must be one of ${Object.keys(TARGETS).join(', ')}.`); - if (target.append && existsSync(target.path) && readFileSync(target.path, 'utf8').includes('')) { - ctx.log(`${target.path} already has the Cleanlist section.`); - return { path: target.path, written: false }; + const existing = target.append && existsSync(target.path) ? readFileSync(target.path, 'utf8') : undefined; + const section = /(?:\r?\n)?\r?\n[\s\S]*?(?:\r?\n)?/; + if (existing !== undefined && section.test(existing)) { + // An older CLI's section names old commands: replace it where it stands. + const next = existing.replace(section, () => target.wrap(SKILL_BODY)); + if (next === existing) { + ctx.log(`${target.path} already has the Cleanlist section.`); + return { path: target.path, written: false }; + } + writeFileSync(target.path, next); + ctx.log(`Updated the Cleanlist section in ${target.path}.`); + return { path: target.path, written: true }; } mkdirSync(dirname(target.path), { recursive: true }); (target.append ? appendFileSync : writeFileSync)(target.path, target.wrap(SKILL_BODY)); diff --git a/src/commands/smart-agents.ts b/src/commands/smart-agents.ts new file mode 100644 index 0000000..149b706 --- /dev/null +++ b/src/commands/smart-agents.ts @@ -0,0 +1,87 @@ +import { type Command, type Ctx, confirmSpend, intOpt, isTerminal, poll, resolveList } from '../context.js'; +import { CliError, EXIT } from '../errors.js'; + +const enc = encodeURIComponent; +const TYPES = ['custom_ai', 'cold_intro_email', 'title_normalizer', 'company_intel', 'pain_point_hypothesis']; + +function waitForAgent(ctx: Ctx, id: string) { + return poll( + ctx, + async () => (await ctx.api.get(`/api/v2/smart-agents/${enc(id)}`)).data, + (d: any) => isTerminal(d.status), + `cleanlist smart-agents results ${id} --wait`, + (d: any) => `Agent ${d.status}: ${d.progress ?? 0}/${d.total ?? '?'}.`, + ); +} + +const RESULT_VIEW = { rows: (d: any) => d.results, columns: ['lead_id', 'value', 'error'] }; + +export const smartAgentCommands: Command[] = [ + { + name: 'smart-agents run', + args: '', + summary: 'Run a smart agent (AI column) over a list. Paid: shows a quote first.', + paid: true, + options: { + type: { type: 'string', desc: `Agent: ${TYPES.join(', ')} (default custom_ai).` }, + prompt: { type: 'string', desc: 'Instructions, for custom_ai. Reference fields like {{company}}.' }, + column: { type: 'string', desc: 'Name of the column to write results into.' }, + template: { type: 'string', desc: 'Saved prompt template id.' }, + rows: { type: 'string', desc: 'Only the first N rows.' }, + all: { type: 'boolean', desc: 'Every row in the list.' }, + overwrite: { type: 'boolean', desc: 'Replace existing values in the column.' }, + wait: { type: 'boolean', desc: 'Block until the run finishes.' }, + timeout: { type: 'string', desc: 'Give up waiting after this long (default 30m).' }, + }, + view: RESULT_VIEW, + examples: [ + 'cleanlist smart-agents run "Q4 ABM" --column "Hook" --prompt "One-line opener about {{company}}" --rows 10 --dry-run', + 'cleanlist smart-agents run "Q4 ABM" --type company_intel --column Intel --all --yes --wait', + ], + async run(ctx) { + const type = ctx.opts.type ?? 'custom_ai'; + if (!TYPES.includes(type)) throw new CliError(EXIT.USAGE, `--type must be one of ${TYPES.join(', ')}.`); + if (!ctx.opts.column) throw new CliError(EXIT.USAGE, 'Pass --column, the name of the column to fill.'); + if (type === 'custom_ai' && !ctx.opts.prompt && !ctx.opts.template) throw new CliError(EXIT.USAGE, 'custom_ai needs --prompt or --template.'); + const listId = await resolveList(ctx, ctx.args[0]); + const rows = intOpt(ctx.opts.rows, 'rows'); + const body = { + list_id: listId, + agent_type: type, + column_name: ctx.opts.column, + prompt: ctx.opts.prompt, + template_id: ctx.opts.template, + lead_scope: ctx.opts.all ? 'all' : 'subset', + max_rows: ctx.opts.all ? undefined : rows, + overwrite: Boolean(ctx.opts.overwrite), + }; + const q = await confirmSpend(ctx, { tool: 'run_smart_agent', ...body }, `Run ${type}`); + const { data } = await ctx.api.post('/api/v2/smart-agents/run', { ...body, quote_id: q.quote_id }); + return ctx.opts.wait ? waitForAgent(ctx, data.smart_agent_task_id) : data; + }, + }, + { + name: 'smart-agents list', + summary: 'Recent smart-agent runs.', + examples: ['cleanlist smart-agents list --list "Q4 ABM" --limit 5'], + options: { list: { type: 'string', desc: 'Only runs on this list.' }, limit: { type: 'string', desc: 'How many (default 20).' } }, + view: { rows: (d) => d.runs, columns: ['task_id', 'column_name', 'agent_type', 'status', 'processed', 'total', 'created_at'] }, + async run(ctx) { + const listId = ctx.opts.list ? await resolveList(ctx, ctx.opts.list) : undefined; + return (await ctx.api.get('/api/v2/smart-agents', { list_id: listId, limit: ctx.opts.limit })).data; + }, + }, + { + name: 'smart-agents results', + args: '', + summary: 'Status and output of a smart-agent run.', + examples: ['cleanlist smart-agents results --wait'], + options: { wait: { type: 'boolean', desc: 'Block until it finishes.' }, timeout: { type: 'string', desc: 'Default 30m.' } }, + view: RESULT_VIEW, + async run(ctx) { + const id = ctx.args[0]; + if (!id) throw new CliError(EXIT.USAGE, 'Pass the smart_agent_task_id.'); + return ctx.opts.wait ? waitForAgent(ctx, id) : (await ctx.api.get(`/api/v2/smart-agents/${enc(id)}`)).data; + }, + }, +]; diff --git a/src/commands/webhooks.ts b/src/commands/webhooks.ts new file mode 100644 index 0000000..7fcb1e9 --- /dev/null +++ b/src/commands/webhooks.ts @@ -0,0 +1,43 @@ +import { type Command, confirmAction, list, requireArg } from '../context.js'; +import { CliError, EXIT } from '../errors.js'; + +const enc = encodeURIComponent; +const EVENTS = 'play_run.completed, play_run.failed, approval.needed, reply.received, enrichment.completed, job_change.detected, website_visit.detected'; + +export const webhookCommands: Command[] = [ + { + name: 'webhooks list', + summary: 'Your webhook subscriptions.', + examples: ['cleanlist webhooks list'], + view: { rows: (d) => d.webhooks, columns: ['webhook_id', 'url', 'events', 'created_at'] }, + async run(ctx) { + return (await ctx.api.get('/api/v2/webhooks')).data; + }, + }, + { + name: 'webhooks add', + args: '', + summary: 'Subscribe a public https URL to events. The signing secret is shown once.', + options: { events: { type: 'string', multiple: true, desc: `Events, comma separated: ${EVENTS}.` } }, + examples: ['cleanlist webhooks add https://example.com/hooks/cleanlist --events play_run.completed,reply.received'], + async run(ctx) { + const url = ctx.args[0]; + const events = list(ctx.opts.events); + if (!url || !events) throw new CliError(EXIT.USAGE, 'Pass the https URL and --events.', `Events: ${EVENTS}.`); + const { data } = await ctx.api.post('/api/v2/webhooks', { url, events }); + ctx.log("Save the secret now: it is not shown again. Verify each delivery's Cleanlist-Signature header with it."); + return data; + }, + }, + { + name: 'webhooks remove', + args: '', + summary: 'Stop sending events to a subscription.', + examples: ['cleanlist webhooks remove --yes'], + async run(ctx) { + const id = requireArg(ctx, 'webhook_id', 'webhooks list'); + await confirmAction(ctx, `Remove webhook ${id}?`); + return (await ctx.api.request('DELETE', `/api/v2/webhooks/${enc(id)}`)).data; + }, + }, +]; diff --git a/src/context.ts b/src/context.ts index b7cb812..74a2994 100644 --- a/src/context.ts +++ b/src/context.ts @@ -86,8 +86,8 @@ export async function confirmSpend(ctx: Ctx, estimate: Record, if (!q.sufficient) { throw new CliError(EXIT.CREDITS, `Not enough credits: needs ${q.estimated_cost}, balance ${q.available_credits}.`, 'Buy credits or narrow the job.', { quote: q }); } - const max = ctx.opts['max-credits']; - if (max !== undefined && q.estimated_cost > Number(max)) { + const max = maxCredits(ctx); + if (max !== undefined && q.estimated_cost > max) { throw new CliError(EXIT.CREDITS, `Quote of ${q.estimated_cost} credits is above --max-credits ${max}.`, undefined, { quote: q }); } if (ctx.opts.yes || q.estimated_cost === 0) { @@ -107,6 +107,67 @@ export async function confirmSpend(ctx: Ctx, estimate: Record, ); } +/** Read one line from the terminal without echoing it. */ +function askSecret(prompt: string): Promise { + process.stderr.write(prompt); + const stdin = process.stdin; + stdin.setRawMode(true); + stdin.resume(); + stdin.setEncoding('utf8'); + return new Promise((resolve, reject) => { + let value = ''; + const done = (fn: () => void) => { + stdin.setRawMode(false); + stdin.pause(); + stdin.off('data', onData); + process.stderr.write('\n'); + fn(); + }; + const onData = (chunk: string) => { + for (const ch of chunk) { + if (ch === '\r' || ch === '\n') return done(() => resolve(value.trim())); + if (ch === '\u0003') return done(() => reject(new CliError(EXIT.USAGE, 'Cancelled.'))); + if (ch === '\u007f' || ch === '\b') value = value.slice(0, -1); + else value += ch; + } + }; + stdin.on('data', onData); + }); +} + +/** An API key flag value; `-` is a hidden prompt in a terminal (ends on Enter), else the pipe. */ +export async function readKey(v: unknown): Promise { + return v !== '-' ? String(v) : process.stdin.isTTY ? askSecret('Paste your Cleanlist API key: ') : readInput('-').trim(); +} + +/** --max-credits as a number. Anything else (1,000 or 5k) exits 2 so the cap is never silently off. */ +export function maxCredits(ctx: Ctx): number | undefined { + const v = ctx.opts['max-credits']; + if (v === undefined) return undefined; + if (!/^\d+(\.\d+)?$/.test(String(v).trim())) throw new CliError(EXIT.USAGE, `--max-credits must be a number, like 1000 (got "${v}").`); + return Number(v); +} + +/** A flag holding a JSON object (`--args '{"a":1}'`). */ +export function jsonOpt(v: unknown, name: string): Record | undefined { + if (v === undefined) return undefined; + let parsed: unknown; + try { + parsed = JSON.parse(String(v)); + } catch (e) { + throw new CliError(EXIT.USAGE, `--${name} is not valid JSON: ${(e as Error).message}`); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new CliError(EXIT.USAGE, `--${name} must be a JSON object.`); + return parsed as Record; +} + +/** The first positional argument, or exit 2 naming it and the command that lists them. */ +export function requireArg(ctx: Ctx, what: string, see?: string): string { + const v = ctx.args[0]; + if (!v) throw new CliError(EXIT.USAGE, `Pass the ${what}.`, see ? `See \`cleanlist ${see}\`.` : undefined); + return v; +} + /** Ask before destructive, non-billed actions (delete). Same TTY/--yes rules as confirmSpend. */ export async function confirmAction(ctx: Ctx, question: string): Promise { if (ctx.opts.yes) return; @@ -114,7 +175,7 @@ export async function confirmAction(ctx: Ctx, question: string): Promise { throw new CliError(EXIT.CONFIRM, `Confirmation required: ${question}`, 'Re-run with --yes.'); } -const TERMINAL = new Set(['completed', 'complete', 'succeeded', 'success', 'failed', 'error', 'cancelled', 'canceled', 'partial', 'done']); +const TERMINAL = new Set(['completed', 'completed_with_errors', 'complete', 'succeeded', 'success', 'failed', 'error', 'cancelled', 'canceled', 'partial', 'done']); export const isTerminal = (status?: string) => TERMINAL.has(String(status ?? '').toLowerCase()); /** Duration like 90s, 10m, 1h → ms. */ diff --git a/test/v1.test.mjs b/test/v1.test.mjs new file mode 100644 index 0000000..7f8b43b --- /dev/null +++ b/test/v1.test.mjs @@ -0,0 +1,328 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { Api, toError } from '../dist/api.js'; +import { actionCommands } from '../dist/commands/actions.js'; +import { agentCommands } from '../dist/commands/agents.js'; +import { mergeCodexConfig } from '../dist/commands/mcp.js'; +import { skillCommands, SKILL_BODY } from '../dist/commands/skill.js'; +import { EXIT } from '../dist/errors.js'; + +const cmd = (list, name) => list.find((c) => c.name === name); + +/** A local API answering from `handler`; returns its base URL and a request log. */ +async function server(handler) { + const hits = []; + const srv = createServer((req, res) => { + hits.push(`${req.method} ${req.url}`); + handler(req, res, hits.length); + }); + await new Promise((r) => srv.listen(0, '127.0.0.1', r)); + return { url: `http://127.0.0.1:${srv.address().port}`, hits, close: () => srv.close() }; +} + +const send = (res, status, body) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); +}; +// retry_after_ms keeps the test fast. +const gatewayError = (res, status) => send(res, status, { error: { code: 'upstream', problem: 'Bad gateway', retry_after_ms: 1 } }); + +/** A ctx whose API records every call and answers from `routes` ("METHOD path" → body). */ +function fakeCtx(args, opts, routes) { + const calls = []; + const answer = async (method, path, body) => { + calls.push({ method, path, body }); + const r = routes[`${method} ${path}`]; + if (r === undefined) throw new Error(`unexpected ${method} ${path}`); + if (r instanceof Error) throw r; + return { status: 200, data: r }; + }; + return { + calls, + args, + opts: { 'no-input': true, ...opts }, + log() {}, + api: { get: (p) => answer('GET', p), post: (p, b) => answer('POST', p, b), request: (m, p, o = {}) => answer(m, p, o.body) }, + }; +} + +/** Run the built CLI with no TTY and the given env. */ +async function runCli(args, env = {}) { + const child = spawn(process.execPath, ['dist/cli.js', ...args], { env: { ...process.env, CI: '1', CLEANLIST_API_KEY: 'clapi_test', ...env } }); + child.stdin.end(''); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (d) => (stdout += d)); + child.stderr.on('data', (d) => (stderr += d)); + const code = await new Promise((r) => child.on('close', r)); + return { code, stdout, stderr }; +} + +// Retries: GET only, on 502/503/504 only. + +test('a GET is retried on 502, 503 and 504, then succeeds', async () => { + for (const status of [502, 503, 504]) { + const s = await server((req, res, n) => (n === 1 ? gatewayError(res, status) : send(res, 200, { ok: true }))); + try { + const { data } = await new Api(s.url, { type: 'api_key', key: 'k' }, 'default', false).get('/api/v2/x'); + assert.deepEqual(data, { ok: true }); + assert.deepEqual(s.hits, ['GET /api/v2/x', 'GET /api/v2/x'], `status ${status}`); + } finally { + s.close(); + } + } +}); + +test('a GET stops after 3 tries, and is not retried on 429 or 500', async () => { + const s = await server((req, res) => gatewayError(res, 503)); + try { + await assert.rejects(new Api(s.url, { type: 'api_key', key: 'k' }, 'default', false).get('/api/v2/x'), (e) => e.exitCode === EXIT.ERROR); + assert.equal(s.hits.length, 3); + } finally { + s.close(); + } + for (const status of [429, 500]) { + const t = await server((req, res) => gatewayError(res, status)); + try { + await assert.rejects(new Api(t.url, { type: 'api_key', key: 'k' }, 'default', false).get('/api/v2/x')); + assert.equal(t.hits.length, 1, `status ${status}`); + } finally { + t.close(); + } + } +}); + +test('POST, PATCH, PUT and DELETE are never retried, even on 502/503/504', async () => { + for (const method of ['POST', 'PATCH', 'PUT', 'DELETE']) { + for (const status of [502, 503, 504]) { + const s = await server((req, res) => gatewayError(res, status)); + try { + await assert.rejects(new Api(s.url, { type: 'api_key', key: 'k' }, 'default', false).request(method, '/api/v2/x', { body: {} })); + assert.deepEqual(s.hits, [`${method} /api/v2/x`], `${method} ${status}`); + } finally { + s.close(); + } + } + } +}); + +test('a POST that gets no response is not resent, and says the write may have gone through', async () => { + const s = await server(() => {}); + const url = s.url; + s.close(); // nothing listens: connection refused + await new Promise((r) => setTimeout(r, 20)); + await assert.rejects(new Api(url, { type: 'api_key', key: 'k' }, 'default', false).post('/api/v2/x', {}), (e) => /not resent/.test(e.fix)); +}); + +// mcp install: update in place. + +test('mcp install claude-code updates an existing entry in place, never removing it, and leaves the rest alone', async () => { + const dir = mkdtempSync(join(tmpdir(), 'cl-mcp-')); + const path = join(dir, '.claude.json'); + const original = { + numStartups: 7, + mcpServers: { first: { type: 'stdio', command: 'a' }, cleanlist: { type: 'http', url: 'https://old.example/mcp' }, last: { type: 'http', url: 'https://x' } }, + projects: { '/p': { allowedTools: [] } }, + }; + writeFileSync(path, JSON.stringify(original, null, 2)); + // PATH has no `claude`: the update must not shell out to `claude mcp remove/add`. + const env = { CLAUDE_CONFIG_DIR: dir, HOME: dir, PATH: '/nonexistent' }; + + const first = await runCli(['mcp', 'install', 'claude-code', '--yes', '--json'], env); + assert.equal(first.code, 0, first.stderr); + assert.equal(JSON.parse(first.stdout).changed, true); + const cfg = JSON.parse(readFileSync(path, 'utf8')); + assert.deepEqual(cfg.mcpServers.cleanlist, { type: 'http', url: 'https://mcp.cleanlist.ai/v1/mcp' }); + assert.deepEqual(Object.keys(cfg.mcpServers), ['first', 'cleanlist', 'last']); // same position + assert.deepEqual({ ...cfg, mcpServers: undefined }, { ...original, mcpServers: undefined }); + assert.deepEqual(cfg.mcpServers.first, original.mcpServers.first); + + const again = await runCli(['mcp', 'install', 'claude-code', '--yes', '--json'], env); + assert.equal(JSON.parse(again.stdout).changed, false); + + // Switching to a key rewrites the same entry, privately, and never prints the key. + const key = 'clapi_abcdefghijklmnopqrstuvwxyz'; + const keyed = await runCli(['mcp', 'install', 'claude-code', '--api-key', key, '--yes', '--json'], env); + assert.equal(keyed.code, 0, keyed.stderr); + assert.ok(!keyed.stderr.includes(key)); + const after = JSON.parse(readFileSync(path, 'utf8')); + assert.equal(after.mcpServers.cleanlist.type, 'stdio'); + assert.equal(after.mcpServers.cleanlist.env.CLEANLIST_API_KEY, key); + assert.deepEqual(Object.keys(after.mcpServers), ['first', 'cleanlist', 'last']); + assert.equal(statSync(path).mode & 0o777, 0o600); +}); + +test('mcp install claude-code without --yes and no TTY exits 7 and writes nothing', async () => { + const dir = mkdtempSync(join(tmpdir(), 'cl-mcp-')); + const path = join(dir, '.claude.json'); + writeFileSync(path, '{"mcpServers":{}}'); + const r = await runCli(['mcp', 'install', 'claude-code'], { CLAUDE_CONFIG_DIR: dir, HOME: dir }); + assert.equal(r.code, EXIT.CONFIRM); + assert.equal(readFileSync(path, 'utf8'), '{"mcpServers":{}}'); +}); + +test('mergeCodexConfig replaces the cleanlist table where it stands', () => { + const before = '[a]\nx = 1\n\n[mcp_servers.cleanlist]\nurl = "old"\n\n[mcp_servers.cleanlist.env]\nK = "v"\n\n[z]\ny = 2\n'; + assert.equal(mergeCodexConfig(before, '[mcp_servers.cleanlist]\nurl = "new"\n'), '[a]\nx = 1\n\n[mcp_servers.cleanlist]\nurl = "new"\n\n[z]\ny = 2\n'); + assert.equal(mergeCodexConfig('[a]\nx = 1\n', '[mcp_servers.cleanlist]\nurl = "new"\n'), '[a]\nx = 1\n\n[mcp_servers.cleanlist]\nurl = "new"\n'); +}); + +test('mergeCodexConfig finds the cleanlist table however its header is quoted or spaced', () => { + for (const header of ['[mcp_servers."cleanlist"]', "[ mcp_servers . 'cleanlist' ]", '[mcp_servers."cleanlist".env]']) { + const out = mergeCodexConfig(`${header}\nurl = "old"\n`, '[mcp_servers.cleanlist]\nurl = "new"\n'); + assert.equal(out, '[mcp_servers.cleanlist]\nurl = "new"\n', header); + } + // A header the decoder can't read (or a \\U escape) is someone else's table, kept as it is. + for (const kept of ['[profiles."\\U00000077ork"]\nx = 1\n', '[profiles."\\q"]\nx = 1\n']) { + assert.ok(mergeCodexConfig(kept, '[mcp_servers.cleanlist]\nurl = "new"\n').startsWith(kept), kept); + } + assert.equal(mergeCodexConfig('[mcp_servers."\\u0063leanlist"]\nurl = "old"\n', '[mcp_servers.cleanlist]\nurl = "new"\n'), '[mcp_servers.cleanlist]\nurl = "new"\n'); + // A single quoted key with a dot in it is another table. + const other = '["mcp_servers.cleanlist"]\nx = 1\n'; + assert.ok(mergeCodexConfig(other, '[mcp_servers.cleanlist]\nurl = "new"\n').startsWith(other)); +}); + +// Refusals the CLI can't work around. + +test('person_required and opt_in_scope_required say who can do it and where', () => { + const person = toError(403, { error: { code: 'person_required', problem: 'agents.set_status turns an agent on.', fix: 'server fix' } }); + assert.equal(person.exitCode, EXIT.AUTH); + assert.equal(person.apiCode, 'person_required'); + assert.match(person.fix, /Cleanlist app/); + const scope = toError(403, { error: { code: 'opt_in_scope_required', problem: 'x', details: { required_scope: 'crm:write' } } }); + assert.match(scope.fix, /"crm:write"/); + assert.match(scope.fix, /Settings → API keys/); +}); + +// actions + +const card = { + action: 'lists.delete', + session_id: 'ses_1', + kind: 'card', + card: { card_id: 'crd_1', title: 'Delete list', summary: 'Deletes Q4 ABM.', credits_required: 0, expires_at: '2026-11-12T00:00:00Z' }, +}; +const routes = { 'POST /api/v2/actions/lists.delete': card, 'POST /api/v2/actions/confirm': { card_id: 'crd_1', status: 'done', result: { ok: true } } }; + +test('actions run: a card without --yes and no TTY exits 7 with the card and confirms nothing', async () => { + const ctx = fakeCtx(['lists.delete'], { args: '{"list_id":"l1"}' }, routes); + await assert.rejects(cmd(actionCommands, 'actions run').run(ctx), (e) => e.exitCode === EXIT.CONFIRM && e.detail.card.card.card_id === 'crd_1' && /actions confirm crd_1 --session ses_1/.test(e.fix)); + assert.deepEqual(ctx.calls, [{ method: 'POST', path: '/api/v2/actions/lists.delete', body: { arguments: { list_id: 'l1' }, session_id: undefined } }]); +}); + +test('actions run: --yes confirms the card once, in its session', async () => { + const ctx = fakeCtx(['lists.delete'], { yes: true }, routes); + assert.equal((await cmd(actionCommands, 'actions run').run(ctx)).status, 'done'); + assert.deepEqual(ctx.calls[1], { method: 'POST', path: '/api/v2/actions/confirm', body: { card_id: 'crd_1', session_id: 'ses_1' } }); +}); + +test('actions confirm refuses --dry-run and sends nothing', async () => { + const ctx = fakeCtx(['crd_1'], { session: 'sess_1', 'dry-run': true }, routes); + await assert.rejects(cmd(actionCommands, 'actions confirm').run(ctx), (e) => e.exitCode === EXIT.USAGE); + assert.deepEqual(ctx.calls, []); +}); + +test('actions confirm refuses --max-credits and sends nothing: the cap is checked at actions run', async () => { + const ctx = fakeCtx(['crd_1'], { session: 'sess_1', 'max-credits': '10' }, routes); + await assert.rejects(cmd(actionCommands, 'actions confirm').run(ctx), (e) => e.exitCode === EXIT.USAGE && /actions run/.test(e.message)); + assert.deepEqual(ctx.calls, []); +}); + +test('skill --target agents replaces an older Cleanlist section in AGENTS.md and keeps the rest', async () => { + const dir = mkdtempSync(join(tmpdir(), 'cl-skill-')); + const cwd = process.cwd(); + process.chdir(dir); + try { + writeFileSync('AGENTS.md', '# Mine\n\n\nold: cleanlist agents run\n\n\n## After\n'); + const run = () => cmd(skillCommands, 'skill').run({ opts: { target: 'agents' }, log() {} }); + assert.equal((await run()).written, true); + const after = readFileSync('AGENTS.md', 'utf8'); + assert.ok(after.startsWith('# Mine\n') && after.endsWith('## After\n'), after); + assert.ok(after.includes(SKILL_BODY) && !after.includes('old: cleanlist agents run')); + assert.equal((await run()).written, false, 'a second run changes nothing'); + // The same with CRLF line endings (an AGENTS.md saved on Windows). + writeFileSync('AGENTS.md', '# Mine\r\n\r\n\r\nold: cleanlist agents run\r\n\r\n\r\n## After\r\n'); + assert.equal((await run()).written, true); + const crlf = readFileSync('AGENTS.md', 'utf8'); + assert.ok(!crlf.includes('old: cleanlist agents run') && crlf.split('').length === 2, crlf); + assert.ok(crlf.startsWith('# Mine\r\n') && crlf.endsWith('## After\r\n'), crlf); + assert.equal((await run()).written, false, 'a second CRLF run changes nothing'); + } finally { + process.chdir(cwd); + } +}); + +test('actions run: a person-only card refused at confirm surfaces person_required', async () => { + const refused = toError(403, { error: { code: 'person_required', problem: 'agents.set_status turns an agent on.' } }); + const ctx = fakeCtx(['lists.delete'], { yes: true }, { ...routes, 'POST /api/v2/actions/confirm': refused }); + await assert.rejects(cmd(actionCommands, 'actions run').run(ctx), (e) => e.exitCode === EXIT.AUTH && e.apiCode === 'person_required'); +}); + +// GTM agents + +test('agents off sends status off; agents update PATCHes, and --schedule null removes the schedule', async () => { + const off = fakeCtx(['a1'], {}, { 'POST /api/v2/gtm-agents/a1/status': { id: 'a1', status: 'paused' } }); + await cmd(agentCommands, 'agents off').run(off); + assert.deepEqual(off.calls[0].body, { status: 'off' }); + + const upd = fakeCtx(['a1'], { schedule: 'null' }, { 'PATCH /api/v2/gtm-agents/a1': { id: 'a1' } }); + await cmd(agentCommands, 'agents update').run(upd); + assert.equal(JSON.stringify(upd.calls[0].body), '{"schedule":null}'); + await assert.rejects(cmd(agentCommands, 'agents update').run(fakeCtx(['a1'], {}, {})), (e) => e.exitCode === EXIT.USAGE); +}); + +test('agents list is GTM agents (a JSON array); the AI-column list is smart-agents list', async () => { + const s = await server((req, res) => + req.url.startsWith('/api/v2/gtm-agents') ? send(res, 200, [{ id: 'a1', name: 'Inbound', status: 'paused' }]) : send(res, 200, { runs: [], total: 0 }), + ); + try { + const gtm = await runCli(['agents', 'list', '--json', '--api-url', s.url]); + assert.equal(gtm.code, 0, gtm.stderr); + assert.deepEqual(JSON.parse(gtm.stdout), [{ id: 'a1', name: 'Inbound', status: 'paused' }]); + const ai = await runCli(['smart-agents', 'list', '--json', '--api-url', s.url]); + assert.deepEqual(JSON.parse(ai.stdout), { runs: [], total: 0 }); + assert.deepEqual(s.hits, ['GET /api/v2/gtm-agents', 'GET /api/v2/smart-agents']); + } finally { + s.close(); + } +}); + +test('0.1.0 agent commands exit 2 and point at smart-agents; agents on says a person does it', async () => { + for (const args of [['agents', 'run', 'Q4', '--column', 'Hook'], ['agents', 'results', 't1'], ['agents', 'list', '--list', 'Q4']]) { + const r = await runCli(args); + assert.equal(r.code, EXIT.USAGE, args.join(' ')); + assert.match(JSON.parse(r.stderr).error.fix, /smart-agents/, args.join(' ')); + } + const on = await runCli(['agents', 'on', 'a1']); + assert.equal(on.code, EXIT.USAGE); + assert.match(JSON.parse(on.stderr).error.fix, /Cleanlist app/); +}); + +test('mergeCodexConfig leaves header-shaped text inside multiline strings alone', () => { + const before = '[profiles.work]\nnotes = """\n[mcp_servers.cleanlist]\nkeep me\n"""\nlit = \'\'\'\n[mcp_servers.cleanlist]\n\'\'\'\n\n[mcp_servers.cleanlist]\nurl = "old"\n'; + const after = mergeCodexConfig(before, '[mcp_servers.cleanlist]\nurl = "new"\n'); + assert.ok(after.includes('notes = """\n[mcp_servers.cleanlist]\nkeep me\n"""'), after); + assert.ok(after.includes("lit = '''\n[mcp_servers.cleanlist]\n'''"), after); + assert.ok(after.endsWith('[mcp_servers.cleanlist]\nurl = "new"\n') && !after.includes('url = "old"'), after); +}); + +test('mergeCodexConfig ignores multiline delimiters in comments and single-line strings', () => { + const before = '[mcp_servers.cleanlist]\nurl = "old"\n# Example delimiter: \'\'\'\nquote = "has \\"\\"\\" inside"\nlit = \'has """ inside\'\n[profiles.work]\nmodel = "keep"\n'; + const after = mergeCodexConfig(before, '[mcp_servers.cleanlist]\nurl = "new"\n'); + assert.ok(after.includes('[profiles.work]\nmodel = "keep"'), after); + assert.ok(after.startsWith('[mcp_servers.cleanlist]\nurl = "new"\n') && !after.includes('url = "old"'), after); +}); + +test('mergeCodexConfig counts quotes before a multiline close as part of the value', () => { + for (const args of [`["""x"""", "'''"]`, `['''x'''', '''y''']`, `["""x""""", "z"]`]) { + const before = `[mcp_servers.cleanlist]\ncommand = "old"\nargs = ${args}\n\n[profiles.work]\nmodel = "keep"\n`; + const after = mergeCodexConfig(before, '[mcp_servers.cleanlist]\nurl = "new"\n'); + assert.ok(after.includes('[profiles.work]\nmodel = "keep"'), after); + assert.ok(!after.includes('command = "old"'), after); + } +});