@votrix-ai/cli 0.0.0-stage → 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.
@@ -0,0 +1,373 @@
1
+ // Config, local state, the HTTP client, SSE, uploads/downloads and output.
2
+ // Everything a caller reads is one JSON object on stdout; people read stderr.
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { basename, dirname, extname, join, resolve } from "node:path";
7
+ import { Readable } from "node:stream";
8
+ import { pipeline } from "node:stream/promises";
9
+ import { fileURLToPath } from "node:url";
10
+ export const VERSION = "0.2.0";
11
+ export const MAX_UPLOAD_BYTES = 500 * 1024 * 1024;
12
+ // --- errors and output ----------------------------------------------------------
13
+ export class VotrixError extends Error {
14
+ kind;
15
+ fix;
16
+ exitCode;
17
+ constructor(kind, message, fix, exitCode = 1) {
18
+ super(message);
19
+ this.kind = kind;
20
+ this.fix = fix;
21
+ this.exitCode = exitCode;
22
+ }
23
+ }
24
+ export const usage = (message, fix) => new VotrixError("bad_input", message, fix, 2);
25
+ export function emit(value) {
26
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
27
+ }
28
+ export function note(text) {
29
+ process.stderr.write(clean(text) + "\n");
30
+ }
31
+ export function errorBody(error) {
32
+ if (error instanceof VotrixError) {
33
+ return { error: { type: error.kind, message: clean(error.message), ...(error.fix ? { fix: error.fix } : {}) } };
34
+ }
35
+ return { error: { type: "error", message: clean(String(error?.message ?? error)) } };
36
+ }
37
+ // Terminal escapes and control bytes never reach a terminal from server text.
38
+ export function clean(value) {
39
+ return String(value ?? "")
40
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
41
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")
42
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
43
+ }
44
+ function origin(value) {
45
+ const url = new URL(value.replace(/\/+$/, ""));
46
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
47
+ if (url.username || url.password || url.search || url.hash || (url.pathname !== "/" && url.pathname !== "")) {
48
+ throw usage("API URLs must be origins, such as https://api.example.com.");
49
+ }
50
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
51
+ throw usage("API URLs must use HTTPS; HTTP is allowed for local testing.");
52
+ }
53
+ return url.origin;
54
+ }
55
+ export function settings() {
56
+ const here = dirname(fileURLToPath(import.meta.url));
57
+ const file = [join(here, "..", "..", "production.json"), join(here, "..", "production.json")].find(existsSync);
58
+ const defaults = file ? JSON.parse(readFileSync(file, "utf8")) : {};
59
+ return {
60
+ backend: origin(process.env.VOTRIX_BACKEND_URL || defaults.backend),
61
+ auth: origin(process.env.VOTRIX_SUPABASE_URL || defaults.auth),
62
+ publicKey: process.env.VOTRIX_SUPABASE_KEY || defaults.public_key || "",
63
+ };
64
+ }
65
+ export function configRoot() {
66
+ if (process.env.VOTRIX_CONFIG_DIR)
67
+ return resolve(process.env.VOTRIX_CONFIG_DIR);
68
+ if (process.platform === "win32" && process.env.APPDATA)
69
+ return join(process.env.APPDATA, "votrix");
70
+ return join(homedir(), ".config", "votrix");
71
+ }
72
+ function writePrivate(path, text) {
73
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
74
+ const temp = join(dirname(path), `.votrix-${randomUUID()}`);
75
+ writeFileSync(temp, text, { mode: 0o600 });
76
+ renameSync(temp, path); // whole or not at all
77
+ }
78
+ export class State {
79
+ path;
80
+ constructor(cfg) {
81
+ const digest = createHash("sha256").update(`${cfg.backend}|${cfg.auth}`).digest("hex").slice(0, 16);
82
+ this.path = join(configRoot(), `${digest}.json`);
83
+ }
84
+ read() {
85
+ if (!existsSync(this.path))
86
+ return {};
87
+ try {
88
+ const data = JSON.parse(readFileSync(this.path, "utf8"));
89
+ if (data && typeof data === "object")
90
+ return data;
91
+ }
92
+ catch { /* fall through */ }
93
+ throw new VotrixError("error", `Cannot read login configuration: ${this.path}`);
94
+ }
95
+ write(data) { writePrivate(this.path, JSON.stringify(data)); }
96
+ update(values) { this.write({ ...this.read(), ...values }); }
97
+ clear() { if (existsSync(this.path))
98
+ unlinkSync(this.path); }
99
+ }
100
+ // A random id for this machine, kept across logins, so a new login replaces the
101
+ // device's earlier keys rather than piling them up.
102
+ export function deviceId() {
103
+ const path = join(configRoot(), "device_id");
104
+ if (existsSync(path)) {
105
+ const value = readFileSync(path, "utf8").trim();
106
+ if (/^[0-9a-f]{32}$/.test(value))
107
+ return value;
108
+ }
109
+ const value = randomUUID().replace(/-/g, "");
110
+ writePrivate(path, value + "\n");
111
+ return value;
112
+ }
113
+ const STATUS_KIND = {
114
+ 400: ["bad_input"], 401: ["unauthorized", "Run votrix login again, or check VOTRIX_API_KEY."],
115
+ 402: ["no_credits", "Top up the workspace; votrix credits shows the balance."],
116
+ 403: ["forbidden", "This key's scopes do not cover that employee, tool or endpoint."],
117
+ 404: ["not_found"], 409: ["busy"], 422: ["bad_input"],
118
+ };
119
+ export class ApiError extends VotrixError {
120
+ status;
121
+ constructor(status, message, fix, kind) {
122
+ super(kind ?? STATUS_KIND[status]?.[0] ?? "server", message, fix ?? STATUS_KIND[status]?.[1]);
123
+ this.status = status;
124
+ }
125
+ }
126
+ async function failure(response, secrets) {
127
+ let detail = `Request failed (${response.status})`;
128
+ try {
129
+ const body = await response.json();
130
+ detail = body?.detail ?? body?.msg ?? body?.error_description ?? body?.message ?? detail;
131
+ }
132
+ catch { /* not JSON */ }
133
+ let message = typeof detail === "object" ? detail.message ?? JSON.stringify(detail) : String(detail);
134
+ for (const secret of secrets)
135
+ if (secret)
136
+ message = message.split(secret).join("<redacted>");
137
+ const fix = typeof detail === "object" ? detail.fix : undefined;
138
+ const kind = typeof detail === "object" ? detail.type : undefined;
139
+ return new ApiError(response.status, clean(message).slice(0, 1200), fix, kind);
140
+ }
141
+ export class Client {
142
+ cfg;
143
+ state;
144
+ constructor(cfg = settings(), state) {
145
+ this.cfg = cfg;
146
+ this.state = state ?? new State(cfg);
147
+ }
148
+ // VOTRIX_API_KEY, VOTRIX_ACCESS_TOKEN, or this device's key for the workspace.
149
+ token(workspace) {
150
+ for (const name of ["VOTRIX_API_KEY", "VOTRIX_ACCESS_TOKEN"]) {
151
+ if (process.env[name])
152
+ return process.env[name];
153
+ }
154
+ const data = this.state.read();
155
+ const keys = data.api_keys ?? {};
156
+ const ids = Object.keys(keys);
157
+ if (!ids.length)
158
+ throw new VotrixError("unauthorized", "Run votrix login first.");
159
+ const chosen = workspace ?? data.workspace_id ?? (ids.length === 1 ? ids[0] : undefined);
160
+ if (!chosen) {
161
+ throw usage("You have several workspaces. Choose one with votrix workspace use <id>, or pass --workspace <id>.");
162
+ }
163
+ const entry = keys[chosen];
164
+ if (!entry?.key) {
165
+ throw new VotrixError("unauthorized", "This device has no key for that workspace.", "Run votrix login to get keys for every workspace you belong to.");
166
+ }
167
+ return entry.key;
168
+ }
169
+ rejected() {
170
+ for (const name of ["VOTRIX_API_KEY", "VOTRIX_ACCESS_TOKEN"]) {
171
+ if (process.env[name]) {
172
+ return new VotrixError("unauthorized", `${name} was rejected (expired, revoked, or invalid).`, "Update it and try again.");
173
+ }
174
+ }
175
+ return new VotrixError("unauthorized", "Your key was rejected: it expired or was revoked.", "Run votrix login again.");
176
+ }
177
+ async raw(method, url, options = {}) {
178
+ const headers = { "User-Agent": `votrix-cli/${VERSION}`, ...(options.headers ?? {}) };
179
+ if (options.auth)
180
+ headers.Authorization = `Bearer ${options.auth}`;
181
+ if (options.workspace)
182
+ headers["X-Workspace-Id"] = options.workspace;
183
+ if (options.body !== undefined)
184
+ headers["Content-Type"] = "application/json";
185
+ if (options.stream)
186
+ headers.Accept = "text/event-stream";
187
+ const controller = new AbortController();
188
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? (options.stream ? 90_000 : 60_000));
189
+ timer.unref(); // a finished command exits; it never waits on this
190
+ let response;
191
+ try {
192
+ response = await fetch(url, {
193
+ method, headers, redirect: "manual", signal: controller.signal,
194
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
195
+ });
196
+ }
197
+ catch {
198
+ clearTimeout(timer);
199
+ throw new VotrixError("network", "The connection failed or timed out. Check your network connection.");
200
+ }
201
+ if (!options.stream)
202
+ clearTimeout(timer);
203
+ if (response.status >= 400) {
204
+ clearTimeout(timer);
205
+ throw await failure(response, [options.auth ?? ""]);
206
+ }
207
+ return response;
208
+ }
209
+ async request(method, path, options = {}) {
210
+ let response;
211
+ try {
212
+ response = await this.raw(method, this.cfg.backend + path, { ...options, auth: this.token(options.workspace) });
213
+ }
214
+ catch (error) {
215
+ // A key does not refresh: 401 means it expired or was revoked.
216
+ if (error instanceof ApiError && error.status === 401)
217
+ throw this.rejected();
218
+ throw error;
219
+ }
220
+ if (options.stream)
221
+ return response;
222
+ const text = await response.text();
223
+ if (!text)
224
+ return null;
225
+ try {
226
+ return JSON.parse(text);
227
+ }
228
+ catch {
229
+ throw new VotrixError("server", "The server returned invalid JSON.");
230
+ }
231
+ }
232
+ currentKey(workspace) {
233
+ return this.request("GET", "/api-keys/current", { workspace });
234
+ }
235
+ // Save a backend file to `target`: a redirect to signed storage is followed
236
+ // without the key; anything else is the file itself.
237
+ async download(path, workspace, target) {
238
+ let response = await this.raw("GET", this.cfg.backend + path, {
239
+ workspace, auth: this.token(workspace), timeoutMs: 600_000,
240
+ }).catch((error) => {
241
+ if (error instanceof ApiError && error.status === 401)
242
+ throw this.rejected();
243
+ throw error;
244
+ });
245
+ if (response.status >= 300 && response.status < 400) {
246
+ const location = new URL(response.headers.get("location") ?? "", this.cfg.backend + path).toString();
247
+ if (!location.startsWith("https:") && !location.startsWith(this.cfg.backend)) {
248
+ throw new VotrixError("server", "The download redirect is not HTTPS.");
249
+ }
250
+ response = await this.raw("GET", location, { timeoutMs: 600_000 });
251
+ }
252
+ if (!response.body)
253
+ throw new VotrixError("network", "The download returned no body.");
254
+ mkdirSync(dirname(target), { recursive: true });
255
+ const part = `${target}.part`;
256
+ try {
257
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(part));
258
+ renameSync(part, target);
259
+ }
260
+ catch {
261
+ if (existsSync(part))
262
+ unlinkSync(part);
263
+ throw new VotrixError("network", `The download of ${basename(target)} was interrupted.`);
264
+ }
265
+ return target;
266
+ }
267
+ // Upload a local file to the workspace; -> its asset id. The bytes go to the
268
+ // signed URL the backend issues, without the key.
269
+ async upload(path, workspace) {
270
+ const info = statSync(path, { throwIfNoEntry: false });
271
+ if (!info?.isFile())
272
+ throw usage(`Not a file: ${path}`);
273
+ if (info.size > MAX_UPLOAD_BYTES)
274
+ throw usage(`${basename(path)} is over 500 MiB.`);
275
+ const filename = basename(path);
276
+ const mime = mimeOf(filename);
277
+ note(`Uploading ${filename} (${info.size} bytes)...`);
278
+ const ticket = await this.request("POST", "/files/upload-url", {
279
+ workspace, body: { filename, mime_type: mime, size_bytes: info.size },
280
+ });
281
+ const put = await fetch(ticket.upload_url, {
282
+ method: "PUT", redirect: "manual", duplex: "half", signal: AbortSignal.timeout(30 * 60_000),
283
+ headers: { "Content-Type": ticket.content_type ?? mime, "Content-Length": String(info.size) },
284
+ body: Readable.toWeb(createReadStream(path)),
285
+ }).catch(() => null);
286
+ if (!put || put.status >= 300)
287
+ throw new VotrixError("network", `Uploading ${filename} failed.`);
288
+ const asset = await this.request("POST", "/files/register", {
289
+ workspace, timeoutMs: 1_260_000, body: { storage_key: ticket.storage_key, filename, mime_type: mime },
290
+ });
291
+ return { id: asset.id, filename, size_bytes: info.size };
292
+ }
293
+ }
294
+ const MIME = {
295
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif",
296
+ ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".mp3": "audio/mpeg", ".wav": "audio/wav",
297
+ ".m4a": "audio/mp4", ".pdf": "application/pdf", ".txt": "text/plain", ".md": "text/markdown",
298
+ ".csv": "text/csv", ".json": "application/json", ".zip": "application/zip", ".html": "text/html",
299
+ };
300
+ export const mimeOf = (name) => MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
301
+ // --- SSE ------------------------------------------------------------------------
302
+ // JSON objects from an SSE body. An incomplete final frame is an error.
303
+ export async function* sse(response) {
304
+ if (!response.body)
305
+ return;
306
+ const decoder = new TextDecoder();
307
+ let buffer = "";
308
+ let data = [];
309
+ const reader = response.body.getReader();
310
+ try {
311
+ for (;;) {
312
+ let chunk;
313
+ try {
314
+ chunk = await reader.read();
315
+ }
316
+ catch {
317
+ throw new VotrixError("network", "The event stream was cut off.");
318
+ }
319
+ buffer += decoder.decode(chunk.value ?? new Uint8Array(), { stream: !chunk.done });
320
+ let match;
321
+ while ((match = buffer.match(/\r\n|\r|\n/)) !== null) {
322
+ const index = match.index;
323
+ if (buffer[index] === "\r" && index + 1 === buffer.length && !chunk.done)
324
+ break; // CRLF split
325
+ const line = buffer.slice(0, index).replace(/^/, "");
326
+ buffer = buffer.slice(index + match[0].length);
327
+ if (!line) {
328
+ if (data.length) {
329
+ let frame;
330
+ try {
331
+ frame = JSON.parse(data.join("\n"));
332
+ }
333
+ catch {
334
+ throw new VotrixError("server", "The event stream sent invalid JSON.");
335
+ }
336
+ if (frame && typeof frame === "object")
337
+ yield frame;
338
+ }
339
+ data = [];
340
+ }
341
+ else if (!line.startsWith(":")) {
342
+ const [field, ...rest] = line.split(":");
343
+ if (field === "data")
344
+ data.push(rest.join(":").replace(/^ /, ""));
345
+ }
346
+ }
347
+ if (chunk.done) {
348
+ if (data.length || (buffer && !buffer.startsWith(":"))) {
349
+ throw new VotrixError("network", "The event stream closed before the frame was complete.");
350
+ }
351
+ return;
352
+ }
353
+ }
354
+ }
355
+ finally {
356
+ reader.releaseLock();
357
+ }
358
+ }
359
+ // --- small helpers ----------------------------------------------------------------
360
+ export const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
361
+ export function uuidOf(value) {
362
+ const text = String(value ?? "").trim().toLowerCase();
363
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(text) ? text : undefined;
364
+ }
365
+ export function readStdin() {
366
+ return new Promise((done, fail) => {
367
+ let text = "";
368
+ process.stdin.setEncoding("utf8");
369
+ process.stdin.on("data", (chunk) => (text += chunk));
370
+ process.stdin.on("end", () => done(text));
371
+ process.stdin.on("error", fail);
372
+ });
373
+ }
@@ -0,0 +1,143 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { emit, readStdin, usage, VotrixError } from "./core.js";
3
+ const TOOLKITS = [
4
+ { slug: "gmail", name: "Gmail" },
5
+ { slug: "outlook", name: "Outlook" },
6
+ { slug: "googlesheets", name: "Google Sheets" },
7
+ { slug: "hubspot", name: "HubSpot" },
8
+ { slug: "googlecalendar", name: "Google Calendar" },
9
+ { slug: "calendly", name: "Calendly" },
10
+ { slug: "slack", name: "Slack" },
11
+ { slug: "google_search_console", name: "Google Search Console" },
12
+ { slug: "google_analytics", name: "Google Analytics 4" },
13
+ { slug: "semrush_mcp", name: "Semrush" },
14
+ { slug: "ahrefs_mcp", name: "Ahrefs" },
15
+ ];
16
+ const OPTIONS = {
17
+ toolkits: [],
18
+ connections: ["toolkit"],
19
+ link: ["no-browser", "no-wait"],
20
+ search: ["toolkits", "limit"],
21
+ execute: ["get-schema", "data", "account", "dry-run"],
22
+ };
23
+ const SHARED_FLAGS = ["workspace", "json"];
24
+ function option(ctx, name) {
25
+ const value = ctx.flags[name];
26
+ if (value === undefined)
27
+ return undefined;
28
+ if (typeof value !== "string" || !value.trim())
29
+ throw usage(`--${name} requires one value.`);
30
+ return value;
31
+ }
32
+ async function argumentsOf(input) {
33
+ if (input === undefined)
34
+ return {};
35
+ let value;
36
+ try {
37
+ const source = input === "-" ? await readStdin() : input.startsWith("@") ? readFileSync(input.slice(1), "utf8") : input;
38
+ value = JSON.parse(source);
39
+ }
40
+ catch {
41
+ throw usage("--data must contain a JSON object. Use inline JSON, @file, or - for stdin.");
42
+ }
43
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
44
+ throw usage("--data must contain a JSON object.");
45
+ }
46
+ return value;
47
+ }
48
+ function switchOn(ctx, name) {
49
+ const value = ctx.flags[name];
50
+ if (value === undefined)
51
+ return false;
52
+ if (value !== true)
53
+ throw usage(`--${name} is a switch.`);
54
+ return true;
55
+ }
56
+ function toolkit(value) {
57
+ if (!/^[a-z][a-z0-9_]*$/.test(value))
58
+ throw usage("Use lowercase toolkit slugs, such as gmail or google_analytics.");
59
+ return value;
60
+ }
61
+ export async function runIntegrations(ctx, command) {
62
+ if (!Object.hasOwn(OPTIONS, command))
63
+ throw usage(`Unknown integrations command '${command}'.`, "Run votrix tools integrations --help.");
64
+ for (const key of Object.keys(ctx.flags)) {
65
+ if (!SHARED_FLAGS.includes(key) && !OPTIONS[command].includes(key)) {
66
+ throw usage(`Unknown option --${key} for integrations ${command}.`, "Run votrix tools integrations --help.");
67
+ }
68
+ }
69
+ const [target] = ctx.positional;
70
+ const count = ctx.positional.length;
71
+ if (command === "search" ? count === 0 : count !== 1) {
72
+ throw usage(`Invalid arguments for integrations ${command}.`, "Run votrix tools integrations --help.");
73
+ }
74
+ if (command === "toolkits") {
75
+ if (target !== "list")
76
+ throw usage("Expected integrations toolkits list.", "Run votrix tools integrations --help.");
77
+ emit({ toolkits: TOOLKITS });
78
+ return 0;
79
+ }
80
+ const request = async (method, path, body) => {
81
+ return ctx.client.request(method, "/tools/integrations" + path, {
82
+ workspace: await ctx.workspace(), body, timeoutMs: 360_000,
83
+ });
84
+ };
85
+ if (command === "connections") {
86
+ if (target !== "list")
87
+ throw usage("Expected integrations connections list.", "Run votrix tools integrations --help.");
88
+ const app = option(ctx, "toolkit");
89
+ emit(await request("GET", app ? `?toolkit=${toolkit(app)}` : ""));
90
+ }
91
+ else if (command === "link") {
92
+ switchOn(ctx, "no-browser");
93
+ switchOn(ctx, "no-wait");
94
+ emit(await request("POST", "/connect", { app: toolkit(target) }));
95
+ }
96
+ else if (command === "search") {
97
+ const query = ctx.positional.join(" ").trim();
98
+ if (!query)
99
+ throw usage("Provide a search query.");
100
+ const toolkits = option(ctx, "toolkits")?.split(",").map((slug) => toolkit(slug.trim()));
101
+ const rawLimit = option(ctx, "limit");
102
+ const limit = rawLimit === undefined ? undefined : Number(rawLimit);
103
+ if (limit !== undefined && (!/^\d+$/.test(rawLimit) || limit < 1 || limit > 1000)) {
104
+ throw usage("--limit must be an integer from 1 to 1000.");
105
+ }
106
+ emit(await request("POST", "/search", { query, toolkits, limit }));
107
+ }
108
+ else {
109
+ if (!/^[A-Z][A-Z0-9_]*$/.test(target))
110
+ throw usage("ACTION must be an uppercase slug returned by search.");
111
+ const schema = switchOn(ctx, "get-schema");
112
+ const dryRun = switchOn(ctx, "dry-run");
113
+ if (schema) {
114
+ if (ctx.flags.data !== undefined || ctx.flags.account !== undefined || dryRun) {
115
+ throw usage("--get-schema cannot be combined with --data, --account or --dry-run.");
116
+ }
117
+ emit(await request("GET", `/actions/${target}/schema`));
118
+ }
119
+ else {
120
+ const account = option(ctx, "account");
121
+ const args = await argumentsOf(option(ctx, "data"));
122
+ const body = { arguments: args, account };
123
+ if (dryRun) {
124
+ const preview = await request("POST", `/actions/${target}/validate`, body);
125
+ emit(preview);
126
+ return preview?.ok === false || preview?.valid === false ? 1 : 0;
127
+ }
128
+ let result;
129
+ try {
130
+ result = await request("POST", `/actions/${target}/execute`, body);
131
+ }
132
+ catch (error) {
133
+ if (error instanceof VotrixError && error.kind === "network") {
134
+ throw new VotrixError("network", error.message, "The action may have run. Check the connected app before retrying.");
135
+ }
136
+ throw error;
137
+ }
138
+ emit(result);
139
+ return result?.ok === false ? 1 : 0;
140
+ }
141
+ }
142
+ return 0;
143
+ }