@growthgenie/cli 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Growth Genie
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,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # Growth Genie CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read your [Growth Genie](https://growthgenie.so) AI visibility, tracked prompts and the answers ChatGPT, Claude,
4
+ Perplexity and Google's AI gave, and add or stop prompts, from a terminal, a script or an AI agent.
5
+
6
+ ```sh
7
+ npx @growthgenie/cli login
8
+ npx @growthgenie/cli visibility acme.com
9
+ ```
10
+
11
+ Or install it once: `npm install -g @growthgenie/cli`, then run `growthgenie`. It needs Node.js 20 or later and has no
12
+ dependencies.
13
+
14
+ ## Sign in
15
+
16
+ ```sh
17
+ growthgenie login # read only
18
+ growthgenie login --write # also add, stop and group prompts
19
+ ```
20
+
21
+ Your browser opens at Growth Genie: sign in, choose the workspaces the CLI may read and approve. On a computer without
22
+ a browser, add `--no-browser`, open the address it prints on any computer, and paste back the address the browser ends
23
+ on. Each computer you sign in on appears in Growth Genie under **Settings → Connected AI clients**, where you can
24
+ disconnect it. `growthgenie logout` signs out here.
25
+
26
+ The sign-in is kept in `~/.config/growthgenie/cli.json` (`$XDG_CONFIG_HOME/growthgenie` if set,
27
+ `%APPDATA%\growthgenie` on Windows), readable only by you. The access token renews itself.
28
+
29
+ ## Commands
30
+
31
+ | Command | What it does |
32
+ | --- | --- |
33
+ | `projects` | The projects you approved, with their IDs. |
34
+ | `visibility <project> [--country GB] [--topic <topic>]` | Today's visibility score, and for each prompt whether each engine named you. |
35
+ | `prompts <project> [--topic <topic>]` | Tracked prompts, and how much of your plan they use. |
36
+ | `topics <project>` | Topics and how many prompts each has. |
37
+ | `answer <project> <prompt-id> <engine> [--day YYYY-MM-DD] [--full]` | One engine's answer, word for word, with every brand it ranked and the sources it cited. |
38
+ | `add-prompt <project> <text> [--topic <topic>] [--country US]` | Start tracking a question. A stopped one comes back with its history. |
39
+ | `remove-prompt <project> <prompt-id>` | Stop tracking a prompt. Its history is kept. |
40
+ | `create-topic <project> <name>` | Create a topic. |
41
+ | `move-prompt <project> <prompt-id> <topic\|none>` | Move a prompt into a topic, or out of one. |
42
+ | `tools` | The MCP tools your sign-in can use. |
43
+ | `call <tool> '<json>'` | Call any tool and print its JSON result. |
44
+ | `status`, `login`, `logout` | Your sign-in on this computer. |
45
+
46
+ `<project>` is a project ID, a domain (`acme.com`) or a name. `<topic>` is a topic ID or name. `<engine>` is
47
+ `chatgpt`, `claude`, `perplexity`, `ai-overviews` or `ai-mode`. Lists show one page; add `--all` for everything.
48
+
49
+ ## Scripts and agents
50
+
51
+ Every command takes `--json` and then prints the tool's structured result, the same JSON the
52
+ [Growth Genie MCP server](https://docs.growthgenie.so/mcp/) returns:
53
+
54
+ ```sh
55
+ growthgenie visibility acme.com --json | jq '.data.score'
56
+ growthgenie prompts acme.com --all --json | jq -r '.data.items[] | select(.status == "active") | .text'
57
+ ```
58
+
59
+ Errors go to stderr as one line, and the exit code says what happened:
60
+
61
+ | Code | Meaning |
62
+ | --- | --- |
63
+ | 0 | Done. |
64
+ | 1 | Growth Genie refused or failed (the message gives the error code). |
65
+ | 2 | Wrong command or arguments. |
66
+ | 3 | Sign-in needed: run `growthgenie login` (or `login --write` to change prompts). |
67
+
68
+ Limits and brief outages are retried after the delay Growth Genie asks for. Changes carry an idempotency key, so a
69
+ retry never applies twice.
70
+
71
+ The CLI is for computers that keep their sign-in: your laptop, a server, an agent's machine. Refresh tokens change on
72
+ every use and a reused one ends the sign-in, so don't copy `cli.json` into short-lived CI runners.
73
+
74
+ ## Docs
75
+
76
+ - [Growth Genie CLI](https://docs.growthgenie.so/cli/)
77
+ - [MCP server](https://docs.growthgenie.so/mcp/) and [API: OAuth, scopes and errors](https://docs.growthgenie.so/api/)
78
+
79
+ MIT licensed.
package/dist/auth.js ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Sign-in for the CLI: OAuth 2.1 against Growth Genie's authorization server, exactly as an MCP client does it.
3
+ *
4
+ * - Discovery: the MCP endpoint's protected resource metadata (RFC 9728) names the authorization server, whose metadata
5
+ * (RFC 8414) lists the endpoints.
6
+ * - Each `login` registers a public client (RFC 7591) with a loopback redirect, so every machine is its own entry under
7
+ * Settings → Connected AI clients and can be disconnected alone.
8
+ * - Authorization code with PKCE (S256) and a `resource` indicator (RFC 8707). The browser comes back to a one-shot
9
+ * server on 127.0.0.1 (RFC 8252); if the browser is on another computer, the address it lands on can be pasted.
10
+ * - Refresh tokens rotate, and reusing an old one revokes the whole sign-in, so refreshing happens under the store's
11
+ * lock and re-reads the file first.
12
+ */
13
+ import { createHash, randomBytes } from "node:crypto";
14
+ import { createServer } from "node:http";
15
+ import { CliError, SignInRequired } from "./errors.js";
16
+ import { USER_AGENT } from "./version.js";
17
+ /** Growth Genie's MCP server, the resource every token is for. */
18
+ export const DEFAULT_RESOURCE = "https://auth.growthgenie.so/mcp";
19
+ export const CLIENT_NAME = "Growth Genie CLI";
20
+ export const READ_SCOPES = ["projects:read", "marketing:read"];
21
+ export const WRITE_SCOPE = "marketing:write";
22
+ /** Registered without a port: the authorization server accepts any port on a loopback redirect (RFC 8252 §7.3). */
23
+ export const REGISTERED_REDIRECT = "http://127.0.0.1/callback";
24
+ /** Refresh this long before the access token expires. */
25
+ const EARLY_MS = 60_000;
26
+ /** An OAuth error response (RFC 6749 §5.2). */
27
+ export class OAuthError extends CliError {
28
+ error;
29
+ constructor(error, description) {
30
+ super(`Growth Genie refused the sign-in: ${error}${description ? ` (${description})` : ""}.`);
31
+ this.error = error;
32
+ }
33
+ }
34
+ const base64url = (bytes) => bytes.toString("base64url");
35
+ const isLoopback = (host) => host === "127.0.0.1" || host === "[::1]" || host === "localhost";
36
+ /** HTTPS, or plain HTTP on this computer (local servers and tests). */
37
+ function trusted(value, what) {
38
+ let url;
39
+ try {
40
+ url = new URL(String(value));
41
+ }
42
+ catch {
43
+ throw new CliError(`Growth Genie's sign-in metadata has an invalid ${what}.`);
44
+ }
45
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopback(url.hostname))) {
46
+ throw new CliError(`Growth Genie's sign-in metadata names an insecure ${what}: ${url.href}`);
47
+ }
48
+ return String(value);
49
+ }
50
+ /** `https://host/.well-known/<name>/path` for an identifier `https://host/path` (RFC 8414 §3, RFC 9728 §3). */
51
+ export function wellKnown(identifier, name) {
52
+ const url = new URL(identifier);
53
+ const path = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "");
54
+ return `${url.origin}/.well-known/${name}${path}`;
55
+ }
56
+ async function getJson(deps, url) {
57
+ const response = await deps.fetch(url, { headers: { Accept: "application/json", "User-Agent": USER_AGENT } });
58
+ if (!response.ok)
59
+ throw new CliError(`Couldn't read ${url} (HTTP ${response.status}).`);
60
+ return (await response.json());
61
+ }
62
+ /** The authorization server for `resource`, checked as RFC 9728 §3.3 and RFC 8414 §3.3 require. */
63
+ export async function discover(resource, deps) {
64
+ const protectedResource = await getJson(deps, wellKnown(resource, "oauth-protected-resource"));
65
+ if (protectedResource.resource !== resource) {
66
+ throw new CliError(`Growth Genie's resource metadata is for ${String(protectedResource.resource)}, not ${resource}.`);
67
+ }
68
+ const servers = protectedResource.authorization_servers;
69
+ if (!Array.isArray(servers) || typeof servers[0] !== "string")
70
+ throw new CliError("Growth Genie's resource metadata names no authorization server.");
71
+ const issuer = servers[0];
72
+ const metadata = await getJson(deps, wellKnown(issuer, "oauth-authorization-server"));
73
+ if (metadata.issuer !== issuer)
74
+ throw new CliError(`Growth Genie's authorization server says it is ${String(metadata.issuer)}, not ${issuer}.`);
75
+ const methods = metadata.code_challenge_methods_supported;
76
+ if (Array.isArray(methods) && !methods.includes("S256"))
77
+ throw new CliError("Growth Genie's authorization server does not offer PKCE with S256.");
78
+ return {
79
+ issuer,
80
+ authorization_endpoint: trusted(metadata.authorization_endpoint, "authorization endpoint"),
81
+ token_endpoint: trusted(metadata.token_endpoint, "token endpoint"),
82
+ registration_endpoint: metadata.registration_endpoint ? trusted(metadata.registration_endpoint, "registration endpoint") : undefined,
83
+ revocation_endpoint: metadata.revocation_endpoint ? trusted(metadata.revocation_endpoint, "revocation endpoint") : undefined,
84
+ };
85
+ }
86
+ async function register(metadata, deps) {
87
+ if (!metadata.registration_endpoint)
88
+ throw new CliError("Growth Genie's authorization server doesn't accept new clients.");
89
+ const response = await deps.fetch(metadata.registration_endpoint, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": USER_AGENT },
92
+ body: JSON.stringify({
93
+ client_name: CLIENT_NAME,
94
+ redirect_uris: [REGISTERED_REDIRECT],
95
+ grant_types: ["authorization_code", "refresh_token"],
96
+ response_types: ["code"],
97
+ token_endpoint_auth_method: "none",
98
+ scope: [...READ_SCOPES, WRITE_SCOPE, "offline_access"].join(" "),
99
+ }),
100
+ });
101
+ const body = (await response.json().catch(() => ({})));
102
+ if (!response.ok || typeof body.client_id !== "string") {
103
+ if (response.status === 429)
104
+ throw new CliError("Too many sign-ins from this network. Try again in a minute.");
105
+ throw new OAuthError(body.error ?? `HTTP ${response.status}`, body.error_description);
106
+ }
107
+ return body.client_id;
108
+ }
109
+ async function tokenRequest(endpoint, form, deps) {
110
+ const response = await deps.fetch(endpoint, {
111
+ method: "POST",
112
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", "User-Agent": USER_AGENT },
113
+ body: new URLSearchParams(form).toString(),
114
+ });
115
+ const body = (await response.json().catch(() => ({})));
116
+ if (!response.ok || typeof body.access_token !== "string") {
117
+ if (body.error)
118
+ throw new OAuthError(body.error, body.error_description);
119
+ throw new CliError(`Growth Genie's token endpoint answered HTTP ${response.status}.`);
120
+ }
121
+ if (typeof body.token_type === "string" && body.token_type.toLowerCase() !== "bearer") {
122
+ throw new CliError(`Growth Genie issued a ${body.token_type} token; the CLI needs a Bearer token.`);
123
+ }
124
+ return body;
125
+ }
126
+ const expiry = (tokens, deps) => deps.now() + (typeof tokens.expires_in === "number" ? tokens.expires_in : 3600) * 1000;
127
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
128
+ /** A one-shot server on 127.0.0.1 that takes the authorization response. */
129
+ async function listen(timeoutMs) {
130
+ let settle;
131
+ let fail;
132
+ const result = new Promise((resolve, reject) => { settle = resolve; fail = reject; });
133
+ const server = createServer((request, response) => {
134
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
135
+ if (url.pathname !== "/callback") {
136
+ response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
137
+ return;
138
+ }
139
+ const failed = url.searchParams.get("error");
140
+ const page = failed
141
+ ? `<p>Growth Genie didn't sign you in (${escapeHtml(failed)}). Go back to the terminal to try again.</p>`
142
+ : "<p>You're signed in to Growth Genie. You can close this tab and go back to the terminal.</p>";
143
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", Connection: "close", "Cache-Control": "no-store" })
144
+ .end(`<!doctype html><meta charset="utf-8"><title>Growth Genie CLI</title><body style="font:16px system-ui;margin:48px">${page}</body>`);
145
+ settle(url.searchParams);
146
+ });
147
+ await new Promise((resolve, reject) => server.once("error", reject).listen(0, "127.0.0.1", resolve));
148
+ const timer = setTimeout(() => fail(new CliError("Sign-in timed out. Run `growthgenie login` again.")), timeoutMs);
149
+ const { port } = server.address();
150
+ return {
151
+ redirectUri: `http://127.0.0.1:${port}/callback`,
152
+ result,
153
+ close: () => {
154
+ clearTimeout(timer);
155
+ server.closeAllConnections();
156
+ server.close();
157
+ },
158
+ };
159
+ }
160
+ export async function login(options, deps) {
161
+ const metadata = await discover(options.resource, deps);
162
+ const clientId = await register(metadata, deps);
163
+ const verifier = base64url(randomBytes(32));
164
+ const state = base64url(randomBytes(16));
165
+ const scope = [...READ_SCOPES, ...(options.write ? [WRITE_SCOPE] : []), "offline_access"].join(" ");
166
+ const callback = await listen(options.timeoutMs ?? 10 * 60_000);
167
+ const paste = new AbortController();
168
+ try {
169
+ const url = new URL(metadata.authorization_endpoint);
170
+ const query = {
171
+ response_type: "code", client_id: clientId, redirect_uri: callback.redirectUri, scope, state,
172
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()), code_challenge_method: "S256", resource: options.resource,
173
+ };
174
+ for (const [key, value] of Object.entries(query))
175
+ url.searchParams.set(key, value);
176
+ const opened = options.openBrowser ? await options.openBrowser(url.href).catch(() => false) : false;
177
+ options.log(opened
178
+ ? `Your browser is open at Growth Genie: sign in and approve "${CLIENT_NAME}". If it didn't open, go to:\n\n ${url.href}\n`
179
+ : `Open this address in a browser, sign in to Growth Genie and approve "${CLIENT_NAME}":\n\n ${url.href}\n`);
180
+ const never = new Promise(() => { });
181
+ let pasted = never;
182
+ if (options.readPasted) {
183
+ options.log("If that browser is on another computer, paste the address it ends on here and press Enter.");
184
+ pasted = options.readPasted(paste.signal).then((text) => {
185
+ if (!text?.trim())
186
+ return never;
187
+ try {
188
+ return new URL(text.trim()).searchParams;
189
+ }
190
+ catch {
191
+ throw new CliError("That isn't the address the browser ended on. Run `growthgenie login` again.");
192
+ }
193
+ });
194
+ }
195
+ const params = await Promise.race([callback.result, pasted]);
196
+ if (params.get("state") !== state)
197
+ throw new CliError("The sign-in answer doesn't belong to this login (state mismatch). Run `growthgenie login` again.");
198
+ const error = params.get("error");
199
+ if (error)
200
+ throw new OAuthError(error, params.get("error_description") ?? undefined);
201
+ const code = params.get("code");
202
+ if (!code)
203
+ throw new CliError("The sign-in answer has no authorization code. Run `growthgenie login` again.");
204
+ const tokens = await tokenRequest(metadata.token_endpoint, {
205
+ grant_type: "authorization_code", code, redirect_uri: callback.redirectUri, code_verifier: verifier, client_id: clientId, resource: options.resource,
206
+ }, deps);
207
+ const credentials = {
208
+ resource: options.resource,
209
+ issuer: metadata.issuer,
210
+ tokenEndpoint: metadata.token_endpoint,
211
+ revocationEndpoint: metadata.revocation_endpoint,
212
+ clientId,
213
+ accessToken: tokens.access_token,
214
+ expiresAt: expiry(tokens, deps),
215
+ refreshToken: tokens.refresh_token,
216
+ scope: tokens.scope ?? scope,
217
+ };
218
+ await options.store.withLock(() => options.store.write(credentials));
219
+ return credentials;
220
+ }
221
+ finally {
222
+ paste.abort();
223
+ callback.close();
224
+ }
225
+ }
226
+ /**
227
+ * Credentials whose access token is not about to expire. `rejected` is a token the server just refused: it is
228
+ * refreshed even with time left, unless another process has already replaced it.
229
+ */
230
+ export async function freshCredentials(store, deps, rejected) {
231
+ const usable = (c) => c.accessToken !== rejected && c.expiresAt - EARLY_MS > deps.now();
232
+ const first = await store.read();
233
+ if (!first)
234
+ throw new SignInRequired();
235
+ if (usable(first))
236
+ return first;
237
+ return store.withLock(async () => {
238
+ const current = await store.read();
239
+ if (!current)
240
+ throw new SignInRequired();
241
+ if (usable(current))
242
+ return current;
243
+ if (!current.refreshToken)
244
+ throw new SignInRequired("Your sign-in expired. Run `growthgenie login`.");
245
+ let tokens;
246
+ try {
247
+ tokens = await tokenRequest(current.tokenEndpoint, {
248
+ grant_type: "refresh_token", refresh_token: current.refreshToken, client_id: current.clientId, resource: current.resource,
249
+ }, deps);
250
+ }
251
+ catch (error) {
252
+ if (error instanceof OAuthError && ["invalid_grant", "invalid_client", "unauthorized_client"].includes(error.error)) {
253
+ await store.clear();
254
+ throw new SignInRequired("Your sign-in expired or was disconnected. Run `growthgenie login`.");
255
+ }
256
+ throw error;
257
+ }
258
+ const next = {
259
+ ...current,
260
+ accessToken: tokens.access_token,
261
+ expiresAt: expiry(tokens, deps),
262
+ refreshToken: tokens.refresh_token ?? current.refreshToken,
263
+ scope: tokens.scope ?? current.scope,
264
+ };
265
+ await store.write(next);
266
+ return next;
267
+ });
268
+ }
269
+ /** Asks the server to revoke the refresh token, then forgets the sign-in either way. */
270
+ export async function logout(store, deps) {
271
+ return store.withLock(async () => {
272
+ const credentials = await store.read();
273
+ if (!credentials)
274
+ return { signedIn: false, revoked: false };
275
+ let revoked = false;
276
+ if (credentials.revocationEndpoint && credentials.refreshToken) {
277
+ try {
278
+ const response = await deps.fetch(credentials.revocationEndpoint, {
279
+ method: "POST",
280
+ headers: { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": USER_AGENT },
281
+ body: new URLSearchParams({ token: credentials.refreshToken, token_type_hint: "refresh_token", client_id: credentials.clientId }).toString(),
282
+ });
283
+ revoked = response.ok;
284
+ }
285
+ catch {
286
+ revoked = false;
287
+ }
288
+ }
289
+ await store.clear();
290
+ return { signedIn: true, revoked };
291
+ });
292
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // The `growthgenie` executable. Everything else lives in main.ts, which the tests call directly.
3
+ import { main } from "./main.js";
4
+ process.exitCode = await main(process.argv.slice(2));
package/dist/client.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * A small MCP client for Growth Genie's server: JSON-RPC over Streamable HTTP, one POST per request, answered with
3
+ * JSON or a short event stream. The server is stateless, so there is no session to open. Access tokens are refreshed
4
+ * when they are about to expire, or once when the server refuses one. Limits and temporary failures are retried with
5
+ * the server's delay, writes keeping their idempotency key so a retry can never apply twice.
6
+ */
7
+ import { freshCredentials } from "./auth.js";
8
+ import { CliError, SignInRequired, ToolError } from "./errors.js";
9
+ import { USER_AGENT } from "./version.js";
10
+ export const PROTOCOL_VERSION = "2025-11-25";
11
+ const MAX_RETRIES = 2;
12
+ const MAX_WAIT_S = 30;
13
+ /** The message with `id` from a JSON body or a `text/event-stream` body. */
14
+ export async function readMessage(response, id) {
15
+ const type = response.headers.get("Content-Type") ?? "";
16
+ const text = await response.text();
17
+ if (!type.includes("text/event-stream"))
18
+ return JSON.parse(text);
19
+ for (const event of text.split(/\r?\n\r?\n/)) {
20
+ const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
21
+ if (!data)
22
+ continue;
23
+ const message = JSON.parse(data);
24
+ if (message.id === id)
25
+ return message;
26
+ }
27
+ throw new CliError("Growth Genie's MCP server ended the response without an answer.");
28
+ }
29
+ const seconds = (value, fallback) => {
30
+ const parsed = Number(value);
31
+ return Math.min(Number.isFinite(parsed) && parsed > 0 ? parsed : fallback, MAX_WAIT_S);
32
+ };
33
+ export class McpClient {
34
+ store;
35
+ deps;
36
+ id = 0;
37
+ constructor(store, deps) {
38
+ this.store = store;
39
+ this.deps = deps;
40
+ }
41
+ /** The signed-in credentials, refreshed if needed. */
42
+ credentials() {
43
+ return freshCredentials(this.store, this.deps);
44
+ }
45
+ async callTool(name, args) {
46
+ for (let attempt = 0;; attempt++) {
47
+ const result = await this.rpc("tools/call", { name, arguments: args });
48
+ const structured = result.structuredContent;
49
+ if (!result.isError) {
50
+ if (structured)
51
+ return structured;
52
+ throw new CliError(`${name} returned no structured result.`);
53
+ }
54
+ const body = (structured && typeof structured.code === "string" ? structured : {
55
+ code: "UNKNOWN", message: textOf(result) || `${name} failed.`, retryable: false,
56
+ });
57
+ if (body.retryable && attempt < MAX_RETRIES) {
58
+ await this.deps.sleep(seconds(String(body.retryAfterSeconds ?? ""), 2 ** attempt) * 1000);
59
+ continue;
60
+ }
61
+ throw new ToolError(name, body);
62
+ }
63
+ }
64
+ async listTools() {
65
+ const tools = [];
66
+ let cursor;
67
+ do {
68
+ const result = await this.rpc("tools/list", cursor ? { cursor } : {});
69
+ tools.push(...(result.tools ?? []));
70
+ cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;
71
+ } while (cursor);
72
+ return tools;
73
+ }
74
+ async rpc(method, params) {
75
+ let credentials = await freshCredentials(this.store, this.deps);
76
+ let refreshed = false;
77
+ for (let attempt = 0;;) {
78
+ const id = ++this.id;
79
+ let response;
80
+ try {
81
+ response = await this.deps.fetch(credentials.resource, {
82
+ method: "POST",
83
+ headers: {
84
+ Authorization: `Bearer ${credentials.accessToken}`,
85
+ "Content-Type": "application/json",
86
+ Accept: "application/json, text/event-stream",
87
+ "MCP-Protocol-Version": PROTOCOL_VERSION,
88
+ "User-Agent": USER_AGENT,
89
+ },
90
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
91
+ });
92
+ }
93
+ catch (error) {
94
+ throw new CliError(`Couldn't reach Growth Genie at ${new URL(credentials.resource).host}: ${error.message}`);
95
+ }
96
+ if (response.status === 401) {
97
+ await response.body?.cancel();
98
+ if (refreshed)
99
+ throw new SignInRequired("Growth Genie didn't accept your sign-in. Run `growthgenie login`.");
100
+ credentials = await freshCredentials(this.store, this.deps, credentials.accessToken);
101
+ refreshed = true;
102
+ continue;
103
+ }
104
+ if ((response.status === 429 || response.status === 503) && attempt < MAX_RETRIES) {
105
+ await response.body?.cancel();
106
+ await this.deps.sleep(seconds(response.headers.get("Retry-After"), 2 ** attempt) * 1000);
107
+ attempt++;
108
+ continue;
109
+ }
110
+ if (!response.ok) {
111
+ const body = (await response.json().catch(() => ({})));
112
+ if (response.status === 403 && (response.headers.get("WWW-Authenticate") ?? "").includes("insufficient_scope")) {
113
+ throw new SignInRequired("Your sign-in is missing a permission Growth Genie needs. Run `growthgenie login` again.");
114
+ }
115
+ const detail = [body.message ?? body.error, body.hint].filter(Boolean).join(" ");
116
+ throw new CliError(`Growth Genie answered HTTP ${response.status}${detail ? `: ${detail}` : "."}`);
117
+ }
118
+ const message = await readMessage(response, id);
119
+ if (message.error)
120
+ throw new CliError(`Growth Genie's MCP server refused ${method}: ${message.error.message} (${message.error.code}).`);
121
+ if (!message.result)
122
+ throw new CliError(`Growth Genie's MCP server sent no result for ${method}.`);
123
+ return message.result;
124
+ }
125
+ }
126
+ }
127
+ function textOf(result) {
128
+ const content = result.content;
129
+ return (content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n");
130
+ }
@@ -0,0 +1,324 @@
1
+ /**
2
+ * What each command does with Growth Genie's MCP tools, and how it prints the result. Every command can print the
3
+ * tool's structured result as JSON (`--json`) for scripts and agents; otherwise it prints plain columns.
4
+ */
5
+ import { randomUUID } from "node:crypto";
6
+ import { WRITE_SCOPE } from "./auth.js";
7
+ import { CliError, EXIT, ToolError, UsageError } from "./errors.js";
8
+ import { json, table, truncate, utcDay, utcTime } from "./format.js";
9
+ /** The MCP tool behind each command (tests/contract.test.ts checks every tool has one). */
10
+ export const COMMAND_TOOLS = {
11
+ projects: "list_projects",
12
+ prompts: "list_prompts",
13
+ topics: "list_topics",
14
+ visibility: "get_today_visibility",
15
+ answer: "get_prompt_answer",
16
+ "add-prompt": "add_prompt",
17
+ "remove-prompt": "remove_prompt",
18
+ "create-topic": "create_topic",
19
+ "move-prompt": "move_prompt",
20
+ };
21
+ /** Engine names people type, to the IDs the tools take. */
22
+ export const ENGINE_ALIASES = {
23
+ chatgpt: "chatgpt",
24
+ claude: "claude",
25
+ perplexity: "perplexity",
26
+ "ai-overviews": "google_ai_overviews",
27
+ "google-ai-overviews": "google_ai_overviews",
28
+ google_ai_overviews: "google_ai_overviews",
29
+ "ai-mode": "google_ai_mode",
30
+ "google-ai-mode": "google_ai_mode",
31
+ google_ai_mode: "google_ai_mode",
32
+ };
33
+ const ENGINE_LABELS = {
34
+ chatgpt: "ChatGPT", claude: "Claude", perplexity: "Perplexity", google_ai_overviews: "AI Overviews", google_ai_mode: "AI Mode",
35
+ };
36
+ const engineLabel = (engine) => ENGINE_LABELS[engine] ?? engine;
37
+ const PAGE_LIMIT = 50;
38
+ const MAX_PAGES = 40;
39
+ const data = (result) => result.data;
40
+ /** Every page of a list tool (or just the first), with `items` merged. */
41
+ async function pages(fetchPage, all) {
42
+ const first = await fetchPage(undefined);
43
+ const merged = { ...first, data: { ...first.data } };
44
+ for (let page = 1; all && merged.data.hasMore && merged.data.nextCursor && page < MAX_PAGES; page++) {
45
+ const next = data(await fetchPage(merged.data.nextCursor));
46
+ merged.data = { ...merged.data, ...next, items: [...merged.data.items, ...next.items] };
47
+ }
48
+ return merged;
49
+ }
50
+ const more = (page, ctx) => {
51
+ if (page.hasMore)
52
+ ctx.out("\nThere is more: add --all to list everything.");
53
+ };
54
+ /** IDs are lowercase letters and digits; names and domains are matched against the projects you can see. */
55
+ const looksLikeId = (value) => /^[0-9a-z]{16,}$/.test(value);
56
+ const bareDomain = (value) => value.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/^www\./, "").replace(/[/?#].*$/, "");
57
+ async function allProjects(ctx) {
58
+ return data(await pages((cursor) => ctx.client.callTool("list_projects", { limit: PAGE_LIMIT, ...(cursor ? { cursor } : {}) }), true)).items;
59
+ }
60
+ /** A project by ID, domain or name. */
61
+ export async function resolveProject(ctx, ref) {
62
+ if (looksLikeId(ref))
63
+ return { projectId: ref, label: ref };
64
+ const projects = await allProjects(ctx);
65
+ const domain = bareDomain(ref);
66
+ const matches = projects.filter((p) => p.projectId === ref || bareDomain(p.domain) === domain || p.name.toLowerCase() === ref.trim().toLowerCase());
67
+ if (matches.length === 1)
68
+ return { projectId: matches[0].projectId, label: `${matches[0].name} (${matches[0].domain})` };
69
+ if (!matches.length)
70
+ throw new CliError(`No project matches "${ref}". Run \`growthgenie projects\` to see yours.`);
71
+ throw new CliError(`"${ref}" matches ${matches.length} projects: ${matches.map((p) => `${p.name} ${p.projectId}`).join(", ")}. Use the project ID.`);
72
+ }
73
+ async function allPrompts(ctx, projectId) {
74
+ return data(await pages((cursor) => ctx.client.callTool("list_prompts", { projectId, limit: PAGE_LIMIT, ...(cursor ? { cursor } : {}) }), true)).items;
75
+ }
76
+ async function findPrompt(ctx, projectId, promptId) {
77
+ const prompt = (await allPrompts(ctx, projectId)).find((p) => p.promptId === promptId);
78
+ if (!prompt)
79
+ throw new CliError(`No prompt ${promptId} in this project. Run \`growthgenie prompts <project>\` to see the IDs.`);
80
+ return prompt;
81
+ }
82
+ /** A topic by ID or name; "ungrouped" (or "none") for prompts without one, when `allowNone`. */
83
+ async function resolveTopic(ctx, projectId, ref, allowNone) {
84
+ if (allowNone && ["none", "ungrouped"].includes(ref.toLowerCase()))
85
+ return null;
86
+ if (looksLikeId(ref))
87
+ return ref;
88
+ const { topics } = data(await ctx.client.callTool("list_topics", { projectId }));
89
+ const matches = topics.filter((t) => t.topicId === ref || t.name.toLowerCase() === ref.trim().toLowerCase());
90
+ if (matches.length === 1)
91
+ return matches[0].topicId;
92
+ throw new CliError(`No topic named "${ref}". Run \`growthgenie topics <project>\` to see them${allowNone ? ', or use "none"' : ""}.`);
93
+ }
94
+ async function requireWrite(ctx) {
95
+ const credentials = await ctx.client.credentials();
96
+ if (!credentials.scope.split(" ").includes(WRITE_SCOPE)) {
97
+ throw new CliError("Your sign-in can only read. Run `growthgenie login --write` and approve \"Also let it add prompts and stop them\".", EXIT.signIn);
98
+ }
99
+ }
100
+ export function engineId(value) {
101
+ const engine = ENGINE_ALIASES[value.toLowerCase()];
102
+ if (!engine)
103
+ throw new UsageError(`Unknown engine "${value}". Use one of: chatgpt, claude, perplexity, ai-overviews, ai-mode.`);
104
+ return engine;
105
+ }
106
+ export function countryCode(value) {
107
+ if (!/^[A-Za-z]{2}$/.test(value))
108
+ throw new UsageError(`Use a two-letter country code, such as US or GB, not "${value}".`);
109
+ return value.toUpperCase();
110
+ }
111
+ export function day(value) {
112
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`)))
113
+ throw new UsageError(`Use a day as YYYY-MM-DD, not "${value}".`);
114
+ return value;
115
+ }
116
+ // ── Reads ───────────────────────────────────────────────────────────────────────────────────────────────────────────
117
+ export async function projects(ctx, opts) {
118
+ const result = await pages((cursor) => ctx.client.callTool("list_projects", {
119
+ limit: PAGE_LIMIT, ...(opts.workspace ? { workspaceId: opts.workspace } : {}), ...(cursor ? { cursor } : {}),
120
+ }), opts.all);
121
+ if (ctx.json)
122
+ return ctx.out(json(result));
123
+ const page = data(result);
124
+ if (!page.items.length)
125
+ return ctx.out("No projects yet. Add a site in Growth Genie, or approve this sign-in for more workspaces.");
126
+ ctx.out(table(["PROJECT", "DOMAIN", "WORKSPACE", "ROLE", "PROJECT ID"], page.items.map((p) => [`${p.name}${p.paused ? " (paused)" : ""}`, p.domain, p.workspaceName, p.role, p.projectId]), [32, 40, 28]));
127
+ more(page, ctx);
128
+ }
129
+ export async function prompts(ctx, ref, opts) {
130
+ const { projectId } = await resolveProject(ctx, ref);
131
+ const topic = opts.topic ? ((await resolveTopic(ctx, projectId, opts.topic, true)) ?? "ungrouped") : undefined;
132
+ const result = await pages((cursor) => ctx.client.callTool("list_prompts", {
133
+ projectId, limit: PAGE_LIMIT, ...(topic ? { topic } : {}), ...(cursor ? { cursor } : {}),
134
+ }), opts.all);
135
+ if (ctx.json)
136
+ return ctx.out(json(result));
137
+ const page = data(result);
138
+ if (!page.items.length)
139
+ ctx.out("No prompts yet.");
140
+ else {
141
+ ctx.out(table(["PROMPT ID", "STATUS", "TOPIC", "COUNTRY", "PROMPT"], page.items.map((p) => [p.promptId, p.status, p.topic?.name ?? "—", p.country ?? "primary", p.text]), [0, 0, 24, 0, 80]));
142
+ }
143
+ if (page.usage)
144
+ ctx.out(`\nTracking ${page.usage.countAtLeast} of ${page.usage.limit} prompts in this plan${page.usage.overLimit ? " (over the limit)" : ""}.`);
145
+ more(page, ctx);
146
+ }
147
+ export async function topics(ctx, ref) {
148
+ const { projectId } = await resolveProject(ctx, ref);
149
+ const result = await ctx.client.callTool("list_topics", { projectId });
150
+ if (ctx.json)
151
+ return ctx.out(json(result));
152
+ const { topics: list, complete } = data(result);
153
+ if (!list.length)
154
+ return ctx.out("No topics yet. Create one with `growthgenie create-topic <project> <name>`.");
155
+ ctx.out(table(["TOPIC ID", "NAME", "ACTIVE PROMPTS"], list.map((t) => [t.topicId, t.name, t.activePromptCount === null ? "?" : String(t.activePromptCount)]), [0, 60]));
156
+ if (!complete)
157
+ ctx.out("\nSome topics or counts couldn't be read just now; try again shortly.");
158
+ }
159
+ function cellText(cell) {
160
+ if (!cell)
161
+ return "—";
162
+ if (cell.status === "answered")
163
+ return cell.ownerNamed === "yes" ? "named" : cell.ownerNamed === "no" ? "not named" : "?";
164
+ return { pending: "pending", unavailable: "no answer", not_scheduled: "—", expired: "expired", unknown: "?" }[cell.status] ?? cell.status;
165
+ }
166
+ export async function visibility(ctx, ref, opts) {
167
+ const project = await resolveProject(ctx, ref);
168
+ const topic = opts.topic ? ((await resolveTopic(ctx, project.projectId, opts.topic, true)) ?? "ungrouped") : undefined;
169
+ const result = await pages((cursor) => ctx.client.callTool("get_today_visibility", {
170
+ projectId: project.projectId, limit: 25, ...(topic ? { topic } : {}), ...(opts.country ? { country: opts.country } : {}), ...(cursor ? { cursor } : {}),
171
+ }), opts.all);
172
+ if (ctx.json)
173
+ return ctx.out(json(result));
174
+ const v = data(result);
175
+ ctx.out(`${project.label} · ${v.day ?? "no checks yet"} (UTC)${opts.country ? ` · ${opts.country}` : ""}${v.state === "starting" ? " · today's checks are starting" : ""}`);
176
+ ctx.out(v.score === null ? "No visibility score yet." : `Visibility score ${v.score}/100. Named in ${v.ownerNamed} of ${v.ownerKnown} answers${v.answered !== v.ownerKnown ? ` (${v.answered} answered in all)` : ""}.`);
177
+ if (v.items.length) {
178
+ ctx.out("");
179
+ ctx.out(table(["PROMPT", ...v.engines.map((e) => engineLabel(e).toUpperCase()), "PROMPT ID"], v.items.map((row) => [row.prompt.text, ...v.engines.map((e) => cellText(row.cells.find((c) => c.engine === e))), row.prompt.promptId]), [56]));
180
+ }
181
+ more(v, ctx);
182
+ }
183
+ export async function answer(ctx, ref, promptId, engine, opts) {
184
+ const { projectId } = await resolveProject(ctx, ref);
185
+ const args = { projectId, promptId, engine: engineId(engine), day: opts.day ?? utcDay(ctx.now()) };
186
+ const result = await ctx.client.callTool("get_prompt_answer", args);
187
+ const a = data(result);
188
+ // Each section pages on its own cursor.
189
+ for (let call = 0; opts.full && call < 50; call++) {
190
+ const cursor = a.text.nextCursor ? { textCursor: a.text.nextCursor } : a.brands.nextCursor ? { brandsCursor: a.brands.nextCursor }
191
+ : a.citations.nextCursor ? { citationsCursor: a.citations.nextCursor } : undefined;
192
+ if (!cursor)
193
+ break;
194
+ const next = data(await ctx.client.callTool("get_prompt_answer", { ...args, ...cursor }));
195
+ if ("textCursor" in cursor)
196
+ a.text = { ...next.text, content: a.text.content + next.text.content };
197
+ if ("brandsCursor" in cursor)
198
+ a.brands = { ...next.brands, items: [...a.brands.items, ...next.brands.items] };
199
+ if ("citationsCursor" in cursor)
200
+ a.citations = { ...next.citations, items: [...a.citations.items, ...next.citations.items] };
201
+ }
202
+ if (ctx.json)
203
+ return ctx.out(json({ ...result, data: a }));
204
+ ctx.out(`${engineLabel(a.engine)} · ${a.day} · ${a.status.replace(/_/g, " ")}${a.checkedAt ? ` · asked ${utcTime(a.checkedAt)}` : ""}${a.model ? ` · ${a.model}` : ""}`);
205
+ if (a.text.content) {
206
+ ctx.out(`\n${a.text.content}${a.text.nextCursor ? "\n\n… (the answer goes on: add --full)" : ""}`);
207
+ }
208
+ else if (a.status === "available")
209
+ ctx.out(`\nThe answer text is ${a.text.state}.`);
210
+ if (a.brands.items.length) {
211
+ ctx.out("\nBrands in this answer:");
212
+ for (const b of a.brands.items) {
213
+ ctx.out(` ${b.position === null ? " -" : `#${String(b.position).padEnd(3)}`} ${b.name}${b.role === "you" ? " (you)" : b.role === "competitor" ? " (competitor)" : ""}${b.mentioned ? "" : " (not mentioned)"}`);
214
+ }
215
+ }
216
+ if (a.citations.items.length) {
217
+ ctx.out("\nSources:");
218
+ for (const c of a.citations.items)
219
+ ctx.out(` [${c.index}] ${c.title ? `${truncate(c.title, 80)} — ` : ""}${c.url}`);
220
+ }
221
+ if (!opts.full && (a.brands.nextCursor || a.citations.nextCursor))
222
+ ctx.out("\nThere are more brands or sources: add --full.");
223
+ }
224
+ // ── Writes ──────────────────────────────────────────────────────────────────────────────────────────────────────────
225
+ const conflictVersion = (error) => error instanceof ToolError && error.body.code === "VERSION_CONFLICT" && typeof error.body.currentVersion === "number" ? error.body.currentVersion : undefined;
226
+ export async function addPrompt(ctx, ref, text, opts) {
227
+ await requireWrite(ctx);
228
+ const project = await resolveProject(ctx, ref);
229
+ const topicId = opts.topic ? await resolveTopic(ctx, project.projectId, opts.topic, false) : undefined;
230
+ const add = (expectedVersion) => ctx.client.callTool("add_prompt", {
231
+ projectId: project.projectId, text, expectedVersion, idempotencyKey: randomUUID(),
232
+ ...(topicId ? { topicId } : {}), ...(opts.country ? { country: opts.country } : {}),
233
+ });
234
+ let result;
235
+ try {
236
+ result = await add(0);
237
+ }
238
+ catch (error) {
239
+ // The same text was tracked before: restore it at the version the server reports.
240
+ const current = conflictVersion(error);
241
+ if (current === undefined)
242
+ throw error;
243
+ result = await add(current);
244
+ }
245
+ if (ctx.json)
246
+ return ctx.out(json(result));
247
+ const { prompt, outcome } = data(result);
248
+ ctx.out({
249
+ created: `Now tracking "${prompt.text}" (${prompt.promptId}). Its first answers arrive with the next daily check.`,
250
+ already_active: `Already tracking "${prompt.text}" (${prompt.promptId}).`,
251
+ restored: `Tracking "${prompt.text}" again (${prompt.promptId}), with its history.`,
252
+ }[outcome] ?? `Done: ${outcome} (${prompt.promptId}).`);
253
+ }
254
+ export async function removePrompt(ctx, ref, promptId) {
255
+ await requireWrite(ctx);
256
+ const { projectId } = await resolveProject(ctx, ref);
257
+ const remove = async () => {
258
+ const prompt = await findPrompt(ctx, projectId, promptId);
259
+ return ctx.client.callTool("remove_prompt", { projectId, promptId, expectedVersion: prompt.version, idempotencyKey: randomUUID() });
260
+ };
261
+ let result;
262
+ try {
263
+ result = await remove();
264
+ }
265
+ catch (error) {
266
+ if (conflictVersion(error) === undefined)
267
+ throw error;
268
+ result = await remove();
269
+ }
270
+ if (ctx.json)
271
+ return ctx.out(json(result));
272
+ const { prompt } = data(result);
273
+ ctx.out(`Stopped tracking "${prompt.text}". Its history is kept, and the slot is free.`);
274
+ }
275
+ export async function createTopic(ctx, ref, name) {
276
+ await requireWrite(ctx);
277
+ const { projectId } = await resolveProject(ctx, ref);
278
+ const result = await ctx.client.callTool("create_topic", { projectId, name, idempotencyKey: randomUUID() });
279
+ if (ctx.json)
280
+ return ctx.out(json(result));
281
+ const { topic, outcome } = data(result);
282
+ ctx.out(outcome === "already_exists" ? `A topic named "${topic.name}" already exists (${topic.topicId}).` : `Created the topic "${topic.name}" (${topic.topicId}).`);
283
+ }
284
+ export async function movePrompt(ctx, ref, promptId, topicRef) {
285
+ await requireWrite(ctx);
286
+ const { projectId } = await resolveProject(ctx, ref);
287
+ const topicId = await resolveTopic(ctx, projectId, topicRef, true);
288
+ const move = async () => {
289
+ const prompt = await findPrompt(ctx, projectId, promptId);
290
+ return ctx.client.callTool("move_prompt", { projectId, promptId, topicId, expectedTopicVersion: prompt.topicVersion, idempotencyKey: randomUUID() });
291
+ };
292
+ let result;
293
+ try {
294
+ result = await move();
295
+ }
296
+ catch (error) {
297
+ if (conflictVersion(error) === undefined)
298
+ throw error;
299
+ result = await move();
300
+ }
301
+ if (ctx.json)
302
+ return ctx.out(json(result));
303
+ const { prompt } = data(result);
304
+ ctx.out(prompt.topic ? `Moved "${prompt.text}" to ${prompt.topic.name}.` : `"${prompt.text}" is no longer in a topic.`);
305
+ }
306
+ // ── Tools ───────────────────────────────────────────────────────────────────────────────────────────────────────────
307
+ export async function tools(ctx) {
308
+ const list = await ctx.client.listTools();
309
+ if (ctx.json)
310
+ return ctx.out(json(list));
311
+ ctx.out(table(["TOOL", "ACCESS", "WHAT IT DOES"], list.map((t) => [t.name, t.annotations?.readOnlyHint ? "read" : "write", (t.description ?? "").split(/(?<=\.)\s/)[0] ?? ""]), [0, 0, 100]));
312
+ }
313
+ export async function call(ctx, name, argsJson) {
314
+ let args;
315
+ try {
316
+ args = argsJson === undefined ? {} : JSON.parse(argsJson);
317
+ }
318
+ catch {
319
+ throw new UsageError("The arguments must be a JSON object, for example '{\"projectId\":\"…\"}'.");
320
+ }
321
+ if (!args || typeof args !== "object" || Array.isArray(args))
322
+ throw new UsageError("The arguments must be a JSON object.");
323
+ ctx.out(json(await ctx.client.callTool(name, args)));
324
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,31 @@
1
+ /** Exit codes, stable for scripts: see README "Exit codes". */
2
+ export const EXIT = { ok: 0, failed: 1, usage: 2, signIn: 3 };
3
+ /** An error the CLI reports as one plain line on stderr, with an exit code. */
4
+ export class CliError extends Error {
5
+ exitCode;
6
+ details;
7
+ constructor(message, exitCode = EXIT.failed, details) {
8
+ super(message);
9
+ this.exitCode = exitCode;
10
+ this.details = details;
11
+ }
12
+ }
13
+ export class UsageError extends CliError {
14
+ constructor(message) {
15
+ super(message, EXIT.usage);
16
+ }
17
+ }
18
+ export class SignInRequired extends CliError {
19
+ constructor(message = "You're not signed in. Run `growthgenie login`.") {
20
+ super(message, EXIT.signIn);
21
+ }
22
+ }
23
+ export class ToolError extends CliError {
24
+ tool;
25
+ body;
26
+ constructor(tool, body) {
27
+ super(`${body.message} (${body.code}${body.requestId ? `, request ${body.requestId}` : ""})`, EXIT.failed, body);
28
+ this.tool = tool;
29
+ this.body = body;
30
+ }
31
+ }
package/dist/format.js ADDED
@@ -0,0 +1,28 @@
1
+ /** Plain-text output: aligned columns, no colour, safe to pipe. */
2
+ const width = (text) => [...text].length;
3
+ export function truncate(text, max) {
4
+ const chars = [...text.replace(/\s+/g, " ").trim()];
5
+ return chars.length <= max ? chars.join("") : `${chars.slice(0, Math.max(1, max - 1)).join("")}…`;
6
+ }
7
+ /** Columns padded to their widest cell; `max` caps a column (the rest of the text is cut with "…"). */
8
+ export function table(headers, rows, max = []) {
9
+ const cells = [headers, ...rows].map((row) => row.map((cell, i) => (max[i] ? truncate(cell, max[i]) : cell.replace(/\s+/g, " "))));
10
+ const widths = headers.map((_, i) => Math.max(...cells.map((row) => width(row[i] ?? ""))));
11
+ return cells
12
+ .map((row) => row.map((cell, i) => (i === row.length - 1 ? cell : cell + " ".repeat(widths[i] - width(cell)))).join(" ").trimEnd())
13
+ .join("\n");
14
+ }
15
+ const pad = (n) => String(n).padStart(2, "0");
16
+ /** `2026-11-20 07:02 UTC` for epoch milliseconds. */
17
+ export function utcTime(ms) {
18
+ if (typeof ms !== "number" || !Number.isFinite(ms))
19
+ return "—";
20
+ const d = new Date(ms);
21
+ return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`;
22
+ }
23
+ /** Today's UTC day, `YYYY-MM-DD`. */
24
+ export function utcDay(ms) {
25
+ const d = new Date(ms);
26
+ return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
27
+ }
28
+ export const json = (value) => JSON.stringify(value, null, 2);
package/dist/main.js ADDED
@@ -0,0 +1,224 @@
1
+ /** Argument parsing, help and dispatch for `growthgenie`. `cli.ts` is the executable; tests call `main` directly. */
2
+ import { spawn } from "node:child_process";
3
+ import { createInterface } from "node:readline";
4
+ import { parseArgs } from "node:util";
5
+ import { DEFAULT_RESOURCE, login, logout, WRITE_SCOPE } from "./auth.js";
6
+ import { McpClient } from "./client.js";
7
+ import * as commands from "./commands.js";
8
+ import { CliError, EXIT, SignInRequired, UsageError } from "./errors.js";
9
+ import { json, utcTime } from "./format.js";
10
+ import { configDir, Store } from "./store.js";
11
+ import { VERSION } from "./version.js";
12
+ export const HELP = `Growth Genie on the command line: your AI visibility, tracked prompts and the answers AI engines gave.
13
+
14
+ Usage: growthgenie <command> [arguments] [options]
15
+
16
+ Sign in
17
+ login [--write] [--no-browser] Sign in with your browser. --write also asks to add and stop prompts.
18
+ logout Sign out on this computer.
19
+ status Show this computer's sign-in and what it can do.
20
+
21
+ Read
22
+ projects [--workspace <id>] The projects you approved.
23
+ visibility <project> Today's AI visibility, per prompt and engine.
24
+ [--country <CC>] [--topic <topic>]
25
+ prompts <project> [--topic <topic>]
26
+ Tracked prompts and how much of the plan they use.
27
+ topics <project> Topics and how many prompts each has.
28
+ answer <project> <prompt-id> <engine> [--day <YYYY-MM-DD>] [--full]
29
+ What one engine answered, with the brands it named and its sources.
30
+
31
+ Change (sign in with --write)
32
+ add-prompt <project> <text> [--topic <topic>] [--country <CC>]
33
+ remove-prompt <project> <prompt-id>
34
+ create-topic <project> <name>
35
+ move-prompt <project> <prompt-id> <topic|none>
36
+
37
+ Any tool
38
+ tools The MCP tools your sign-in can use.
39
+ call <tool> [<json-arguments>] Call one tool and print its JSON result.
40
+
41
+ <project> is a project ID, domain (acme.com) or name. <topic> is a topic ID or name.
42
+ <engine> is chatgpt, claude, perplexity, ai-overviews or ai-mode.
43
+
44
+ Options
45
+ --json Print the result as JSON (any command).
46
+ --all Fetch every page of a list.
47
+ -h, --help Show help. -v, --version Show the version.
48
+
49
+ Exit codes: 0 done, 1 failed, 2 wrong usage, 3 sign-in needed.
50
+ Docs: https://docs.growthgenie.so/cli/`;
51
+ const OPTIONS = {
52
+ json: { type: "boolean" },
53
+ all: { type: "boolean" },
54
+ help: { type: "boolean", short: "h" },
55
+ version: { type: "boolean", short: "v" },
56
+ write: { type: "boolean" },
57
+ "no-browser": { type: "boolean" },
58
+ full: { type: "boolean" },
59
+ workspace: { type: "string" },
60
+ topic: { type: "string" },
61
+ country: { type: "string" },
62
+ day: { type: "string" },
63
+ };
64
+ const COMMANDS = {
65
+ login: { usage: "login [--write] [--no-browser]", args: [0, 0], options: ["write", "no-browser"], run: runLogin },
66
+ logout: { usage: "logout", args: [0, 0], options: [], run: runLogout },
67
+ status: { usage: "status", args: [0, 0], options: [], run: runStatus },
68
+ projects: { usage: "projects [--workspace <id>] [--all]", args: [0, 0], options: ["workspace", "all"],
69
+ run: (_, v, __, ctx) => commands.projects(ctx(), { workspace: v.workspace, all: !!v.all }) },
70
+ visibility: { usage: "visibility <project> [--country <CC>] [--topic <topic>] [--all]", args: [1, 1], options: ["country", "topic", "all"],
71
+ run: ([p], v, __, ctx) => commands.visibility(ctx(), p, { topic: v.topic, country: v.country ? commands.countryCode(v.country) : undefined, all: !!v.all }) },
72
+ prompts: { usage: "prompts <project> [--topic <topic>] [--all]", args: [1, 1], options: ["topic", "all"],
73
+ run: ([p], v, __, ctx) => commands.prompts(ctx(), p, { topic: v.topic, all: !!v.all }) },
74
+ topics: { usage: "topics <project>", args: [1, 1], options: [], run: ([p], _, __, ctx) => commands.topics(ctx(), p) },
75
+ answer: { usage: "answer <project> <prompt-id> <engine> [--day <YYYY-MM-DD>] [--full]", args: [3, 3], options: ["day", "full"],
76
+ run: ([p, prompt, engine], v, __, ctx) => {
77
+ commands.engineId(engine);
78
+ return commands.answer(ctx(), p, prompt, engine, { day: v.day ? commands.day(v.day) : undefined, full: !!v.full });
79
+ } },
80
+ "add-prompt": { usage: "add-prompt <project> <text> [--topic <topic>] [--country <CC>]", args: [2, 2], options: ["topic", "country"],
81
+ run: ([p, text], v, __, ctx) => commands.addPrompt(ctx(), p, text, { topic: v.topic, country: v.country ? commands.countryCode(v.country) : undefined }) },
82
+ "remove-prompt": { usage: "remove-prompt <project> <prompt-id>", args: [2, 2], options: [], run: ([p, id], _, __, ctx) => commands.removePrompt(ctx(), p, id) },
83
+ "create-topic": { usage: "create-topic <project> <name>", args: [2, 2], options: [], run: ([p, name], _, __, ctx) => commands.createTopic(ctx(), p, name) },
84
+ "move-prompt": { usage: "move-prompt <project> <prompt-id> <topic|none>", args: [3, 3], options: [],
85
+ run: ([p, id, topic], _, __, ctx) => commands.movePrompt(ctx(), p, id, topic) },
86
+ tools: { usage: "tools", args: [0, 0], options: [], run: (_, __, ___, ctx) => commands.tools(ctx()) },
87
+ call: { usage: "call <tool> [<json-arguments>]", args: [1, 2], options: [], run: ([tool, args], _, __, ctx) => commands.call(ctx(), tool, args) },
88
+ };
89
+ async function runLogin(_, values, deps) {
90
+ const store = new Store(deps.configDir);
91
+ const credentials = await login({
92
+ resource: deps.resource, write: !!values.write, store,
93
+ openBrowser: values["no-browser"] ? undefined : deps.openBrowser,
94
+ readPasted: deps.readPasted, log: deps.stderr,
95
+ }, deps);
96
+ const write = credentials.scope.split(" ").includes(WRITE_SCOPE);
97
+ if (values.json)
98
+ deps.stdout(json({ signedIn: true, scope: credentials.scope, accessTokenExpiresAt: new Date(credentials.expiresAt).toISOString() }));
99
+ else
100
+ deps.stdout(`Signed in. This computer can read your Growth Genie data${write ? " and add, stop and group prompts" : ""}.\nTry: growthgenie projects`);
101
+ }
102
+ async function runLogout(_, values, deps) {
103
+ const result = await logout(new Store(deps.configDir), deps);
104
+ if (values.json)
105
+ return deps.stdout(json(result));
106
+ if (!result.signedIn)
107
+ return deps.stdout("This computer wasn't signed in.");
108
+ deps.stdout(result.revoked ? "Signed out on this computer."
109
+ : "Signed out on this computer. Growth Genie didn't confirm the sign-in was revoked: to be sure, disconnect \"Growth Genie CLI\" in Growth Genie under Settings → Connected AI clients.");
110
+ }
111
+ async function runStatus(_, values, deps, ctx) {
112
+ const store = new Store(deps.configDir);
113
+ if (!(await store.read()))
114
+ throw new SignInRequired("Not signed in on this computer. Run `growthgenie login`.");
115
+ const context = ctx();
116
+ const credentials = await context.client.credentials();
117
+ const projects = await context.client.callTool("list_projects", { limit: 50 });
118
+ const page = projects.data;
119
+ const count = `${page.items.length}${page.hasMore ? "+" : ""}`;
120
+ const scopes = credentials.scope.split(" ");
121
+ if (values.json) {
122
+ return deps.stdout(json({ signedIn: true, server: credentials.resource, scopes, accessTokenExpiresAt: new Date(credentials.expiresAt).toISOString(), projects: count, file: store.file }));
123
+ }
124
+ deps.stdout([
125
+ `Signed in to ${new URL(credentials.resource).host} on this computer (${store.file}).`,
126
+ `Can ${scopes.includes(WRITE_SCOPE) ? "read, and add, stop and group prompts" : "read only (run `growthgenie login --write` to change prompts)"}.`,
127
+ `Sees ${count} project${count === "1" ? "" : "s"}. The access token renews itself; this one lasts until ${utcTime(credentials.expiresAt)}.`,
128
+ ].join("\n"));
129
+ }
130
+ function check(name, command, args, values) {
131
+ const [min, max] = command.args;
132
+ if (args.length < min || args.length > max)
133
+ throw new UsageError(`Usage: growthgenie ${command.usage}`);
134
+ for (const key of Object.keys(values)) {
135
+ if (["json", "help", "version"].includes(key) || command.options.includes(key))
136
+ continue;
137
+ throw new UsageError(`${name} doesn't take --${key}. Usage: growthgenie ${command.usage}`);
138
+ }
139
+ }
140
+ export async function main(argv, partial = {}) {
141
+ const deps = {
142
+ fetch: globalThis.fetch,
143
+ now: Date.now,
144
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
145
+ stdout: (text) => process.stdout.write(`${text}\n`),
146
+ stderr: (text) => process.stderr.write(`${text}\n`),
147
+ configDir: configDir(),
148
+ resource: DEFAULT_RESOURCE,
149
+ openBrowser,
150
+ readPasted: process.stdin.isTTY ? readLine : undefined,
151
+ ...partial,
152
+ };
153
+ try {
154
+ let parsed;
155
+ try {
156
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
157
+ }
158
+ catch (error) {
159
+ throw new UsageError(`${error.message.split("\n")[0]} Run \`growthgenie --help\`.`);
160
+ }
161
+ const values = parsed.values;
162
+ const [name, ...args] = parsed.positionals;
163
+ if (values.version) {
164
+ deps.stdout(VERSION);
165
+ return EXIT.ok;
166
+ }
167
+ if (!name || name === "help") {
168
+ (name || values.help ? deps.stdout : deps.stderr)(HELP);
169
+ return name || values.help ? EXIT.ok : EXIT.usage;
170
+ }
171
+ const command = COMMANDS[name];
172
+ if (!command)
173
+ throw new UsageError(`Unknown command "${name}". Run \`growthgenie --help\` for the list.`);
174
+ if (values.help) {
175
+ deps.stdout(`Usage: growthgenie ${command.usage}\n\nRun \`growthgenie --help\` for every command.`);
176
+ return EXIT.ok;
177
+ }
178
+ check(name, command, args, values);
179
+ let context;
180
+ const ctx = () => (context ??= { client: new McpClient(new Store(deps.configDir), deps), out: deps.stdout, json: !!values.json, now: deps.now });
181
+ const code = await command.run(args, values, deps, ctx);
182
+ return typeof code === "number" ? code : EXIT.ok;
183
+ }
184
+ catch (error) {
185
+ if (error instanceof CliError) {
186
+ deps.stderr(`growthgenie: ${error.message}`);
187
+ return error.exitCode;
188
+ }
189
+ deps.stderr(`growthgenie: ${error?.message ?? String(error)}`);
190
+ return EXIT.failed;
191
+ }
192
+ }
193
+ /** Opens `url` in the default browser without a shell, so nothing in the address is interpreted. */
194
+ function openBrowser(url) {
195
+ const [command, args] = process.platform === "darwin" ? ["open", [url]]
196
+ : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
197
+ : ["xdg-open", [url]];
198
+ return new Promise((resolve) => {
199
+ try {
200
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
201
+ child.once("error", () => resolve(false));
202
+ child.once("spawn", () => {
203
+ child.unref();
204
+ resolve(true);
205
+ });
206
+ }
207
+ catch {
208
+ resolve(false);
209
+ }
210
+ });
211
+ }
212
+ /** One line from the terminal, given up when `signal` aborts. */
213
+ function readLine(signal) {
214
+ return new Promise((resolve) => {
215
+ const rl = createInterface({ input: process.stdin, terminal: false });
216
+ const done = (value) => {
217
+ rl.close();
218
+ resolve(value);
219
+ };
220
+ signal.addEventListener("abort", () => done(undefined), { once: true });
221
+ rl.once("line", (line) => done(line));
222
+ rl.once("close", () => resolve(undefined));
223
+ });
224
+ }
package/dist/store.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Where the CLI keeps its sign-in: one JSON file, readable only by you (0600, in a 0700 directory). Refreshing rotates
3
+ * the refresh token, so two processes must never refresh at once: `withLock` serializes them across processes, and the
4
+ * caller re-reads the file inside the lock.
5
+ */
6
+ import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ import path from "node:path";
9
+ /** `$XDG_CONFIG_HOME/growthgenie`, `%APPDATA%\growthgenie` on Windows, else `~/.config/growthgenie`. */
10
+ export function configDir(env = process.env, platform = process.platform, home = homedir()) {
11
+ if (env.XDG_CONFIG_HOME)
12
+ return path.join(env.XDG_CONFIG_HOME, "growthgenie");
13
+ if (platform === "win32")
14
+ return path.join(env.APPDATA ?? path.join(home, "AppData", "Roaming"), "growthgenie");
15
+ return path.join(home, ".config", "growthgenie");
16
+ }
17
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
18
+ export class Store {
19
+ dir;
20
+ file;
21
+ lockFile;
22
+ constructor(dir) {
23
+ this.dir = dir;
24
+ this.file = path.join(dir, "cli.json");
25
+ this.lockFile = path.join(dir, "cli.json.lock");
26
+ }
27
+ async read() {
28
+ let text;
29
+ try {
30
+ text = await readFile(this.file, "utf8");
31
+ }
32
+ catch (error) {
33
+ if (error.code === "ENOENT")
34
+ return undefined;
35
+ throw error;
36
+ }
37
+ try {
38
+ const value = JSON.parse(text);
39
+ return typeof value.accessToken === "string" && typeof value.clientId === "string" && typeof value.tokenEndpoint === "string"
40
+ ? value : undefined;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ async write(credentials) {
47
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
48
+ const temp = `${this.file}.${process.pid}.tmp`;
49
+ await writeFile(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
50
+ await rename(temp, this.file);
51
+ }
52
+ async clear() {
53
+ await rm(this.file, { force: true });
54
+ }
55
+ /** Runs `fn` while holding a lock file; a lock older than `staleMs` is from a process that died and is taken over. */
56
+ async withLock(fn, { waitMs = 20_000, staleMs = 30_000 } = {}) {
57
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
58
+ const deadline = Date.now() + waitMs;
59
+ for (;;) {
60
+ try {
61
+ const handle = await open(this.lockFile, "wx", 0o600);
62
+ await handle.close();
63
+ break;
64
+ }
65
+ catch (error) {
66
+ if (error.code !== "EEXIST")
67
+ throw error;
68
+ const age = await stat(this.lockFile).then((s) => Date.now() - s.mtimeMs, () => 0);
69
+ if (age > staleMs)
70
+ await rm(this.lockFile, { force: true });
71
+ else if (Date.now() > deadline) {
72
+ throw new Error(`Another growthgenie command is signing in or refreshing (lock ${this.lockFile}).`, { cause: error });
73
+ }
74
+ else
75
+ await sleep(50);
76
+ }
77
+ }
78
+ try {
79
+ return await fn();
80
+ }
81
+ finally {
82
+ await rm(this.lockFile, { force: true });
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,3 @@
1
+ /** The package version (tests/cli.test.ts checks it matches package.json). */
2
+ export const VERSION = "0.1.0";
3
+ export const USER_AGENT = `growthgenie-cli/${VERSION} (node ${process.version}; ${process.platform})`;
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@growthgenie/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Growth Genie on the command line: read your AI visibility, prompts and AI answers, and manage tracked prompts. For people, scripts and agents.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://docs.growthgenie.so/cli/",
8
+ "keywords": [
9
+ "growth-genie",
10
+ "ai-visibility",
11
+ "ai-search",
12
+ "mcp",
13
+ "cli",
14
+ "seo",
15
+ "chatgpt",
16
+ "perplexity"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "bin": {
22
+ "growthgenie": "dist/cli.js"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "sideEffects": true,
30
+ "devDependencies": {
31
+ "@types/node": "24.13.3",
32
+ "eslint": "10.10.0",
33
+ "typescript": "6.0.3",
34
+ "vitest": "5.0.0",
35
+ "@growthwand/config": "0.0.0",
36
+ "@growthwand/contracts": "0.0.0"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.build.json",
43
+ "lint": "eslint .",
44
+ "typecheck": "tsc --noEmit",
45
+ "test": "vitest run"
46
+ }
6
47
  }