consulti 0.0.1 → 0.2.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/LICENSE +21 -0
- package/README.md +127 -3
- package/dist/auth.js +69 -0
- package/dist/cli.js +50 -0
- package/dist/client.js +166 -0
- package/dist/commands.js +102 -0
- package/dist/config.js +120 -0
- package/dist/context.js +2 -0
- package/dist/errors.js +35 -0
- package/dist/exit-codes.js +31 -0
- package/dist/flags.js +57 -0
- package/dist/generated/endpoints.json +558 -0
- package/dist/index.js +77 -0
- package/dist/manifest.js +19 -0
- package/dist/output.js +41 -0
- package/dist/param.js +1 -0
- package/dist/skill.js +57 -0
- package/package.json +36 -6
- package/index.js +0 -7
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Consulti, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,7 +1,131 @@
|
|
|
1
1
|
# consulti
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Consulti command line. Verify emails, enrich leads, search the B2B and Instagram databases and manage lists from a terminal, a script or a coding agent. It covers the same stable endpoints as the Consulti API and the `consulti-mcp` tools.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Needs Node.js 20 or newer.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i -g consulti
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or run it without installing:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npx consulti --help
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Or use the installer, which checks your Node version and runs the npm install for you. It never uses sudo:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
curl -fsSL https://consulti.ai/install.sh | bash
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Sign in
|
|
26
|
+
|
|
27
|
+
Create a key at https://www.consulti.ai/settings?tab=integrations#api-keys (API access needs a paid plan). Then save it once:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
consulti login
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
It asks for the key with a hidden prompt. The key is stored in `~/.config/consulti/config.json` (or under an absolute `$XDG_CONFIG_HOME`; a relative one is ignored), readable only by you. For CI or one-off shells, set the environment variable instead, typing the key at a hidden prompt so it stays out of your shell history:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
read -rs CONSULTI_API_KEY && export CONSULTI_API_KEY
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`consulti whoami` shows the key prefix in use, `consulti logout` removes the saved key. The CLI never prints a full key.
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
consulti credits
|
|
45
|
+
consulti meta countries
|
|
46
|
+
consulti verify --email jane@example.com
|
|
47
|
+
consulti search --titles CEO --countries "United States" --size 1
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`credits` and `meta` are free. `verify` and `search` spend credits.
|
|
51
|
+
|
|
52
|
+
## Commands
|
|
53
|
+
|
|
54
|
+
Every command is named after an endpoint id. Path parameters are positional, other parameters are flags.
|
|
55
|
+
|
|
56
|
+
| Command | Alias | What it does |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| `verify` | | Verify an email address |
|
|
59
|
+
| `verify-catchall` | | Verify a catch-all mailbox |
|
|
60
|
+
| `credits` | | Show your credit balance (free) |
|
|
61
|
+
| `meta-filter <filter>` | `meta` | List the accepted values for a filter (free) |
|
|
62
|
+
| `enrich` | | Enrich a lead by email |
|
|
63
|
+
| `enrich-linkedin` | | Enrich a lead by LinkedIn URL |
|
|
64
|
+
| `leads-search` | `search` | Search B2B leads |
|
|
65
|
+
| `instagram-search` | | Search Instagram profiles |
|
|
66
|
+
| `lists-get` | `lists` | Get your saved lists (free) |
|
|
67
|
+
| `lists-create` | | Create a list (free) |
|
|
68
|
+
| `lists-add-leads <id>` | | Add leads to a list |
|
|
69
|
+
| `placement-tests-create` | | Create an inbox placement test (1 lead credit, Pro plan or higher) |
|
|
70
|
+
| `placement-tests-sent <id>` | | Start checking a draft placement test (free) |
|
|
71
|
+
| `placement-tests-get <id>` | | Get a placement test (free) |
|
|
72
|
+
| `placement-tests-list` | | List your placement tests (free) |
|
|
73
|
+
|
|
74
|
+
Also: `consulti login`, `consulti logout`, `consulti whoami`, `consulti skill`, `--version` and `--help`. Run `consulti <command> --help` for the flags of one command.
|
|
75
|
+
|
|
76
|
+
Flags:
|
|
77
|
+
|
|
78
|
+
- List flags take repeated values or a comma-separated list: `--titles CEO,CTO` or `--titles CEO --titles CTO`.
|
|
79
|
+
- Boolean flags are `--flag` and `--no-flag`.
|
|
80
|
+
- On `placement-tests-create` the email body flag is `--email-body`, because `--body` already means the full JSON request body.
|
|
81
|
+
- camelCase and snake_case parameters become kebab-case flags (`businessIds` is `--business-ids`, `linkedin_url` is `--linkedin-url`).
|
|
82
|
+
- `--body <json|@file|->` sends a full JSON body on POST commands. Explicit flags override keys in the body. GET commands (`credits`, `meta`, `lists`) take no `--body`.
|
|
83
|
+
- Use `--body` for a list value that itself contains a comma. Empty list values are an error (exit 2), numbers must be plain decimals, and an empty, `.` or `..` path argument is exit 2.
|
|
84
|
+
|
|
85
|
+
## Output
|
|
86
|
+
|
|
87
|
+
JSON goes to stdout, pretty-printed in a terminal and compact when piped. `--jsonl` on `search` and `instagram-search` prints one result per line. If a response carries a warning, a `{"warning": ...}` line goes to stderr, and a `{"meta": {credits_used, has_more, total}}` line follows, so read stderr too. A search warning means do not repeat the search.
|
|
88
|
+
|
|
89
|
+
Errors go to stderr as one JSON object:
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
{"error":"...","code":"...","status":402,"retry_after":null,"credits_used":0,"hint":"..."}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Exit codes
|
|
96
|
+
|
|
97
|
+
| Code | Meaning |
|
|
98
|
+
|---|---|
|
|
99
|
+
| 0 | Success. |
|
|
100
|
+
| 1 | Unexpected error, including HTTP 404 and any 5xx other than 502, 503 and 504. On a billable command, run `consulti credits` before retrying. |
|
|
101
|
+
| 2 | Usage or validation: a missing or bad flag, a bad path argument, or HTTP 400 or 422 from the API. |
|
|
102
|
+
| 3 | Auth: no key, a malformed key (code `invalid_key_format`, from `CONSULTI_API_KEY`, the saved file or `consulti login`), or HTTP 401. |
|
|
103
|
+
| 4 | Plan or credits: HTTP 402, or a 403 with a JSON body. |
|
|
104
|
+
| 5 | Rate limited, unavailable or blocked: HTTP 429 or 503 (`retry_after` is set when the server sends one), or a 403 or 429 with a non-JSON body, which means the request was blocked before it reached the API (code `blocked`). |
|
|
105
|
+
| 6 | Network error or timeout, including a 502 or 504 with a non-JSON body (code `gateway_timeout`). On a billable command, run `consulti credits` before retrying. |
|
|
106
|
+
|
|
107
|
+
## Billing
|
|
108
|
+
|
|
109
|
+
The CLI never retries. A retried search or verification is billed again. If a request ends with exit code 6 (timeout or dropped connection), it may still have been charged: run `consulti credits` before you try again. Any other 5xx on a billable command (for example a JSON 500 `refund_unconfirmed`) is exit 1 with the same advice. Searches wait up to 130 seconds, everything else 310.
|
|
110
|
+
|
|
111
|
+
## For coding agents
|
|
112
|
+
|
|
113
|
+
Paste this into your `AGENTS.md` or `CLAUDE.md`:
|
|
114
|
+
|
|
115
|
+
```markdown
|
|
116
|
+
## Consulti CLI
|
|
117
|
+
|
|
118
|
+
- Use the `consulti` command for lead data. The key is set up by the user with `consulti login` (or `CONSULTI_API_KEY`); never put a key in a command and never print it.
|
|
119
|
+
- Free calls: `consulti credits`, `consulti meta <filter>`, `consulti lists`.
|
|
120
|
+
- Check filter values with `consulti meta <filter>` before searching.
|
|
121
|
+
- Preview with `consulti search ... --size 3` and confirm the credit cost with the user before a larger run.
|
|
122
|
+
- Never retry a failed paid call. On exit code 6, run `consulti credits` first.
|
|
123
|
+
- Errors are JSON on stderr; the exit code says what class of failure it was.
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`consulti skill` prints a short SKILL.md for the CLI that an agent can save into its skills folder.
|
|
127
|
+
|
|
128
|
+
## Settings
|
|
129
|
+
|
|
130
|
+
- `CONSULTI_API_KEY`: your API key.
|
|
131
|
+
- `CONSULTI_BASE_URL`: override the API URL (https only, except localhost and 127.0.0.1).
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { call } from "./client.js";
|
|
2
|
+
import { KEY_FORMAT, configPath, deleteKeyFile, keyPrefix, requireKey, resolveBaseUrl, saveKey } from "./config.js";
|
|
3
|
+
import { SETTINGS_URL } from "./context.js";
|
|
4
|
+
import { CliError } from "./errors.js";
|
|
5
|
+
import { EXIT } from "./exit-codes.js";
|
|
6
|
+
import { DEFAULT_TIMEOUT_MS } from "./manifest.js";
|
|
7
|
+
import { printJson } from "./output.js";
|
|
8
|
+
function checkCredits(ctx, key) {
|
|
9
|
+
return call(ctx, { method: "GET", path: "/credits", key, timeoutMs: DEFAULT_TIMEOUT_MS, billable: false });
|
|
10
|
+
}
|
|
11
|
+
async function login(ctx) {
|
|
12
|
+
let key;
|
|
13
|
+
if (ctx.io.inIsTTY) {
|
|
14
|
+
ctx.io.err(`Create or copy your API key at:\n ${SETTINGS_URL}\n`);
|
|
15
|
+
ctx.io.openUrl(SETTINGS_URL);
|
|
16
|
+
key = (await ctx.io.readSecret("Paste your API key (input is hidden): ")).trim();
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
key = ((await ctx.io.readStdin()).split(/\r?\n/)[0] ?? "").trim();
|
|
20
|
+
}
|
|
21
|
+
if (!KEY_FORMAT.test(key)) {
|
|
22
|
+
throw new CliError({
|
|
23
|
+
exit: EXIT.auth,
|
|
24
|
+
error: "That does not look like a Consulti API key (expected capi_ followed by 64 hex characters).",
|
|
25
|
+
code: "invalid_key_format",
|
|
26
|
+
hint: `Create a key at ${SETTINGS_URL}`,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
await checkCredits(ctx, key);
|
|
30
|
+
const file = saveKey(ctx, key);
|
|
31
|
+
const note = ctx.env.CONSULTI_API_KEY?.trim()
|
|
32
|
+
? "CONSULTI_API_KEY is set and takes precedence over the saved key."
|
|
33
|
+
: undefined;
|
|
34
|
+
printJson(ctx, { logged_in: true, key_prefix: keyPrefix(key), config_file: file, ...(note && { note }) });
|
|
35
|
+
}
|
|
36
|
+
function logout(ctx) {
|
|
37
|
+
const removed = deleteKeyFile(ctx);
|
|
38
|
+
printJson(ctx, {
|
|
39
|
+
logged_out: true,
|
|
40
|
+
removed_config_file: removed,
|
|
41
|
+
note: `The key stays active until you revoke it at ${SETTINGS_URL}`,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
async function whoami(ctx) {
|
|
45
|
+
const { key, source } = requireKey(ctx);
|
|
46
|
+
const res = await checkCredits(ctx, key);
|
|
47
|
+
const data = (res.data ?? {});
|
|
48
|
+
printJson(ctx, {
|
|
49
|
+
key_prefix: keyPrefix(key),
|
|
50
|
+
key_source: source === "env" ? "CONSULTI_API_KEY" : configPath(ctx),
|
|
51
|
+
base_url: resolveBaseUrl(ctx),
|
|
52
|
+
lead_credits: data.lead_credits ?? null,
|
|
53
|
+
verification_credits: data.verification_credits ?? null,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
export function registerAuth(program, ctx) {
|
|
57
|
+
program
|
|
58
|
+
.command("login")
|
|
59
|
+
.description(`Save your API key. Opens ${SETTINGS_URL} on a terminal; off a terminal, reads the key from one line of stdin.`)
|
|
60
|
+
.action(() => login(ctx));
|
|
61
|
+
program
|
|
62
|
+
.command("logout")
|
|
63
|
+
.description("Delete the saved key file. The key itself stays active until you revoke it in Settings.")
|
|
64
|
+
.action(() => logout(ctx));
|
|
65
|
+
program
|
|
66
|
+
.command("whoami")
|
|
67
|
+
.description("Show the key prefix, base URL and spendable credits.")
|
|
68
|
+
.action(() => whoami(ctx));
|
|
69
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { Command, CommanderError } from "commander";
|
|
3
|
+
import { registerAuth } from "./auth.js";
|
|
4
|
+
import { registerEndpoints } from "./commands.js";
|
|
5
|
+
import { CliError } from "./errors.js";
|
|
6
|
+
import { EXIT, EXIT_TABLE } from "./exit-codes.js";
|
|
7
|
+
import { loadManifest } from "./manifest.js";
|
|
8
|
+
import { printError } from "./output.js";
|
|
9
|
+
import { registerSkill } from "./skill.js";
|
|
10
|
+
export function packageVersion() {
|
|
11
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
12
|
+
return pkg.version;
|
|
13
|
+
}
|
|
14
|
+
/** Runs one invocation and returns the exit code. Never calls process.exit. */
|
|
15
|
+
export async function run(argv, ctx) {
|
|
16
|
+
const endpoints = loadManifest();
|
|
17
|
+
const program = new Command("consulti");
|
|
18
|
+
program
|
|
19
|
+
.description("Command-line client for the Consulti.ai API. JSON on stdout, errors as JSON on stderr.")
|
|
20
|
+
.version(ctx.version, "-v, --version", "Print the CLI version.")
|
|
21
|
+
.exitOverride()
|
|
22
|
+
.configureOutput({
|
|
23
|
+
writeOut: (s) => ctx.io.out(s),
|
|
24
|
+
writeErr: (s) => ctx.io.err(s),
|
|
25
|
+
outputError: () => { },
|
|
26
|
+
})
|
|
27
|
+
.addHelpText("after", `\nExit codes:\n${EXIT_TABLE.map(([c, m]) => ` ${c} ${m}`).join("\n")}\n\nAuth: set CONSULTI_API_KEY or run \`consulti login\`.\nThe CLI never retries; a retried billable call bills again.`);
|
|
28
|
+
registerEndpoints(program, ctx, endpoints);
|
|
29
|
+
registerAuth(program, ctx);
|
|
30
|
+
registerSkill(program, ctx, endpoints);
|
|
31
|
+
try {
|
|
32
|
+
await program.parseAsync(argv.length === 0 ? ["--help"] : argv, { from: "user" });
|
|
33
|
+
return EXIT.ok;
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
if (e instanceof CommanderError) {
|
|
37
|
+
if (e.exitCode === 0)
|
|
38
|
+
return EXIT.ok;
|
|
39
|
+
const message = e.message.replace(/^error: /, "");
|
|
40
|
+
printError(ctx, new CliError({ exit: EXIT.usage, error: message, code: "usage" }));
|
|
41
|
+
return EXIT.usage;
|
|
42
|
+
}
|
|
43
|
+
if (e instanceof CliError) {
|
|
44
|
+
printError(ctx, e);
|
|
45
|
+
return e.exit;
|
|
46
|
+
}
|
|
47
|
+
printError(ctx, new CliError({ exit: EXIT.unexpected, error: e instanceof Error ? e.message : String(e), code: "unexpected" }));
|
|
48
|
+
return EXIT.unexpected;
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { resolveBaseUrl } from "./config.js";
|
|
2
|
+
import { CliError } from "./errors.js";
|
|
3
|
+
import { EXIT, exitForStatus } from "./exit-codes.js";
|
|
4
|
+
const BILLED_HINT = "The request may still have been billed. Run consulti credits before retrying.";
|
|
5
|
+
/** Removes secrets (the key, the query string) from a message built from an exception. */
|
|
6
|
+
function scrub(message, secrets) {
|
|
7
|
+
let out = message;
|
|
8
|
+
for (const secret of secrets) {
|
|
9
|
+
if (secret && secret.length > 1)
|
|
10
|
+
out = out.split(secret).join("[redacted]");
|
|
11
|
+
}
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
function appendQuery(url, query) {
|
|
15
|
+
for (const [name, value] of Object.entries(query)) {
|
|
16
|
+
if (value === undefined || value === null)
|
|
17
|
+
continue;
|
|
18
|
+
if (Array.isArray(value)) {
|
|
19
|
+
for (const item of value)
|
|
20
|
+
url.searchParams.append(name, String(item));
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
url.searchParams.set(name, String(value));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function parseRetryAfter(header, body) {
|
|
28
|
+
if (header) {
|
|
29
|
+
const secs = Number(header);
|
|
30
|
+
if (Number.isFinite(secs) && secs >= 0)
|
|
31
|
+
return secs;
|
|
32
|
+
const date = Date.parse(header);
|
|
33
|
+
if (!Number.isNaN(date))
|
|
34
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
35
|
+
}
|
|
36
|
+
for (const field of ["retry_after", "retryAfter", "retry_after_seconds"]) {
|
|
37
|
+
const v = body?.[field];
|
|
38
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
39
|
+
return v;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
function asObject(text) {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(text);
|
|
46
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
|
|
47
|
+
? parsed
|
|
48
|
+
: undefined;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function str(v) {
|
|
55
|
+
return typeof v === "string" && v.length > 0 ? v : null;
|
|
56
|
+
}
|
|
57
|
+
function httpError(res, text, billable) {
|
|
58
|
+
const status = res.status;
|
|
59
|
+
const body = asObject(text);
|
|
60
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"), body);
|
|
61
|
+
const billedHint = billable && status >= 500 && status !== 503 ? BILLED_HINT : null;
|
|
62
|
+
if (!body) {
|
|
63
|
+
// An edge bot challenge or gateway page: HTML (or empty), never the API's JSON.
|
|
64
|
+
if (status === 502 || status === 504) {
|
|
65
|
+
// The platform cut the function off, so the route's refund may not have run.
|
|
66
|
+
return new CliError({
|
|
67
|
+
exit: EXIT.network,
|
|
68
|
+
error: `The gateway answered HTTP ${status} with a non-JSON body; the request may have been cut off mid-flight.`,
|
|
69
|
+
code: "gateway_timeout",
|
|
70
|
+
status,
|
|
71
|
+
retryAfter,
|
|
72
|
+
hint: billedHint,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
if (status === 403) {
|
|
76
|
+
return new CliError({
|
|
77
|
+
exit: EXIT.unavailable,
|
|
78
|
+
error: "The request was blocked before reaching the API (an edge firewall answered instead).",
|
|
79
|
+
code: "blocked",
|
|
80
|
+
status,
|
|
81
|
+
hint: "Contact support if this persists.",
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (status === 429) {
|
|
85
|
+
return new CliError({
|
|
86
|
+
exit: EXIT.unavailable,
|
|
87
|
+
error: "The request was blocked before reaching the API (an edge challenge answered instead). Wait a moment and retry.",
|
|
88
|
+
code: "blocked",
|
|
89
|
+
status,
|
|
90
|
+
retryAfter,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return new CliError({
|
|
94
|
+
exit: exitForStatus(status),
|
|
95
|
+
error: `The server answered HTTP ${status} with a non-JSON body.`,
|
|
96
|
+
status,
|
|
97
|
+
retryAfter,
|
|
98
|
+
hint: billedHint,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
const extra = {};
|
|
102
|
+
if (body.field !== undefined)
|
|
103
|
+
extra.field = body.field;
|
|
104
|
+
if (body.invalid_values !== undefined)
|
|
105
|
+
extra.invalid_values = body.invalid_values;
|
|
106
|
+
return new CliError({
|
|
107
|
+
exit: exitForStatus(status),
|
|
108
|
+
error: str(body.error) ?? str(body.message) ?? `HTTP ${status}`,
|
|
109
|
+
code: str(body.code),
|
|
110
|
+
status,
|
|
111
|
+
retryAfter,
|
|
112
|
+
creditsUsed: typeof body.credits_used === "number" ? body.credits_used : null,
|
|
113
|
+
hint: billedHint ? [str(body.hint), billedHint].filter(Boolean).join(" ") : str(body.hint),
|
|
114
|
+
extra,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** One request, no retry. Returns the parsed JSON body on 2xx; throws CliError otherwise. */
|
|
118
|
+
export async function call(ctx, opts) {
|
|
119
|
+
const url = new URL(resolveBaseUrl(ctx) + opts.path);
|
|
120
|
+
if (opts.query)
|
|
121
|
+
appendQuery(url, opts.query);
|
|
122
|
+
const headers = {
|
|
123
|
+
Accept: "application/json",
|
|
124
|
+
"User-Agent": `consulti-cli/${ctx.version}`,
|
|
125
|
+
};
|
|
126
|
+
if (opts.key)
|
|
127
|
+
headers.Authorization = `Bearer ${opts.key}`;
|
|
128
|
+
if (opts.body !== undefined)
|
|
129
|
+
headers["Content-Type"] = "application/json";
|
|
130
|
+
let res;
|
|
131
|
+
let text;
|
|
132
|
+
try {
|
|
133
|
+
res = await ctx.fetch(url, {
|
|
134
|
+
method: opts.method,
|
|
135
|
+
headers,
|
|
136
|
+
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
137
|
+
signal: AbortSignal.timeout(opts.timeoutMs),
|
|
138
|
+
redirect: "error",
|
|
139
|
+
});
|
|
140
|
+
text = await res.text();
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
const name = e instanceof Error ? e.name : "";
|
|
144
|
+
const timedOut = name === "TimeoutError" || name === "AbortError";
|
|
145
|
+
throw new CliError({
|
|
146
|
+
exit: EXIT.network,
|
|
147
|
+
error: timedOut
|
|
148
|
+
? `The request timed out after ${Math.round(opts.timeoutMs / 1000)} seconds.`
|
|
149
|
+
: `Network error: ${scrub(e instanceof Error ? e.message : String(e), [opts.key, url.search])}`,
|
|
150
|
+
code: timedOut ? "timeout" : "network_error",
|
|
151
|
+
hint: opts.billable ? BILLED_HINT : null,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (!res.ok)
|
|
155
|
+
throw httpError(res, text, opts.billable);
|
|
156
|
+
const body = asObject(text);
|
|
157
|
+
if (!body) {
|
|
158
|
+
throw new CliError({
|
|
159
|
+
exit: EXIT.unexpected,
|
|
160
|
+
error: "The server answered with a body that is not a JSON object.",
|
|
161
|
+
code: "bad_response",
|
|
162
|
+
status: res.status,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return body;
|
|
166
|
+
}
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { Option } from "commander";
|
|
3
|
+
import { call } from "./client.js";
|
|
4
|
+
import { requireKey } from "./config.js";
|
|
5
|
+
import { usageError } from "./errors.js";
|
|
6
|
+
import { attributeFor, optionsFor, paramFlag } from "./flags.js";
|
|
7
|
+
import { ALIASES, JSONL_IDS, timeoutFor } from "./manifest.js";
|
|
8
|
+
import { printJson, printJsonl } from "./output.js";
|
|
9
|
+
async function readBody(ctx, spec) {
|
|
10
|
+
let text;
|
|
11
|
+
if (spec === "-") {
|
|
12
|
+
text = await ctx.io.readStdin();
|
|
13
|
+
}
|
|
14
|
+
else if (spec.startsWith("@")) {
|
|
15
|
+
try {
|
|
16
|
+
text = readFileSync(spec.slice(1), "utf8");
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
throw usageError(`Cannot read --body file ${spec.slice(1)}: ${e instanceof Error ? e.message : String(e)}`, "bad_body");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
text = spec;
|
|
24
|
+
}
|
|
25
|
+
let parsed;
|
|
26
|
+
try {
|
|
27
|
+
parsed = JSON.parse(text);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw usageError("--body is not valid JSON.", "bad_body");
|
|
31
|
+
}
|
|
32
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
33
|
+
throw usageError("--body must be a JSON object.", "bad_body");
|
|
34
|
+
}
|
|
35
|
+
return parsed;
|
|
36
|
+
}
|
|
37
|
+
async function run(ctx, ep, positional, cmd) {
|
|
38
|
+
const opts = cmd.opts();
|
|
39
|
+
for (const [i, value] of positional.entries()) {
|
|
40
|
+
if (value === "" || value === "." || value === "..") {
|
|
41
|
+
throw usageError(`<${ep.pathParams[i]}> must not be empty, "." or "..".`, "bad_path_param");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const payload = typeof opts.body === "string" ? await readBody(ctx, opts.body) : {};
|
|
45
|
+
for (const p of ep.params) {
|
|
46
|
+
const v = opts[attributeFor(p)];
|
|
47
|
+
if (v !== undefined)
|
|
48
|
+
payload[p.name] = v;
|
|
49
|
+
}
|
|
50
|
+
for (const p of ep.params) {
|
|
51
|
+
if (p.required && payload[p.name] === undefined) {
|
|
52
|
+
throw usageError(`Missing required flag --${paramFlag(p)} (${p.name}).`, "missing_required");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const key = ep.noAuth ? undefined : requireKey(ctx).key;
|
|
56
|
+
let path = ep.path;
|
|
57
|
+
ep.pathParams.forEach((name, i) => {
|
|
58
|
+
path = path.replace(`{${name}}`, encodeURIComponent(positional[i]));
|
|
59
|
+
});
|
|
60
|
+
const isGet = ep.method === "GET";
|
|
61
|
+
const body = await call(ctx, {
|
|
62
|
+
method: ep.method,
|
|
63
|
+
path,
|
|
64
|
+
query: isGet ? payload : undefined,
|
|
65
|
+
body: isGet ? undefined : payload,
|
|
66
|
+
key,
|
|
67
|
+
timeoutMs: timeoutFor(ep.id),
|
|
68
|
+
billable: ep.billable,
|
|
69
|
+
});
|
|
70
|
+
if (opts.jsonl === true)
|
|
71
|
+
printJsonl(ctx, body);
|
|
72
|
+
else
|
|
73
|
+
printJson(ctx, body);
|
|
74
|
+
}
|
|
75
|
+
/** One command per manifest entry, plus the short aliases. */
|
|
76
|
+
export function registerEndpoints(program, ctx, endpoints) {
|
|
77
|
+
for (const ep of endpoints) {
|
|
78
|
+
const cmd = program.command(ep.id).summary(ep.title);
|
|
79
|
+
for (const [alias, target] of Object.entries(ALIASES)) {
|
|
80
|
+
if (target === ep.id)
|
|
81
|
+
cmd.alias(alias);
|
|
82
|
+
}
|
|
83
|
+
for (const name of ep.pathParams)
|
|
84
|
+
cmd.argument(`<${name}>`);
|
|
85
|
+
cmd.description(`${ep.title}\n\n${ep.description.replace(/\s+/g, " ").trim()}`);
|
|
86
|
+
for (const p of ep.params) {
|
|
87
|
+
for (const opt of optionsFor(p))
|
|
88
|
+
cmd.addOption(opt);
|
|
89
|
+
}
|
|
90
|
+
if (ep.method !== "GET") {
|
|
91
|
+
cmd.addOption(new Option("--body <json>", "Full JSON request body: inline JSON, @file, or - for stdin. Explicit flags override body keys."));
|
|
92
|
+
}
|
|
93
|
+
if (JSONL_IDS.includes(ep.id)) {
|
|
94
|
+
cmd.addOption(new Option("--jsonl", "Print one result row per line instead of the whole response."));
|
|
95
|
+
}
|
|
96
|
+
cmd.addHelpText("after", `\nCredits: ${ep.credits.replace(/\s+/g, " ").trim()}\nPlan: ${ep.tier}${ep.noAuth ? " (no API key needed)" : ""}`);
|
|
97
|
+
cmd.action(async (...args) => {
|
|
98
|
+
const command = args[args.length - 1];
|
|
99
|
+
await run(ctx, ep, args.slice(0, ep.pathParams.length), command);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { DEFAULT_BASE_URL, SETTINGS_URL } from "./context.js";
|
|
5
|
+
import { CliError, usageError } from "./errors.js";
|
|
6
|
+
import { EXIT } from "./exit-codes.js";
|
|
7
|
+
export const KEY_FORMAT = /^capi_[0-9a-f]{64}$/;
|
|
8
|
+
export function configDir(ctx) {
|
|
9
|
+
const xdg = ctx.env.XDG_CONFIG_HOME;
|
|
10
|
+
// A relative XDG_CONFIG_HOME is ignored (the XDG spec says so), so the key never lands in the cwd.
|
|
11
|
+
const base = xdg && isAbsolute(xdg) ? xdg : join(ctx.homedir, ".config");
|
|
12
|
+
return join(base, "consulti");
|
|
13
|
+
}
|
|
14
|
+
export function configPath(ctx) {
|
|
15
|
+
return join(configDir(ctx), "config.json");
|
|
16
|
+
}
|
|
17
|
+
function readFileKey(ctx) {
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(readFileSync(configPath(ctx), "utf8"));
|
|
20
|
+
return typeof parsed.api_key === "string" && parsed.api_key.length > 0 ? parsed.api_key : null;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Env beats file. Returns null when neither holds a key; throws on a malformed one (never echoed). */
|
|
27
|
+
export function resolveKey(ctx) {
|
|
28
|
+
const env = ctx.env.CONSULTI_API_KEY?.trim();
|
|
29
|
+
if (env) {
|
|
30
|
+
if (!KEY_FORMAT.test(env)) {
|
|
31
|
+
throw new CliError({
|
|
32
|
+
exit: EXIT.auth,
|
|
33
|
+
error: "CONSULTI_API_KEY is not a valid Consulti API key (expected capi_ followed by 64 hex characters).",
|
|
34
|
+
code: "invalid_key_format",
|
|
35
|
+
hint: `Create a key at ${SETTINGS_URL}`,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return { key: env, source: "env" };
|
|
39
|
+
}
|
|
40
|
+
const file = readFileKey(ctx);
|
|
41
|
+
if (!file)
|
|
42
|
+
return null;
|
|
43
|
+
if (!KEY_FORMAT.test(file)) {
|
|
44
|
+
throw new CliError({
|
|
45
|
+
exit: EXIT.auth,
|
|
46
|
+
error: "The saved API key is not valid. Run `consulti login` again.",
|
|
47
|
+
code: "invalid_key_format",
|
|
48
|
+
hint: `Create a key at ${SETTINGS_URL}`,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return { key: file, source: "file" };
|
|
52
|
+
}
|
|
53
|
+
export function requireKey(ctx) {
|
|
54
|
+
const found = resolveKey(ctx);
|
|
55
|
+
if (found)
|
|
56
|
+
return found;
|
|
57
|
+
throw new CliError({
|
|
58
|
+
exit: EXIT.auth,
|
|
59
|
+
error: "No API key configured. Set CONSULTI_API_KEY or run `consulti login`.",
|
|
60
|
+
code: "no_api_key",
|
|
61
|
+
hint: `Create a key at ${SETTINGS_URL}`,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** Writes the key to a 0600 file inside a 0700 directory, whatever the umask. */
|
|
65
|
+
export function saveKey(ctx, key) {
|
|
66
|
+
const dir = configDir(ctx);
|
|
67
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
68
|
+
const st = lstatSync(dir);
|
|
69
|
+
if (!st.isDirectory() || (process.getuid && st.uid !== process.getuid())) {
|
|
70
|
+
throw new CliError({
|
|
71
|
+
exit: EXIT.unexpected,
|
|
72
|
+
error: `Refusing to save the key: ${dir} is not a directory you own.`,
|
|
73
|
+
code: "unsafe_config_dir",
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
chmodSync(dir, 0o700);
|
|
77
|
+
const file = configPath(ctx);
|
|
78
|
+
const tmp = join(dir, `.config.json.${randomBytes(6).toString("hex")}.tmp`);
|
|
79
|
+
try {
|
|
80
|
+
writeFileSync(tmp, JSON.stringify({ api_key: key }) + "\n", { flag: "wx", mode: 0o600 });
|
|
81
|
+
renameSync(tmp, file);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
rmSync(tmp, { force: true });
|
|
85
|
+
throw e;
|
|
86
|
+
}
|
|
87
|
+
return file;
|
|
88
|
+
}
|
|
89
|
+
/** Returns true when a file (or a symlink in its place) was removed. */
|
|
90
|
+
export function deleteKeyFile(ctx) {
|
|
91
|
+
try {
|
|
92
|
+
lstatSync(configPath(ctx));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
rmSync(configPath(ctx), { force: true });
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
/** Shows only `capi_` plus 4 characters, and nothing at all for anything that is not a valid key. */
|
|
101
|
+
export function keyPrefix(key) {
|
|
102
|
+
return KEY_FORMAT.test(key) ? key.slice(0, 9) + "…" : "(unrecognised key format)";
|
|
103
|
+
}
|
|
104
|
+
export function resolveBaseUrl(ctx) {
|
|
105
|
+
const raw = ctx.env.CONSULTI_BASE_URL?.trim();
|
|
106
|
+
if (!raw)
|
|
107
|
+
return DEFAULT_BASE_URL;
|
|
108
|
+
let url;
|
|
109
|
+
try {
|
|
110
|
+
url = new URL(raw);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
throw usageError(`CONSULTI_BASE_URL is not a valid URL: ${raw}`, "invalid_base_url");
|
|
114
|
+
}
|
|
115
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
116
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
|
|
117
|
+
throw usageError("CONSULTI_BASE_URL must use https (http is allowed only for localhost and 127.0.0.1).", "insecure_base_url");
|
|
118
|
+
}
|
|
119
|
+
return raw.replace(/\/+$/, "");
|
|
120
|
+
}
|
package/dist/context.js
ADDED