@votrix-ai/cli 0.0.0-stage → 0.2.1

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,170 @@
1
+ #!/usr/bin/env node
2
+ // votrix: hand work to Votrix employees and run Votrix tools. Built for other
3
+ // agents to call: one JSON object on stdout (errors too), progress on stderr,
4
+ // never a prompt. Exit codes: 0 answered, 1 failed, 2 bad usage.
5
+ import { realpathSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ import { runAgent } from "./agent.js";
8
+ import { login, logout, whoami, workspaces } from "./auth.js";
9
+ import { Client, emit, errorBody, usage, uuidOf, VERSION, VotrixError } from "./core.js";
10
+ import { runTools } from "./tools.js";
11
+ import { help, resolveCommand } from "./commands.js";
12
+ const BOOLEAN = new Set(["callback", "code-flow", "no-browser", "no-wait", "no-track", "draft", "json", "help", "logs", "get-schema", "dry-run"]);
13
+ export function parse(argv) {
14
+ const positional = [];
15
+ const flags = {};
16
+ const set = (name, value) => {
17
+ if (name in flags)
18
+ flags[name] = [].concat(flags[name], value);
19
+ else
20
+ flags[name] = value;
21
+ };
22
+ for (let i = 0; i < argv.length; i++) {
23
+ const token = argv[i];
24
+ if (token === "--") {
25
+ positional.push(...argv.slice(i + 1));
26
+ break;
27
+ }
28
+ if (token === "-d" && positional.slice(0, 3).join(" ") === "tools integrations execute") {
29
+ if (!argv[i + 1] || argv[i + 1].startsWith("--"))
30
+ throw usage("-d requires a JSON object, @file, or - for stdin.");
31
+ set("data", argv[++i]);
32
+ }
33
+ else if (token.startsWith("--") && token.length > 2) {
34
+ const [name, inline] = token.slice(2).split(/=(.*)/s);
35
+ if (inline !== undefined)
36
+ set(name, inline);
37
+ else if (BOOLEAN.has(name) || i + 1 >= argv.length || (argv[i + 1].startsWith("--") && argv[i + 1].length > 2))
38
+ set(name, true);
39
+ else
40
+ set(name, argv[++i]);
41
+ }
42
+ else {
43
+ positional.push(token);
44
+ }
45
+ }
46
+ return { positional, flags };
47
+ }
48
+ function context(client, positional, flags) {
49
+ let chosen;
50
+ return {
51
+ client, positional, flags,
52
+ async workspace() {
53
+ if (chosen)
54
+ return chosen;
55
+ const given = flags.workspace ?? process.env.VOTRIX_WORKSPACE_ID ?? client.state.read().workspace_id;
56
+ if (given) {
57
+ if (!uuidOf(given))
58
+ throw usage("--workspace must be a workspace id.");
59
+ return (chosen = uuidOf(given));
60
+ }
61
+ const rows = await workspaces(client);
62
+ if (rows.length === 1)
63
+ return (chosen = rows[0].id);
64
+ throw usage("You have several workspaces. Choose one with votrix workspace use <id>, or pass --workspace <id>.", rows.map((w) => `${w.display_name} ${w.id}`).join("; "));
65
+ },
66
+ };
67
+ }
68
+ export async function main(argv) {
69
+ const { positional, flags } = parse(argv);
70
+ const [command, ...rest] = positional;
71
+ if (flags.version && !command)
72
+ return process.stdout.write(VERSION + "\n"), 0;
73
+ const path = [...positional];
74
+ if (flags.help && path.slice(0, 3).join(" ") === "tools site tracking")
75
+ path[2] = "track";
76
+ const resolved = resolveCommand(path);
77
+ if (resolved.command.usage === undefined && resolved.depth < path.length) {
78
+ throw usage(`Unknown command '${path.slice(0, resolved.depth + 1).join(" ")}'.`, help(resolved.command));
79
+ }
80
+ if (flags.help || resolved.command.usage === undefined) {
81
+ process.stdout.write(help(resolved.command) + "\n");
82
+ return flags.help ? 0 : 2;
83
+ }
84
+ const client = new Client();
85
+ const ctx = context(client, rest, flags);
86
+ switch (command) {
87
+ case "login":
88
+ for (const name of ["code", "key"]) {
89
+ if (flags[name] === true)
90
+ throw usage(`--${name} needs a value.`);
91
+ }
92
+ emit(await login(client, { noBrowser: flags["no-browser"], port: flags.port ? Number(flags.port) : undefined,
93
+ timeout: flags.timeout ? Number(flags.timeout) : undefined, code: flags.code, key: flags.key,
94
+ callback: flags.callback, codeFlow: flags["code-flow"],
95
+ // A person at a terminal pastes the code here; an agent gets the link and runs --code later.
96
+ interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY) }));
97
+ return 0;
98
+ case "logout":
99
+ emit(await logout(client));
100
+ return 0;
101
+ case "whoami": {
102
+ if (process.env.VOTRIX_API_KEY)
103
+ return emit(await whoami(client)), 0;
104
+ let workspace;
105
+ try {
106
+ workspace = await ctx.workspace();
107
+ }
108
+ catch (error) {
109
+ // Signed in to several workspaces and none chosen: say who and where, not an error.
110
+ if (!(error instanceof VotrixError) || error.kind !== "bad_input")
111
+ throw error;
112
+ emit({ ...(client.state.read().user ?? {}), workspace_id: null, workspaces: await workspaces(client),
113
+ next: "votrix workspace use <id>, or pass --workspace <id>." });
114
+ return 0;
115
+ }
116
+ emit(await whoami(client, workspace));
117
+ return 0;
118
+ }
119
+ case "workspaces":
120
+ emit({ workspaces: await workspaces(client) });
121
+ return 0;
122
+ case "credits": {
123
+ const workspace = await ctx.workspace();
124
+ const { balance, entries } = await client.request("GET", "/billing/balance", { workspace });
125
+ emit({ workspace_id: workspace, balance, recent: (entries ?? []).slice(0, 10) });
126
+ return 0;
127
+ }
128
+ case "workspace": {
129
+ if (rest[0] !== "use" || !uuidOf(rest[1]))
130
+ throw usage("Usage: votrix workspace use <workspace-id>");
131
+ const id = uuidOf(rest[1]);
132
+ if (!(await workspaces(client)).some((w) => w.id === id)) {
133
+ throw new VotrixError("not_found", "This credential cannot act in that workspace.", "Run votrix login to refresh your workspaces.");
134
+ }
135
+ client.state.update({ workspace_id: id });
136
+ emit({ workspace_id: id });
137
+ return 0;
138
+ }
139
+ case "agent": {
140
+ return runAgent({ ...ctx, positional: rest.slice(1) }, rest[0]);
141
+ }
142
+ case "tools": {
143
+ const [group, action] = rest;
144
+ // Integrations consumes the target (including "list") in its handler.
145
+ const nested = resolved.depth === 4 && group !== "integrations";
146
+ const sub = nested ? rest[2] : undefined;
147
+ return runTools({ ...ctx, positional: rest.slice(nested ? 3 : 2) }, group, action, sub);
148
+ }
149
+ }
150
+ throw usage(`Unknown command '${command}'.`, "votrix --help lists the commands.");
151
+ }
152
+ function invokedDirectly() {
153
+ try {
154
+ return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
155
+ }
156
+ catch {
157
+ return false;
158
+ }
159
+ }
160
+ const invoked = invokedDirectly();
161
+ if (invoked || process.env.VOTRIX_CLI_MAIN) {
162
+ process.on("SIGINT", () => {
163
+ process.stderr.write("\nStopped waiting. Work already started keeps going on Votrix; votrix agent get / votrix tools runs get picks it up.\n");
164
+ process.exit(130);
165
+ });
166
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (error) => {
167
+ emit(errorBody(error));
168
+ process.exitCode = error instanceof VotrixError ? error.exitCode : 1;
169
+ });
170
+ }
@@ -0,0 +1,116 @@
1
+ export const commands = new Map();
2
+ function group(path, description) {
3
+ commands.set(path, { path, description });
4
+ }
5
+ function leaf(path, usage, description, result, example = "") {
6
+ commands.set(path, { path, usage, description, result, example });
7
+ }
8
+ group("", "Votrix accounts, employees and tools");
9
+ leaf("login", "[--no-browser] [--port N] [--timeout S]\n votrix login --key vtx_...", "Sign in with Google in a browser on this computer (default port 8765, timeout 180 seconds); saves a key for each of your workspaces. On a server or remote machine, create a CLI key for a workspace in the Votrix App and save it with --key.", "The account and its workspaces, or the workspace of the saved key.", "--key vtx_...");
10
+ leaf("logout", "", "Revoke the saved device keys.", "Logout result.");
11
+ leaf("whoami", "", "Show the current identity and workspace.", "Account and credential metadata; with several workspaces and none chosen, the workspaces and how to choose one.");
12
+ leaf("workspaces", "", "List available workspaces.", "workspaces array.");
13
+ group("workspace", "Select the default workspace.");
14
+ leaf("workspace use", "ID", "Select a workspace by ID.", "workspace_id.", "WORKSPACE_ID");
15
+ leaf("credits", "", "Check workspace credit usage.", "balance and recent charges.");
16
+ group("agent", "Delegate tasks to Votrix employees.");
17
+ leaf("agent ls", "", "List available employees.", "Employee identifiers and roles.");
18
+ leaf("agent ask", "EMPLOYEE TASK|- [--file PATH|ID ...] [--session ID] [--out DIR] [--no-wait]", "Send a task and wait by default.", "Session ID and, after completion, reply and presented files.", 'rebecca "Review this brief" --file brief.pdf');
19
+ leaf("agent wait", "SESSION [--out DIR]", "Wait for the latest task.", "Session status, reply and presented files.", "SESSION_ID");
20
+ leaf("agent sessions", "[--employee NAME] [--limit N] [--before UPDATED_AT]", "List recent conversations.", "Session records.");
21
+ leaf("agent get", "SESSION", "Inspect a session without waiting.", "Session status.", "SESSION_ID");
22
+ leaf("agent files", "SESSION", "List output files.", "File metadata.", "SESSION_ID");
23
+ leaf("agent pull", "ASSET ... [--out DIR]", "Download output assets.", "Downloaded files and paths.", "ASSET_ID --out ./out");
24
+ leaf("agent history", "SESSION [--limit N] [--before SEQ]", "Read messages and presented files.", "History rows and pagination.", "SESSION_ID");
25
+ leaf("agent stop", "SESSION", "Interrupt a running session.", "Session and interruption result.", "SESSION_ID");
26
+ group("tools", "Run tools directly in a workspace.");
27
+ export const categories = ["media", "seo", "scraper", "ui"];
28
+ const descriptions = ["Generate media.", "Query SEO datasets.", "Collect data from supported sources.", "Run UI design tools."];
29
+ const examples = ["seedance", "keyword_metrics", "reddit-posts", "design"];
30
+ for (const [index, category] of categories.entries()) {
31
+ const path = `tools ${category}`;
32
+ group(path, descriptions[index]);
33
+ leaf(path + " list", "", "Discover available tools.", "Current catalog.");
34
+ leaf(path + " explore", "NAME [--mode MODE]", "Inspect supported parameters, outputs and price.", "Tool description and parameter schema.", examples[index]);
35
+ leaf(path + " run", "NAME [--mode MODE] [--input JSON|@FILE] [--PARAM VALUE ...] [--max-credits N] [--out DIR] [--no-wait]", "Run a tool. Explore its inputs first: explore shows credits at default settings. --max-credits refuses a run estimated above N credits, or one that cannot be priced. Waits by default.", "Run ID, status, estimate_credits, credits charged, and results or files.", examples[index] + " --input @input.json");
36
+ }
37
+ group("tools runs", "Inspect and manage tool runs.");
38
+ leaf("tools runs list", "[--category NAME] [--limit N]", "List recent runs (default limit 20).", "Run records.");
39
+ leaf("tools runs get", "ID [--out DIR] [--no-wait]", "Wait for a run or return its current state.", "Run status and available outputs.", "RUN_ID --no-wait");
40
+ leaf("tools runs stop", "ID", "Stop a run.", "Run status.", "RUN_ID");
41
+ group("tools files", "Upload, download and publish workspace files.");
42
+ leaf("tools files upload", "PATH ...", "Upload local files privately.", "Asset IDs and file metadata.", "./brief.pdf");
43
+ leaf("tools files get", "ASSET", "Inspect file metadata.", "File record.", "ASSET_ID");
44
+ leaf("tools files pull", "ASSET ... [--out DIR]", "Download workspace assets.", "Local paths.", "ASSET_ID --out ./out");
45
+ leaf("tools files publish", "ASSET|PATH --name NAME", "Publish a file at a permanent public URL.", "Publication information.", "./brief.pdf --name brief");
46
+ leaf("tools files library", "[--query TEXT] [--mime-group GROUP ...] [--before CURSOR] [--limit N]", "Search saved workspace files. Default limit 50.", "Matching file records.", "--query brief");
47
+ group("tools social", "Manage social accounts and posts.");
48
+ leaf("tools social accounts", "[--platform NAME]", "List connected social accounts.", "accounts array.");
49
+ group("tools social posts", "Draft, schedule and inspect posts.");
50
+ const postFlags = "[--file JSON_FILE|-] [--account ID ...] [--caption TEXT|--caption-file FILE] [--media URL|PATH|ASSET ...] [--thumbnail X] [--title TEXT] [--schedule-at TIME|--draft]";
51
+ leaf("tools social posts create", postFlags, "Create posts from a JSON file or account and content flags.", "Created post records.", '--account ACCOUNT_ID --caption "Launch day" --draft');
52
+ leaf("tools social posts update", "ID " + postFlags, "Update a post.", "Updated post record.", "POST_ID --file post.json");
53
+ leaf("tools social posts list", "[--account ID ...] [--status STATUS ...] [--limit N] [--offset N]", "List posts (default limit 50, offset 0).", "Post records.");
54
+ for (const [action, description, result] of [["get", "Inspect a post.", "Post record."], ["results", "Read publication results.", "Platform results."], ["cancel", "Cancel a post.", "Cancellation result."]]) {
55
+ leaf("tools social posts " + action, "ID", description, result, "POST_ID");
56
+ }
57
+ group("tools site", "Deploy websites and inspect visitor analytics.");
58
+ leaf("tools site list", "", "List workspace sites.", "Sites, addresses and live versions.");
59
+ leaf("tools site deploy", "DIR|ZIP --name SITE [--address SUB] [--no-track] [--no-wait]\n votrix tools site deploy --asset ID --name SITE [--no-track] [--no-wait]\n votrix tools site deploy --name SITE --version N [--no-wait]", "Deploy a version or restore an earlier one. Waits by default.", "Site, version, deployment status and available tracking metadata.", "./website --name my-site");
60
+ leaf("tools site versions", "SITE", "List deployment versions.", "Version history and live version.", "my-site");
61
+ leaf("tools site status", "SITE [--version N] [--logs]", "Inspect deployment progress.", "Deployment status and optional logs.", "my-site");
62
+ group("tools site env", "Manage site environment variables.");
63
+ leaf("tools site env list", "SITE", "List environment variable names.", "Variable names.", "my-site");
64
+ leaf("tools site env set", "SITE --from-file FILE|- [--target production|preview|all]", "Read KEY=VALUE lines from file or stdin. Default target is all.", "Environment update result.", "my-site --from-file site.env");
65
+ group("tools site domain", "Connect a domain and check its DNS.");
66
+ for (const action of ["add", "status"])
67
+ leaf("tools site domain " + action, "SITE DOMAIN", action === "add" ? "Connect a custom domain." : "Check domain status.", "Domain status and DNS information.", "my-site example.com");
68
+ group("tools site track", "Measure visits, clicks and outcomes on a Votrix site.");
69
+ for (const action of ["enable", "disable"])
70
+ leaf("tools site track " + action, "SITE", action === "enable" ? "Enable or upgrade visitor tracking." : "Disable visitor tracking.", "Tracking state and changed flag. A change may redeploy the live version.", "my-site");
71
+ const filters = "[--period 7d|30d|90d] [--by FIELD] [--where FIELD=VALUE[,VALUE...] ...]";
72
+ leaf("tools site track events", "SITE " + filters + " [--event NAME] [--search TEXT] [--limit N]", "Discover recorded names or group events. Defaults to 30d, grouped by name, limit 50 (max 200). Grouping by another field defaults to visit.", "data_status and rows with visitors and event count.", "my-site --by source");
73
+ leaf("tools site track funnel", "SITE --steps NAME,NAME[,NAME...] " + filters + " [--window 1h|1d|7d|30d]", "Count distinct browsers completing 2-5 steps in order. Defaults to period 30d and window 7d. Filters and grouping apply to the first step.", "data_status and steps (or groups) with visitors, of_previous_percent and of_first_percent.", "my-site --steps visit,login,signup_completed --where source=utm:instagram");
74
+ group("tools integrations", "Connect external apps such as Outlook or GA4 and run their actions.");
75
+ group("tools integrations toolkits", "Discover supported apps.");
76
+ leaf("tools integrations toolkits list", "", "List supported apps offline.", "toolkits with name and slug.");
77
+ leaf("tools integrations connections", "[list] [--toolkit APP]", "List the workspace's connected accounts.", "apps with toolkit, accounts and status. Pass an account_id to execute --account.", "--toolkit outlook");
78
+ leaf("tools integrations link", "APP [--no-browser] [--no-wait]", "Request the hosted OAuth URL. Open the returned URL to authorize.", "app, url, status, account_id and expires_at.", "outlook");
79
+ leaf("tools integrations search", "QUERY [--toolkit APP] [--limit N]", "Search the live action catalog. Default limit 20.", "actions and needs_connection.", '"read my Gmail profile" --toolkit gmail');
80
+ leaf("tools integrations execute", "ACTION --get-schema\n votrix tools integrations execute ACTION [-d|--data JSON|@FILE|-] [--account ID] [--dry-run]", "Inspect the live schema, validate arguments or execute the action. Data defaults to {}.", "Schema mode returns parameters (name, type, required, description), rules that span parameters, and the raw input_schema. Dry-run checks the arguments and the account the action would run as, and returns valid and account. Execution returns ok, action and data or error.", "GMAIL_GET_PROFILE --get-schema");
81
+ export function children(path) {
82
+ return [...commands.values()].filter(c => c.path && c.path.split(" ").slice(0, -1).join(" ") === path);
83
+ }
84
+ export function resolveCommand(words) {
85
+ let command = commands.get("");
86
+ let depth = 0;
87
+ while (depth < words.length && command.usage === undefined) {
88
+ const next = commands.get(words.slice(0, depth + 1).join(" "));
89
+ if (!next)
90
+ break;
91
+ command = next;
92
+ depth++;
93
+ }
94
+ return { command, depth };
95
+ }
96
+ export function help(command) {
97
+ const prefix = ("votrix " + command.path).trim();
98
+ const lines = [prefix + " — " + command.description, ""];
99
+ if (command.usage === undefined) {
100
+ for (const child of children(command.path)) {
101
+ lines.push(" " + child.path.padEnd(32) + " " + child.description);
102
+ }
103
+ if (command.path === "tools site track")
104
+ lines.push("", 'New deployments request tracking by default. Names use 1-40 lowercase letters, digits or underscores. Label clicks with data-track="login". Record a confirmed outcome with window.votrix.track("signup_completed").');
105
+ lines.push("", "Run " + prefix + " COMMAND --help for details.");
106
+ }
107
+ else {
108
+ lines.push("Usage", (" " + prefix + " " + command.usage).trimEnd(), "", "Returns " + command.result, "", "Example", (" " + prefix + " " + command.example).trimEnd());
109
+ }
110
+ if (["tools site track events", "tools site track funnel"].includes(command.path)) {
111
+ lines.push("", "Fields: source, campaign, medium, content, page, device, browser, os, country, city, day and name. Funnel grouping excludes name. Repeat --where to combine filters.");
112
+ }
113
+ if (!command.path)
114
+ lines.push("Use --workspace ID to select a workspace. VOTRIX_API_KEY supplies a saved API credential.");
115
+ return lines.join("\n");
116
+ }
@@ -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.1";
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
+ }