@kantadev/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,223 @@
1
+ # @kantadev/cli
2
+
3
+ Terminal (`kanta`) and MCP server (`kanta-mcp`) for **Kanta Verify**, **Kanta
4
+ Find**, and the **Kanta Database**. Thin wrapper over the `api.kanta.dev` and
5
+ `database.kanta.dev` REST APIs — no product logic lives here.
6
+
7
+ - Node 20+, ESM.
8
+ - Design specs: `docs/superpowers/specs/2026-09-04-kanta-cli-mcp-verify-find-admin-design.md`,
9
+ `docs/superpowers/specs/2026-09-04-kanta-database-api-mcp-design.md`
10
+ - Full command reference: [`docs/cli.md`](../docs/cli.md)
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install -g @kantadev/cli
16
+ kanta login # paste your API key from app.kanta.dev
17
+ ```
18
+
19
+ Local/dev:
20
+
21
+ ```bash
22
+ cd kanta-cli
23
+ npm install
24
+ npm link
25
+ ```
26
+
27
+ ## MCP (Claude Desktop / Claude Code / Cursor)
28
+
29
+ ```json
30
+ {
31
+ "mcpServers": {
32
+ "kanta": {
33
+ "command": "npx",
34
+ "args": ["-y", "@kantadev/cli", "kanta-mcp"],
35
+ "env": { "KANTA_API_KEY": "your_key" }
36
+ }
37
+ }
38
+ }
39
+ ```
40
+
41
+ The server calls `GET /me` once at startup to learn the key scope. If the API is
42
+ unreachable it still boots with the customer tool set (admin tools appear once
43
+ `/me` succeeds).
44
+
45
+ ## Auth
46
+
47
+ Key resolution order (first match wins):
48
+
49
+ 1. `--api-key <key>` global flag (never persisted)
50
+ 2. `KANTA_API_KEY` env var (optionally `KANTA_BASE_URL`, `KANTA_DB_URL`)
51
+ 3. `--profile <name>` from `~/.kanta/config.json`
52
+ 4. `default_profile` from `~/.kanta/config.json`
53
+ 5. Error — run `kanta login`
54
+
55
+ The Kanta Database API is a **second base URL**, resolved independently with the
56
+ same key: `--db-url` → `KANTA_DB_URL` → profile `db_base_url` →
57
+ `https://database.kanta.dev/v1`.
58
+
59
+ `~/.kanta/config.json` is written mode `0600`:
60
+
61
+ ```json
62
+ {
63
+ "default_profile": "personal",
64
+ "profiles": {
65
+ "personal": { "key": "kdev_live_…", "base_url": "https://api.kanta.dev", "db_base_url": "https://database.kanta.dev/v1" },
66
+ "admin": { "key": "kdev_live_…", "base_url": "https://api.kanta.dev", "db_base_url": "https://database.kanta.dev/v1" }
67
+ }
68
+ }
69
+ ```
70
+
71
+ ```bash
72
+ kanta login --profile personal # prompts for the key (hidden), validates via GET /me
73
+ kanta whoami
74
+ kanta config show # resolved config, key masked
75
+ kanta logout --profile personal
76
+ ```
77
+
78
+ ## Customer commands
79
+
80
+ ```bash
81
+ kanta verify name@example.com
82
+ kanta verify bulk contacts.csv # CSV needs an "email" column
83
+ kanta find Ada Lovelace analytical.co # synchronous — prints the email (or "no email found")
84
+ kanta find bulk people.csv # CSV needs first_name,last_name,company; prints a job id
85
+ kanta jobs list [--status <s>]
86
+ kanta jobs get <id> [--breakdown]
87
+ kanta jobs results <id> [-o results.csv]
88
+ kanta jobs cancel|resume|delete <id>
89
+ kanta account
90
+ kanta credits
91
+ ```
92
+
93
+ Add `--json` to any command for machine output.
94
+
95
+ ## Kanta Database
96
+
97
+ Search, count, facet, and export the B2B contact database. Search/count/facets
98
+ are free; `export` costs 1 db credit per row delivered (admin keys are not
99
+ charged).
100
+
101
+ ```bash
102
+ kanta db count --seniority c-suite --industry software
103
+ kanta db search --function marketing --has-email --limit 25 [-o people.csv]
104
+ kanta db facets --industry software --field seniority --field person_state
105
+ kanta db lookup --email jane@acme.com
106
+ kanta db lookup --name "Jane Doe" --domain acme.com
107
+
108
+ kanta db export --seniority vp --industry software --max 5000 -o leads.csv
109
+ kanta db exports # your recent export jobs
110
+ kanta db export-status <id>
111
+ kanta db download <id> -o leads.csv
112
+
113
+ kanta db companies count --industry software --employees-min 50
114
+ kanta db companies search --hq-country "United States" --min-contacts 5
115
+ kanta db companies export --industry fintech --max 2000 -o firms.csv
116
+ kanta db company contacts <kanta_org_id> --limit 25
117
+
118
+ kanta --profile admin db ca-count # CCPA California-record monitor (admin)
119
+ ```
120
+
121
+ ### Person filter flags
122
+
123
+ | Flag | Meaning |
124
+ |---|---|
125
+ | `--query <text>` | free text over name / title / company |
126
+ | `--seniority <label…>` | `c-suite`, `vp`, `director`, `manager`, … (case-insensitive) |
127
+ | `--function <name…>` | job function(s) |
128
+ | `--title <text>` | title prefix match |
129
+ | `--title-exact <text…>` | exact normalized title(s) |
130
+ | `--country <name…>` / `--state <name…>` | person location |
131
+ | `--company <text>` | company name prefix |
132
+ | `--company-domain <domain…>` | company domain(s) |
133
+ | `--industry <name…>` | company industry/industries |
134
+ | `--employee-range <range…>` | e.g. `51-200` |
135
+ | `--has-email` / `--has-linkedin` / `--has-phone` | presence filters |
136
+ | `--verification-status <s…>` | admin only (else the API returns 403) |
137
+ | `--filter-file <path>` | raw JSON filter object, merged under the flags |
138
+
139
+ Company flags: `--query`, `--domain`, `--industry`, `--employee-range`,
140
+ `--hq-country`, `--hq-state`, `--funding-stage`, `--employees-min/max`,
141
+ `--revenue-min-k/max-k`, `--founded-after`, `--min-contacts`, `--filter-file`.
142
+
143
+ The `db export` flow prints the match count and credit cost, prompts for
144
+ confirmation (skip with `-y`), submits the job, polls until it finishes, and
145
+ writes the CSV to `-o`. A `confirm_credits_required` response is retried once
146
+ with the API's capped `estimated_max`.
147
+
148
+ ## Admin commands (admin-scoped key only)
149
+
150
+ ```bash
151
+ kanta --profile admin admin credits add --email u@x.com --product find --amount 500 --reason topup
152
+ kanta --profile admin admin jobs list [--status <s>] [--user <email>]
153
+ kanta --profile admin admin user u@x.com
154
+ kanta --profile admin admin verify u@x.com # no credit charge
155
+ kanta --profile admin admin suppress add blocked.com # email vs domain auto-detected by "@"
156
+ kanta --profile admin admin suppress check u@x.com
157
+ ```
158
+
159
+ Every admin command calls `GET /me` first; if the resolving key is not
160
+ `scope: 'admin'` it exits 1 with:
161
+
162
+ ```
163
+ This command requires an admin profile. Active profile "<name>" is a standard key.
164
+ ```
165
+
166
+ ## The admin tag
167
+
168
+ Admin capability is **not** self-service. It requires an `api_keys` row with
169
+ `scope = 'admin'` **and** the owning user having `is_god_mode = true`.
170
+
171
+ 1. Apply `EmailVerifier_V1/infra/api_key_scope_migration.sql` to Supabase.
172
+ 2. Generate a normal key from `app.kanta.dev` for the operator.
173
+ 3. In Supabase Studio → Table Editor → `api_keys`, find that row (match on
174
+ `label` or `last_used_at`) and set `scope` to `admin`. Save.
175
+ 4. `kanta login --profile admin` with that key.
176
+
177
+ Revoke by setting `scope` back to `user`. No API path or dashboard UI reads or
178
+ writes `scope`, so a leaked standard key can never reach `/admin/*`.
179
+
180
+ ## MCP tools
181
+
182
+ See the config block at the top of this file. Admin tools appear in
183
+ `tools/list` **only** when the key is admin-scoped.
184
+
185
+ - Verify / Find / jobs: `kanta_verify_email`, `kanta_verify_bulk`,
186
+ `kanta_find_email`, `kanta_find_bulk`, `kanta_jobs_list`, `kanta_job_get`,
187
+ `kanta_job_results`, `kanta_job_cancel`, `kanta_job_delete`, `kanta_account`,
188
+ `kanta_credits`
189
+ - Database: `kanta_db_count`, `kanta_db_search`, `kanta_db_facets`,
190
+ `kanta_db_lookup`, `kanta_db_export`, `kanta_db_export_status`,
191
+ `kanta_db_companies_count`, `kanta_db_companies_search`,
192
+ `kanta_db_companies_facets`, `kanta_db_company_contacts`
193
+ - Admin: `kanta_admin_credits_add`, `kanta_admin_jobs_list`, `kanta_admin_user`,
194
+ `kanta_admin_verify`, `kanta_admin_suppress_add`, `kanta_admin_suppress_check`,
195
+ `kanta_db_ca_count`
196
+
197
+ `kanta_find_email` is synchronous — it returns `{ email, confidence, method, pattern }`
198
+ inline (or `{ email: null }`) and charges a find credit only on a hit. Bulk tools
199
+ accept either an inline array or a `path` to a CSV and return a `job_id`. Result
200
+ tools cap inline output at 100 rows and otherwise return a sample plus a CLI hint.
201
+ `kanta_db_export` **requires** a `confirm_credits` integer — call
202
+ `kanta_db_count` first, then pass the number of credits you intend to spend; on
203
+ `confirm_credits_required` the tool returns the `estimated_max` to retry with.
204
+
205
+ ## Tests
206
+
207
+ ```bash
208
+ npm test # vitest
209
+ ```
210
+
211
+ ## Layout
212
+
213
+ ```
214
+ kanta-cli/
215
+ ├── bin/kanta.js `kanta` CLI entry
216
+ ├── bin/kanta-mcp.js `kanta-mcp` stdio MCP server entry
217
+ ├── server.json MCP registry manifest
218
+ ├── src/
219
+ │ ├── core/ client.js config.js auth.js identity.js errors.js dbFilter.js
220
+ │ ├── cli/ index.js format.js context.js commands/ (incl. commands/db/)
221
+ │ └── mcp/ server.js register.js tools/ (customer.js admin.js database.js)
222
+ └── tests/ bin.test.js core/ cli/ mcp/
223
+ ```
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // Kanta MCP stdio server entry point (`npx @kanta/cli kanta-mcp`).
3
+ import { startServer } from '../src/mcp/server.js';
4
+
5
+ startServer().catch((err) => {
6
+ process.stderr.write(`kanta-mcp failed to start: ${err?.message || err}\n`);
7
+ process.exit(1);
8
+ });
package/bin/kanta.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../src/cli/index.js';
3
+
4
+ run().catch((err) => {
5
+ process.stderr.write(`Error: ${err?.message || err}\n`);
6
+ process.exit(1);
7
+ });
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@kantadev/cli",
3
+ "version": "0.1.0",
4
+ "description": "Kanta CLI + MCP server — email verification, email finding, and the Kanta B2B contact database from your terminal or an MCP client.",
5
+ "mcpName": "dev.kanta/cli",
6
+ "type": "module",
7
+ "bin": {
8
+ "kanta": "./bin/kanta.js",
9
+ "kanta-mcp": "./bin/kanta-mcp.js"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "src",
14
+ "server.json",
15
+ "README.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
20
+ "exports": {
21
+ ".": "./src/core/client.js",
22
+ "./mcp": "./src/mcp/server.js"
23
+ },
24
+ "scripts": {
25
+ "start": "node bin/kanta.js",
26
+ "mcp": "node bin/kanta-mcp.js",
27
+ "test": "vitest run",
28
+ "test:watch": "vitest"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/griffinkanta/kanta-dev.git",
33
+ "directory": "kanta-cli"
34
+ },
35
+ "homepage": "https://kanta.dev/developers",
36
+ "keywords": [
37
+ "kanta",
38
+ "email-verification",
39
+ "email-finder",
40
+ "b2b-data",
41
+ "mcp",
42
+ "modelcontextprotocol",
43
+ "cli"
44
+ ],
45
+ "license": "MIT",
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "dependencies": {
50
+ "@modelcontextprotocol/sdk": "^1.0.4",
51
+ "commander": "^12.1.0",
52
+ "csv-parse": "^5.5.6",
53
+ "csv-stringify": "^6.5.1"
54
+ },
55
+ "devDependencies": {
56
+ "vitest": "^2.1.8"
57
+ }
58
+ }
package/server.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "dev.kanta/cli",
4
+ "description": "Email verification, email finding, and the Kanta B2B contact database — search, count, facet, and export contacts and companies.",
5
+ "version": "0.1.0",
6
+ "repository": {
7
+ "url": "https://github.com/griffinkanta/kanta-dev",
8
+ "source": "github",
9
+ "subfolder": "kanta-cli"
10
+ },
11
+ "packages": [
12
+ {
13
+ "registryType": "npm",
14
+ "identifier": "@kantadev/cli",
15
+ "version": "0.1.0",
16
+ "runtimeHint": "npx",
17
+ "transport": { "type": "stdio" },
18
+ "environmentVariables": [
19
+ {
20
+ "name": "KANTA_API_KEY",
21
+ "description": "Your Kanta API key from app.kanta.dev",
22
+ "isRequired": true,
23
+ "isSecret": true
24
+ },
25
+ {
26
+ "name": "KANTA_BASE_URL",
27
+ "description": "Override the EmailVerifier (Verify/Find) API base URL",
28
+ "isRequired": false
29
+ },
30
+ {
31
+ "name": "KANTA_DB_URL",
32
+ "description": "Override the Kanta Database API base URL",
33
+ "isRequired": false
34
+ },
35
+ {
36
+ "name": "KANTA_PROFILE",
37
+ "description": "Named profile from ~/.kanta/config.json to use instead of KANTA_API_KEY",
38
+ "isRequired": false
39
+ }
40
+ ]
41
+ }
42
+ ]
43
+ }
@@ -0,0 +1,22 @@
1
+ import { action, getClient, globalOpts } from '../context.js';
2
+ import { printJson, printTable } from '../format.js';
3
+
4
+ export function registerAccount(program) {
5
+ program
6
+ .command('account')
7
+ .description('Show your account and credit balances')
8
+ .action(
9
+ action(async (_opts, cmd) => {
10
+ const client = getClient(cmd);
11
+ const me = await client.getAccount();
12
+ if (globalOpts(cmd).json) return printJson(me);
13
+ printTable([
14
+ { field: 'email', value: me.email },
15
+ { field: 'plan', value: me.plan },
16
+ { field: 'verify credits', value: me.verify_credits },
17
+ { field: 'find credits', value: me.find_credits },
18
+ { field: 'db credits', value: me.db_credits },
19
+ ], [{ key: 'field', label: 'FIELD' }, { key: 'value', label: 'VALUE' }]);
20
+ }),
21
+ );
22
+ }
@@ -0,0 +1,136 @@
1
+ import { action, getClient, globalOpts, requireAdmin, CliExit } from '../../context.js';
2
+ import { printJson, printTable } from '../../format.js';
3
+
4
+ export function registerAdmin(program) {
5
+ const admin = program.command('admin').description('Operator commands (admin-scoped key only)');
6
+
7
+ // ---- credits add ----
8
+ admin
9
+ .command('credits')
10
+ .description('Admin credit operations')
11
+ .command('add')
12
+ .description('Grant credits to a user')
13
+ .requiredOption('--product <product>', 'verify | find | db')
14
+ .requiredOption('--amount <n>', 'number of credits', v => parseInt(v, 10))
15
+ .option('--email <email>', 'target user email')
16
+ .option('--user-id <id>', 'target user id (alternative to --email)')
17
+ .option('--reason <note>', 'free-text note recorded on the ledger entry')
18
+ .action(
19
+ action(async (opts, cmd) => {
20
+ await requireAdmin(cmd);
21
+ if (!opts.email && !opts.userId) throw new CliExit('Provide --email or --user-id.');
22
+ if (!['verify', 'find', 'db'].includes(opts.product)) {
23
+ throw new CliExit('--product must be verify, find, or db.');
24
+ }
25
+ const client = getClient(cmd);
26
+ const res = await client.adminAddCredits({
27
+ email: opts.email,
28
+ userId: opts.userId,
29
+ product: opts.product,
30
+ amount: opts.amount,
31
+ reason: opts.reason,
32
+ });
33
+ if (globalOpts(cmd).json) return printJson(res);
34
+ process.stdout.write(`Granted ${opts.amount} ${opts.product} credits. New balance: ${res.balance}\n`);
35
+ }),
36
+ );
37
+
38
+ // ---- jobs list ----
39
+ admin
40
+ .command('jobs')
41
+ .description('List jobs across all users')
42
+ .command('list')
43
+ .option('--status <status>', 'filter by status')
44
+ .option('--user <email>', 'filter by user email')
45
+ .action(
46
+ action(async (opts, cmd) => {
47
+ await requireAdmin(cmd);
48
+ const client = getClient(cmd);
49
+ const { jobs } = await client.adminListJobs({ status: opts.status, user: opts.user });
50
+ let list = jobs || [];
51
+ if (opts.user) list = list.filter(j => j.user_email === opts.user || j.user_id === opts.user);
52
+ if (globalOpts(cmd).json) return printJson(list);
53
+ printTable(list, [
54
+ { key: 'id', label: 'ID' },
55
+ { key: 'user_id', label: 'USER' },
56
+ { key: 'job_type', label: 'TYPE' },
57
+ { key: 'status', label: 'STATUS' },
58
+ { key: 'completed', label: 'DONE' },
59
+ { key: 'total', label: 'TOTAL' },
60
+ { key: 'filename', label: 'FILE' },
61
+ { key: 'created_at', label: 'CREATED' },
62
+ ]);
63
+ }),
64
+ );
65
+
66
+ // ---- user <email> ----
67
+ admin
68
+ .command('user')
69
+ .description('Show a user account, balances, and last 10 jobs')
70
+ .argument('<email>', 'user email')
71
+ .action(
72
+ action(async (email, _opts, cmd) => {
73
+ await requireAdmin(cmd);
74
+ const client = getClient(cmd);
75
+ const data = await client.adminGetUser({ email });
76
+ if (globalOpts(cmd).json) return printJson(data);
77
+ process.stdout.write(
78
+ `${data.user.email} plan=${data.user.plan} god_mode=${data.user.is_god_mode}\n` +
79
+ `credits: verify=${data.credits.verify} find=${data.credits.find} db=${data.credits.db}\n\n`,
80
+ );
81
+ printTable(data.jobs || [], [
82
+ { key: 'id', label: 'ID' },
83
+ { key: 'job_type', label: 'TYPE' },
84
+ { key: 'status', label: 'STATUS' },
85
+ { key: 'total', label: 'TOTAL' },
86
+ { key: 'created_at', label: 'CREATED' },
87
+ ]);
88
+ }),
89
+ );
90
+
91
+ // ---- verify <email> (no charge) ----
92
+ admin
93
+ .command('verify')
94
+ .description('Verify an email with no credit charge')
95
+ .argument('<email>', 'email address')
96
+ .action(
97
+ action(async (email, _opts, cmd) => {
98
+ await requireAdmin(cmd);
99
+ const client = getClient(cmd);
100
+ const res = await client.adminVerify(email);
101
+ if (globalOpts(cmd).json) return printJson(res);
102
+ process.stdout.write(`${res.email} ${res.status}${res.reason ? ` (${res.reason})` : ''}\n`);
103
+ }),
104
+ );
105
+
106
+ // ---- suppress add / check ----
107
+ const suppress = admin.command('suppress').description('Manage the suppression list');
108
+ suppress
109
+ .command('add')
110
+ .description('Add an email or domain to the suppression list')
111
+ .argument('<value>', 'email or domain (auto-detected by "@")')
112
+ .action(
113
+ action(async (value, _opts, cmd) => {
114
+ await requireAdmin(cmd);
115
+ const client = getClient(cmd);
116
+ const res = await client.adminSuppressAdd(value);
117
+ if (globalOpts(cmd).json) return printJson(res);
118
+ process.stdout.write(`Added ${res.kind}: ${value}\n`);
119
+ }),
120
+ );
121
+ suppress
122
+ .command('check')
123
+ .description('Check whether an email is suppressed')
124
+ .argument('<email>', 'email address')
125
+ .action(
126
+ action(async (email, _opts, cmd) => {
127
+ await requireAdmin(cmd);
128
+ const client = getClient(cmd);
129
+ const res = await client.adminSuppressCheck(email);
130
+ if (globalOpts(cmd).json) return printJson(res);
131
+ process.stdout.write(
132
+ res.suppressed ? `SUPPRESSED (matched on ${res.matched_on})\n` : 'not suppressed\n',
133
+ );
134
+ }),
135
+ );
136
+ }
@@ -0,0 +1,25 @@
1
+ import { action, getClient, globalOpts } from '../context.js';
2
+ import { printJson, printTable } from '../format.js';
3
+
4
+ export function registerCredits(program) {
5
+ program
6
+ .command('credits')
7
+ .description('Show your credit ledger (last 20 entries)')
8
+ .action(
9
+ action(async (_opts, cmd) => {
10
+ const client = getClient(cmd);
11
+ const data = await client.getCredits();
12
+ if (globalOpts(cmd).json) return printJson(data);
13
+ process.stdout.write(
14
+ `verify: ${data.balance} find: ${data.find_balance} db: ${data.db_balance}\n\n`,
15
+ );
16
+ printTable(data.ledger || [], [
17
+ { key: 'created_at', label: 'DATE' },
18
+ { key: 'delta', label: 'DELTA' },
19
+ { key: 'reason', label: 'REASON' },
20
+ { key: 'label', label: 'LABEL' },
21
+ { key: 'balance_after', label: 'BALANCE' },
22
+ ]);
23
+ }),
24
+ );
25
+ }
@@ -0,0 +1,133 @@
1
+ import { action, getClient, globalOpts, rootProgram } from '../../context.js';
2
+ import { printJson, printTable } from '../../format.js';
3
+ import { buildCompanyFilter } from '../../../core/dbFilter.js';
4
+ import { runExportFlow } from './export.js';
5
+ import { personRow, PERSON_TABLE_COLUMNS } from './index.js';
6
+
7
+ function companyFilterOptions(cmd) {
8
+ return cmd
9
+ .option('--query <text>', 'company name (prefix match)')
10
+ .option('--domain <d...>', 'company domain(s)')
11
+ .option('--industry <name...>', 'industry/industries')
12
+ .option('--employee-range <range...>', 'employee range(s)')
13
+ .option('--hq-country <c...>', 'HQ country/countries')
14
+ .option('--hq-state <s...>', 'HQ state(s)')
15
+ .option('--funding-stage <s...>', 'latest funding stage(s)')
16
+ .option('--employees-min <n>', 'minimum employee count')
17
+ .option('--employees-max <n>', 'maximum employee count')
18
+ .option('--revenue-min-k <n>', 'minimum revenue (thousands)')
19
+ .option('--revenue-max-k <n>', 'maximum revenue (thousands)')
20
+ .option('--founded-after <year>', 'founded on/after this year')
21
+ .option('--min-contacts <n>', 'minimum contacts we hold at the company')
22
+ .option('--filter-file <path>', 'raw JSON filter object, merged under the flags');
23
+ }
24
+
25
+ function companyRow(c) {
26
+ return {
27
+ id: c.id ?? '',
28
+ name: c.name ?? '',
29
+ domain: c.domain ?? '',
30
+ industry: c.industry ?? '',
31
+ employee_range: c.employee_range ?? '',
32
+ contacts: c.contact_count ?? c.person_count ?? '',
33
+ };
34
+ }
35
+
36
+ const COMPANY_TABLE = [
37
+ { key: 'id', label: 'ID' },
38
+ { key: 'name', label: 'NAME' },
39
+ { key: 'domain', label: 'DOMAIN' },
40
+ { key: 'industry', label: 'INDUSTRY' },
41
+ { key: 'employee_range', label: 'EMPLOYEES' },
42
+ { key: 'contacts', label: 'CONTACTS' },
43
+ ];
44
+
45
+ export function registerDbCompanies(db) {
46
+ const companies = db
47
+ .command('companies')
48
+ .description('Company (organization) search, count, facets, and export');
49
+
50
+ companyFilterOptions(companies.command('count'))
51
+ .description('Count companies matching a filter (free)')
52
+ .action(
53
+ action(async (opts, cmd) => {
54
+ const client = getClient(cmd);
55
+ const res = await client.companiesCount(buildCompanyFilter(opts));
56
+ if (globalOpts(cmd).json) return printJson(res);
57
+ process.stdout.write(`${Number(res.count || 0).toLocaleString()} companies\n`);
58
+ }),
59
+ );
60
+
61
+ companyFilterOptions(companies.command('search'))
62
+ .description('List companies matching a filter (free)')
63
+ .option('--limit <n>', 'max rows (<=100)', '25')
64
+ .option('--cursor <token>', 'pagination cursor')
65
+ .action(
66
+ action(async (opts, cmd) => {
67
+ const client = getClient(cmd);
68
+ const res = await client.companiesSearch(buildCompanyFilter(opts), {
69
+ limit: parseInt(opts.limit, 10),
70
+ cursor: opts.cursor,
71
+ });
72
+ const rows = res.companies || res.hits || res.records || [];
73
+ if (globalOpts(cmd).json) return printJson(res);
74
+ printTable(rows.map(companyRow), COMPANY_TABLE);
75
+ if (res.next_cursor) process.stdout.write(`\nmore: --cursor ${res.next_cursor}\n`);
76
+ }),
77
+ );
78
+
79
+ companyFilterOptions(companies.command('facets'))
80
+ .description('Term breakdowns for a company segment (free)')
81
+ .requiredOption('--field <name...>', 'facet field(s), max 5')
82
+ .action(
83
+ action(async (opts, cmd) => {
84
+ const client = getClient(cmd);
85
+ const res = await client.companiesFacets(buildCompanyFilter(opts), opts.field);
86
+ const facets = res.facets || res;
87
+ if (globalOpts(cmd).json) return printJson(facets);
88
+ for (const [field, list] of Object.entries(facets)) {
89
+ process.stdout.write(`\n${field}\n`);
90
+ for (const row of list || []) {
91
+ process.stdout.write(` ${String(row.count).padStart(9)} ${row.value}\n`);
92
+ }
93
+ }
94
+ }),
95
+ );
96
+
97
+ companyFilterOptions(companies.command('export'))
98
+ .description('Export matching companies to CSV (prints cost, confirms, polls, downloads)')
99
+ .requiredOption('--max <n>', 'maximum rows to export')
100
+ .requiredOption('-o, --output <file>', 'CSV output path')
101
+ .option('-y, --yes', 'skip the cost confirmation prompt')
102
+ .action(
103
+ action(async (opts, cmd) => {
104
+ const client = getClient(cmd);
105
+ const deps = rootProgram(cmd)._deps;
106
+ await runExportFlow(
107
+ { filter: buildCompanyFilter(opts), kind: 'companies', max: opts.max, output: opts.output, yes: opts.yes },
108
+ client,
109
+ { confirm: deps.confirm, sleep: deps.sleep },
110
+ );
111
+ }),
112
+ );
113
+
114
+ const company = db.command('company').description('Operations on one company');
115
+ company
116
+ .command('contacts <kantaOrgId>')
117
+ .description('List people at one company (free; masked per key scope)')
118
+ .option('--limit <n>', 'max rows (<=100)', '25')
119
+ .option('--cursor <token>', 'pagination cursor')
120
+ .action(
121
+ action(async (id, opts, cmd) => {
122
+ const client = getClient(cmd);
123
+ const res = await client.companyContacts(id, {
124
+ limit: parseInt(opts.limit, 10),
125
+ cursor: opts.cursor,
126
+ });
127
+ const records = res.records || res.hits || [];
128
+ if (globalOpts(cmd).json) return printJson(res);
129
+ printTable(records.map(personRow), PERSON_TABLE_COLUMNS);
130
+ if (res.next_cursor) process.stdout.write(`\nmore: --cursor ${res.next_cursor}\n`);
131
+ }),
132
+ );
133
+ }