@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.
- package/README.md +192 -2
- package/SITE-TRACKING-CLI-DESIGN.md +117 -0
- package/dist/src/agent.js +366 -0
- package/dist/src/auth.js +283 -0
- package/dist/src/cli.js +170 -0
- package/dist/src/commands.js +116 -0
- package/dist/src/core.js +373 -0
- package/dist/src/integrations.js +156 -0
- package/dist/src/site.js +278 -0
- package/dist/src/tools.js +289 -0
- package/dist/src/zip.js +112 -0
- package/docs/API.md +98 -0
- package/docs/cli/account.md +77 -0
- package/docs/cli/agent.md +105 -0
- package/docs/cli/files.md +65 -0
- package/docs/cli/integrations.md +67 -0
- package/docs/cli/media.md +45 -0
- package/docs/cli/runs.md +44 -0
- package/docs/cli/scraper.md +45 -0
- package/docs/cli/seo.md +45 -0
- package/docs/cli/site.md +137 -0
- package/docs/cli/social.md +85 -0
- package/docs/cli/ui.md +45 -0
- package/package.json +30 -4
- package/production.json +5 -0
- package/skills/votrix/SKILL.md +97 -0
- package/skills/votrix/agents/openai.yaml +4 -0
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// `votrix agent`: hand work to a Votrix employee, wait until the whole session is
|
|
2
|
+
// done (its turns, subagents and background jobs), collect what it made.
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { basename, join, resolve } from "node:path";
|
|
5
|
+
import { clean, emit, note, readStdin, sleep, sse, usage, uuidOf, VotrixError } from "./core.js";
|
|
6
|
+
import { unzipTo } from "./zip.js";
|
|
7
|
+
const PRESENT = new Set(["present_file", "present_project"]);
|
|
8
|
+
const DONE = new Set(["idle", "failed"]);
|
|
9
|
+
const BUNDLE = /^(.+?)\.(website|video)\.zip$/i;
|
|
10
|
+
const STREAM_TIMEOUT_MS = 30_000;
|
|
11
|
+
const SEND_TIMEOUT_MS = 600_000;
|
|
12
|
+
const seqOf = (row) => (Number.isInteger(row?.seq) ? row.seq : 0);
|
|
13
|
+
const isMain = (row) => !row?.session_thread_id;
|
|
14
|
+
export function fileCard(row) {
|
|
15
|
+
const name = row.filename ?? row.id;
|
|
16
|
+
const bundle = BUNDLE.exec(name ?? "");
|
|
17
|
+
return {
|
|
18
|
+
asset_id: row.id, filename: name, kind: bundle ? bundle[2].toLowerCase() : "file",
|
|
19
|
+
mime_type: row.mime_type ?? null, size_bytes: row.size_bytes ?? null,
|
|
20
|
+
created_at: row.created_at ?? null,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
// Asset ids a frame shows the employee handing over (present_file / present_project).
|
|
24
|
+
export function presentedIds(frame) {
|
|
25
|
+
if (!["tool_call", "tool_final_result"].includes(frame?.type) || frame.status === "error" || !PRESENT.has(frame.name))
|
|
26
|
+
return [];
|
|
27
|
+
try {
|
|
28
|
+
const output = JSON.parse(frame.output ?? "");
|
|
29
|
+
return output?.asset_id ? [output.asset_id] : [];
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// A website or video project comes as `<slug>.website.zip`; it is also unpacked
|
|
36
|
+
// beside the zip, into `<slug>/` (`folder` in the answer).
|
|
37
|
+
export async function downloadCard(ctx, card, out, name = basename(card.filename ?? card.asset_id)) {
|
|
38
|
+
note(`Downloading ${name}...`);
|
|
39
|
+
const target = await ctx.client.download(`/files/${encodeURIComponent(card.asset_id)}/download`, await ctx.workspace(), join(resolve(out), name));
|
|
40
|
+
const bundle = BUNDLE.exec(name);
|
|
41
|
+
if (!bundle)
|
|
42
|
+
return { ...card, path: target };
|
|
43
|
+
const folder = join(resolve(out), bundle[1]);
|
|
44
|
+
const files = unzipTo(target, folder);
|
|
45
|
+
note(`Unpacked ${files} files into ${folder}`);
|
|
46
|
+
return { ...card, path: target, folder };
|
|
47
|
+
}
|
|
48
|
+
// Download several files into `out`. Two with one name (from different folders
|
|
49
|
+
// in the sandbox) are kept apart locally as name, name-2, name-3...
|
|
50
|
+
export async function downloadCards(ctx, cards, out) {
|
|
51
|
+
const taken = new Set();
|
|
52
|
+
const names = cards.map((card) => {
|
|
53
|
+
const base = basename(card.filename ?? card.asset_id);
|
|
54
|
+
const dot = base.lastIndexOf(".") > 0 ? base.lastIndexOf(".") : base.length;
|
|
55
|
+
let name = base;
|
|
56
|
+
for (let n = 2; taken.has(name.toLowerCase()); n++)
|
|
57
|
+
name = `${base.slice(0, dot)}-${n}${base.slice(dot)}`;
|
|
58
|
+
taken.add(name.toLowerCase());
|
|
59
|
+
return name;
|
|
60
|
+
});
|
|
61
|
+
return Promise.all(cards.map((card, i) => downloadCard(ctx, card, out, names[i])));
|
|
62
|
+
}
|
|
63
|
+
class Agent {
|
|
64
|
+
ctx;
|
|
65
|
+
lastStatus = null;
|
|
66
|
+
constructor(ctx) {
|
|
67
|
+
this.ctx = ctx;
|
|
68
|
+
}
|
|
69
|
+
call(method, path, body, extra = {}) {
|
|
70
|
+
return this.ctx.workspace().then((workspace) => this.ctx.client.request(method, path, { workspace, body, ...extra }));
|
|
71
|
+
}
|
|
72
|
+
async employees() { return this.call("GET", "/employees"); }
|
|
73
|
+
async resolve(name) {
|
|
74
|
+
const rows = await this.employees();
|
|
75
|
+
const wanted = name.trim().toLowerCase();
|
|
76
|
+
for (const field of ["id", "slug", "display_name"]) {
|
|
77
|
+
const hits = rows.filter((row) => String(row[field] ?? "").toLowerCase() === wanted);
|
|
78
|
+
if (hits.length === 1)
|
|
79
|
+
return hits[0];
|
|
80
|
+
}
|
|
81
|
+
throw new VotrixError("not_found", `No employee called '${name}'.`, "votrix agent ls lists them: " + rows.map((r) => `${r.display_name} (${r.slug})`).join(", "));
|
|
82
|
+
}
|
|
83
|
+
async outputs(session) {
|
|
84
|
+
const listing = await this.call("GET", `/sessions/${session}/files/list`);
|
|
85
|
+
return (listing.files ?? []).filter((row) => row.origin === "output").map(fileCard);
|
|
86
|
+
}
|
|
87
|
+
async status(session) {
|
|
88
|
+
this.lastStatus = await this.call("GET", `/sessions/${session}/status`);
|
|
89
|
+
return this.lastStatus;
|
|
90
|
+
}
|
|
91
|
+
// Read the session from `after` until it is done: a session-level idle that
|
|
92
|
+
// /status confirms. A quiet stream timing out is a poll, not a failure.
|
|
93
|
+
async *follow(session, after, first) {
|
|
94
|
+
let cursor = after, failures = 0, response = first;
|
|
95
|
+
for (;;) {
|
|
96
|
+
try {
|
|
97
|
+
response ??= await this.call("GET", `/sessions/${session}/events/stream?after_seq=${cursor}`, undefined, { stream: true, timeoutMs: STREAM_TIMEOUT_MS });
|
|
98
|
+
for await (const frame of sse(response)) {
|
|
99
|
+
if (frame.kind === "delta")
|
|
100
|
+
continue;
|
|
101
|
+
if (seqOf(frame) <= cursor && frame.type !== "user_message")
|
|
102
|
+
continue;
|
|
103
|
+
cursor = Math.max(cursor, seqOf(frame));
|
|
104
|
+
yield frame;
|
|
105
|
+
if (frame.type === "session_status" && frame.status === "idle" && DONE.has((await this.status(session)).state))
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!(error instanceof VotrixError) || error.kind !== "network")
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
response = undefined;
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
const state = (await this.status(session)).state;
|
|
118
|
+
failures = 0;
|
|
119
|
+
if (DONE.has(state))
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (!(error instanceof VotrixError) || error.kind !== "network" || ++failures > 5)
|
|
124
|
+
throw error;
|
|
125
|
+
await sleep(Math.min(2 ** failures, 10) * 1000);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
describe(frame) {
|
|
130
|
+
const who = isMain(frame) ? "" : "[subagent] ";
|
|
131
|
+
switch (frame.type) {
|
|
132
|
+
case "tool_start": return `${who}${frame.label ?? frame.name}...`;
|
|
133
|
+
case "thread_created": return `Started a subagent: ${frame.label ?? frame.agent_name}`;
|
|
134
|
+
case "job_result": return "A background job finished; the employee is continuing";
|
|
135
|
+
case "error": return `Error: ${frame.message ?? ""}`;
|
|
136
|
+
case "ai_message": {
|
|
137
|
+
if (!isMain(frame) || !String(frame.text ?? "").trim())
|
|
138
|
+
return undefined;
|
|
139
|
+
const text = frame.text.split(/\s+/).join(" ");
|
|
140
|
+
return "Replied: " + (text.length > 160 ? text.slice(0, 160) + "..." : text);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
// `frames` are this turn's only: what it said last and what it handed over.
|
|
146
|
+
async result(session, employee, frames, status, out) {
|
|
147
|
+
let reply = null;
|
|
148
|
+
const presented = [], errors = [];
|
|
149
|
+
for (const frame of frames) {
|
|
150
|
+
if (frame.type === "ai_message" && isMain(frame) && String(frame.text ?? "").trim())
|
|
151
|
+
reply = frame.text;
|
|
152
|
+
else if (frame.type === "error")
|
|
153
|
+
errors.push(clean(frame.message ?? ""));
|
|
154
|
+
for (const id of presentedIds(frame))
|
|
155
|
+
if (!presented.includes(id))
|
|
156
|
+
presented.push(id);
|
|
157
|
+
}
|
|
158
|
+
let cards = await Promise.all(presented.map((id) => this.call("GET", `/files/${id}`).then(fileCard)));
|
|
159
|
+
if (out)
|
|
160
|
+
cards = await downloadCards(this.ctx, cards, out);
|
|
161
|
+
const folders = cards.map((card) => card.folder).filter(Boolean);
|
|
162
|
+
return {
|
|
163
|
+
session_id: session, employee, status: status.state, reply,
|
|
164
|
+
...(folders.length ? { folders } : {}), presented: cards,
|
|
165
|
+
...(errors.length ? { errors } : {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
// --- commands -------------------------------------------------------------
|
|
169
|
+
async ls() {
|
|
170
|
+
return { employees: (await this.employees()).map((r) => ({ id: r.id, name: r.display_name, slug: r.slug, role: r.role })) };
|
|
171
|
+
}
|
|
172
|
+
async ask() {
|
|
173
|
+
const [who, given] = this.ctx.positional;
|
|
174
|
+
if (!who || given === undefined)
|
|
175
|
+
throw usage("Usage: votrix agent ask <employee> \"<task>\" [--file PATH|ASSET_ID] [--session ID] [--out DIR]");
|
|
176
|
+
const text = given === "-" ? await readStdin() : given;
|
|
177
|
+
if (!text.trim())
|
|
178
|
+
throw usage("The task cannot be empty.");
|
|
179
|
+
const employee = await this.resolve(who);
|
|
180
|
+
const person = { id: employee.id, name: employee.display_name };
|
|
181
|
+
const workspace = await this.ctx.workspace();
|
|
182
|
+
// Checked before a session exists, so a refusal never looks like work started.
|
|
183
|
+
const { balance } = await this.call("GET", "/billing/balance");
|
|
184
|
+
if (Number(balance) <= 0) {
|
|
185
|
+
throw new VotrixError("no_credits", `${person.name} cannot start: the workspace balance is ${Number(balance).toFixed(2)}.`, "Top up the workspace (votrix credits shows the balance), then ask again.");
|
|
186
|
+
}
|
|
187
|
+
const attachments = [];
|
|
188
|
+
for (const item of [].concat(this.ctx.flags.file ?? [])) {
|
|
189
|
+
const asset = uuidOf(item);
|
|
190
|
+
attachments.push(asset && !existsSync(item) ? asset : (await this.ctx.client.upload(item, workspace)).id);
|
|
191
|
+
}
|
|
192
|
+
let session = this.ctx.flags.session ? uuidOf(this.ctx.flags.session) : undefined;
|
|
193
|
+
if (this.ctx.flags.session && !session)
|
|
194
|
+
throw usage("--session must be a session id.");
|
|
195
|
+
let floor = 0; // what the session already held: never read back as this task's
|
|
196
|
+
if (session) {
|
|
197
|
+
const latest = await this.call("GET", `/sessions/${session}/events/list?limit=50`);
|
|
198
|
+
floor = Math.max(0, ...(latest.events ?? []).map(seqOf));
|
|
199
|
+
}
|
|
200
|
+
else
|
|
201
|
+
session = (await this.call("POST", "/sessions/create", { employee_id: employee.id, is_main: false, initial_message: text.slice(0, 500) })).id;
|
|
202
|
+
const body = { type: "user_message", text };
|
|
203
|
+
if (attachments.length)
|
|
204
|
+
body.attachments = attachments.map((asset_id) => ({ asset_id }));
|
|
205
|
+
let response;
|
|
206
|
+
try {
|
|
207
|
+
// Attachments are copied and mounted before the backend answers: allow for it.
|
|
208
|
+
response = await this.call("POST", `/sessions/${session}/events/send`, body, { stream: true, timeoutMs: SEND_TIMEOUT_MS });
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
if (error instanceof VotrixError && error.kind === "network") {
|
|
212
|
+
throw new VotrixError("network", "The send result is unknown; the message was not resent.", `votrix agent get ${session}`);
|
|
213
|
+
}
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
const accepted = Number(response.headers.get("x-accepted-event-seq") ?? 0) || 0;
|
|
217
|
+
if (this.ctx.flags["no-wait"]) {
|
|
218
|
+
await response.body?.cancel().catch(() => { });
|
|
219
|
+
emit({ session_id: session, employee: person, status: "running",
|
|
220
|
+
next: `votrix agent wait ${session}${this.ctx.flags.out ? ` --out ${this.ctx.flags.out}` : ""}` });
|
|
221
|
+
return 0;
|
|
222
|
+
}
|
|
223
|
+
note(`Session ${session} with ${person.name}. Waiting until the work is done...`);
|
|
224
|
+
const frames = [];
|
|
225
|
+
// A queued message (the employee was busy) comes back without an accepted seq.
|
|
226
|
+
for await (const frame of this.follow(session, Math.max(accepted - 1, floor), response)) {
|
|
227
|
+
frames.push(frame);
|
|
228
|
+
const line = this.describe(frame);
|
|
229
|
+
if (line)
|
|
230
|
+
note(line);
|
|
231
|
+
}
|
|
232
|
+
const status = this.lastStatus ?? (await this.status(session));
|
|
233
|
+
const result = await this.result(session, person, frames, status, this.ctx.flags.out);
|
|
234
|
+
emit(result);
|
|
235
|
+
return status.state === "failed" ? 1 : 0;
|
|
236
|
+
}
|
|
237
|
+
async sessions() {
|
|
238
|
+
const names = new Map((await this.employees()).map((e) => [e.id, e.display_name]));
|
|
239
|
+
const query = new URLSearchParams({ limit: String(this.ctx.flags.limit ?? 50) });
|
|
240
|
+
if (this.ctx.flags.employee)
|
|
241
|
+
query.set("employee_id", (await this.resolve(this.ctx.flags.employee)).id);
|
|
242
|
+
if (this.ctx.flags.before)
|
|
243
|
+
query.set("before", this.ctx.flags.before);
|
|
244
|
+
const page = await this.call("GET", `/sessions/list?${query}`);
|
|
245
|
+
const rows = page.sessions ?? [];
|
|
246
|
+
return {
|
|
247
|
+
sessions: rows.map((r) => ({ session_id: r.id, employee: { id: r.employee_id, name: names.get(r.employee_id) ?? null },
|
|
248
|
+
title: r.title, is_main: Boolean(r.is_main), last_message_at: r.last_message_at, updated_at: r.updated_at })),
|
|
249
|
+
has_more: Boolean(page.has_more),
|
|
250
|
+
before: rows.length && page.has_more ? rows[rows.length - 1].updated_at : null,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
sessionArg() {
|
|
254
|
+
const session = uuidOf(this.ctx.positional[0]);
|
|
255
|
+
if (!session)
|
|
256
|
+
throw usage("A session id is required.");
|
|
257
|
+
return session;
|
|
258
|
+
}
|
|
259
|
+
// The latest task's events: from its user message on.
|
|
260
|
+
async lastTurn(session) {
|
|
261
|
+
const page = await this.call("GET", `/sessions/${session}/events/list?limit=1000`);
|
|
262
|
+
const rows = (page.events ?? []).sort((a, b) => seqOf(a) - seqOf(b));
|
|
263
|
+
let start = 0;
|
|
264
|
+
rows.forEach((row, i) => { if (row.type === "user_message" && isMain(row))
|
|
265
|
+
start = i; });
|
|
266
|
+
return rows.slice(start);
|
|
267
|
+
}
|
|
268
|
+
async owner(session) {
|
|
269
|
+
const listing = await this.call("GET", "/sessions/list?limit=200");
|
|
270
|
+
const owner = (listing.sessions ?? []).find((r) => r.id === session);
|
|
271
|
+
const names = new Map((await this.employees()).map((e) => [e.id, e.display_name]));
|
|
272
|
+
return owner ? { id: owner.employee_id, name: names.get(owner.employee_id) ?? null } : null;
|
|
273
|
+
}
|
|
274
|
+
async get() {
|
|
275
|
+
const session = this.sessionArg();
|
|
276
|
+
const status = await this.status(session);
|
|
277
|
+
return this.result(session, await this.owner(session), await this.lastTurn(session), status);
|
|
278
|
+
}
|
|
279
|
+
// Block until the session's latest task is done, then collect it, like ask.
|
|
280
|
+
async wait() {
|
|
281
|
+
const session = this.sessionArg();
|
|
282
|
+
let status = await this.status(session);
|
|
283
|
+
if (!DONE.has(status.state)) {
|
|
284
|
+
const turn = await this.lastTurn(session);
|
|
285
|
+
note(`Waiting until session ${session} is done...`);
|
|
286
|
+
for await (const frame of this.follow(session, Math.max(seqOf(turn[turn.length - 1]), 0))) {
|
|
287
|
+
const line = this.describe(frame);
|
|
288
|
+
if (line)
|
|
289
|
+
note(line);
|
|
290
|
+
}
|
|
291
|
+
status = this.lastStatus ?? (await this.status(session));
|
|
292
|
+
}
|
|
293
|
+
const result = await this.result(session, await this.owner(session), await this.lastTurn(session), status, this.ctx.flags.out);
|
|
294
|
+
emit(result);
|
|
295
|
+
return status.state === "failed" ? 1 : 0;
|
|
296
|
+
}
|
|
297
|
+
async files() {
|
|
298
|
+
const session = this.sessionArg();
|
|
299
|
+
return { session_id: session, files: await this.outputs(session) };
|
|
300
|
+
}
|
|
301
|
+
async pull() {
|
|
302
|
+
if (!this.ctx.positional.length)
|
|
303
|
+
throw usage("Usage: votrix agent pull <asset_id> [<asset_id> ...] [--out DIR]");
|
|
304
|
+
const cards = [];
|
|
305
|
+
for (const given of this.ctx.positional) {
|
|
306
|
+
const asset = uuidOf(given);
|
|
307
|
+
if (!asset)
|
|
308
|
+
throw usage(`'${given}' is not an asset id.`, "votrix agent files <session> lists them.");
|
|
309
|
+
cards.push(fileCard(await this.call("GET", `/files/${asset}`)));
|
|
310
|
+
}
|
|
311
|
+
return { files: await downloadCards(this.ctx, cards, this.ctx.flags.out ?? ".") };
|
|
312
|
+
}
|
|
313
|
+
async stop() {
|
|
314
|
+
const session = this.sessionArg();
|
|
315
|
+
await this.call("POST", `/sessions/${session}/events/send`, { type: "interrupt" });
|
|
316
|
+
return { session_id: session, stopped: true };
|
|
317
|
+
}
|
|
318
|
+
// The last `--limit` messages before `--before` (a seq), oldest first.
|
|
319
|
+
async history() {
|
|
320
|
+
const session = this.sessionArg();
|
|
321
|
+
const limit = Number(this.ctx.flags.limit ?? 50);
|
|
322
|
+
if (!(limit >= 1))
|
|
323
|
+
throw usage("--limit must be at least 1.");
|
|
324
|
+
let cursor = this.ctx.flags.before ? Number(this.ctx.flags.before) : undefined;
|
|
325
|
+
let rows = [], more = true;
|
|
326
|
+
while (more) {
|
|
327
|
+
const page = await this.call("GET", `/sessions/${session}/events/list?limit=500${cursor ? `&before=${cursor}` : ""}`);
|
|
328
|
+
rows = [...(page.events ?? []), ...rows];
|
|
329
|
+
more = Boolean(page.has_more) && page.oldest_seq != null;
|
|
330
|
+
cursor = page.oldest_seq;
|
|
331
|
+
if (messages(rows).length > limit)
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
const all = messages(rows);
|
|
335
|
+
const older = all.length > limit || more;
|
|
336
|
+
const shown = all.slice(-limit);
|
|
337
|
+
return { session_id: session, messages: shown, has_more: older, before: shown.length && older ? shown[0].seq : null };
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
export function messages(rows) {
|
|
341
|
+
const sorted = [...rows].sort((a, b) => seqOf(a) - seqOf(b));
|
|
342
|
+
const out = [];
|
|
343
|
+
for (const row of sorted) {
|
|
344
|
+
if (["user_message", "ai_message"].includes(row.type) && isMain(row) && String(row.text ?? "").trim()) {
|
|
345
|
+
out.push({ seq: seqOf(row), role: row.type === "user_message" ? "user" : "employee", text: row.text });
|
|
346
|
+
}
|
|
347
|
+
for (const asset of presentedIds(row))
|
|
348
|
+
out.push({ seq: seqOf(row), role: "employee", presented: asset });
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
export async function runAgent(ctx, action) {
|
|
353
|
+
const agent = new Agent(ctx);
|
|
354
|
+
const commands = {
|
|
355
|
+
ls: () => agent.ls(), sessions: () => agent.sessions(), get: () => agent.get(), files: () => agent.files(),
|
|
356
|
+
pull: () => agent.pull(), stop: () => agent.stop(), history: () => agent.history(),
|
|
357
|
+
};
|
|
358
|
+
if (action === "ask")
|
|
359
|
+
return agent.ask();
|
|
360
|
+
if (action === "wait")
|
|
361
|
+
return agent.wait();
|
|
362
|
+
if (!commands[action])
|
|
363
|
+
throw usage(`Unknown agent command '${action ?? ""}'.`, "Run votrix agent --help.");
|
|
364
|
+
emit(await commands[action]());
|
|
365
|
+
return 0;
|
|
366
|
+
}
|
package/dist/src/auth.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// Sign in, then keep only API keys: one per workspace this device was approved
|
|
2
|
+
// for. Neither the Google session nor the one-time code is stored.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { hostname } from "node:os";
|
|
7
|
+
import { createInterface } from "node:readline";
|
|
8
|
+
import { ApiError, clean, deviceId, note, usage, VotrixError } from "./core.js";
|
|
9
|
+
const CALLBACK = "/auth/callback";
|
|
10
|
+
const START = "/auth/start";
|
|
11
|
+
function pkce() {
|
|
12
|
+
const verifier = randomBytes(64).toString("base64url");
|
|
13
|
+
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
|
|
14
|
+
}
|
|
15
|
+
function openBrowser(url) {
|
|
16
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]]
|
|
17
|
+
: process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
|
|
18
|
+
: ["xdg-open", [url]];
|
|
19
|
+
try {
|
|
20
|
+
spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => { }).unref();
|
|
21
|
+
}
|
|
22
|
+
catch { /* the link is printed anyway */ }
|
|
23
|
+
}
|
|
24
|
+
function same(a, b) {
|
|
25
|
+
const x = Buffer.from(a), y = Buffer.from(b);
|
|
26
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
27
|
+
}
|
|
28
|
+
// One-use loopback listener: /auth/start redirects to Google, /auth/callback
|
|
29
|
+
// receives the code. Both require the random nonce.
|
|
30
|
+
function awaitCode(port, timeoutMs, authorize, noBrowser) {
|
|
31
|
+
const nonce = randomBytes(32).toString("base64url");
|
|
32
|
+
return new Promise((done, fail) => {
|
|
33
|
+
let settled = false;
|
|
34
|
+
const reply = (res, status, text, location) => {
|
|
35
|
+
res.writeHead(status, {
|
|
36
|
+
"Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
|
|
37
|
+
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'", ...(location ? { Location: location } : {}),
|
|
38
|
+
});
|
|
39
|
+
res.end(text);
|
|
40
|
+
};
|
|
41
|
+
const server = createServer((req, res) => {
|
|
42
|
+
const host = `127.0.0.1:${server.address().port}`;
|
|
43
|
+
if (req.headers.host !== host)
|
|
44
|
+
return reply(res, 400, "Invalid sign-in callback address.");
|
|
45
|
+
const url = new URL(req.url ?? "/", `http://${host}`);
|
|
46
|
+
if (![START, CALLBACK].includes(url.pathname))
|
|
47
|
+
return reply(res, 404, "Not found.");
|
|
48
|
+
const state = url.searchParams.getAll("state");
|
|
49
|
+
if (state.length !== 1 || !same(state[0], nonce))
|
|
50
|
+
return reply(res, 400, "Sign-in verification failed.");
|
|
51
|
+
if (settled)
|
|
52
|
+
return reply(res, 409, "This sign-in callback has already been used.");
|
|
53
|
+
if (url.pathname === START)
|
|
54
|
+
return reply(res, 302, "Continue to Google sign-in.", authorizeUrl);
|
|
55
|
+
settled = true;
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
if (url.searchParams.has("error")) {
|
|
58
|
+
reply(res, 400, "Sign-in failed or was canceled. Return to your terminal.");
|
|
59
|
+
server.close();
|
|
60
|
+
return fail(new VotrixError("unauthorized", "Google sign-in failed or was canceled. Run votrix login again."));
|
|
61
|
+
}
|
|
62
|
+
const code = url.searchParams.getAll("code");
|
|
63
|
+
if (code.length !== 1 || !code[0] || code[0].length > 4096) {
|
|
64
|
+
reply(res, 400, "No valid authorization code was received.");
|
|
65
|
+
server.close();
|
|
66
|
+
return fail(new VotrixError("unauthorized", "The sign-in callback had no valid code. Run votrix login again."));
|
|
67
|
+
}
|
|
68
|
+
reply(res, 200, "Votrix received your sign-in. Return to your terminal; you can close this page.");
|
|
69
|
+
server.close();
|
|
70
|
+
done(code[0]);
|
|
71
|
+
});
|
|
72
|
+
let authorizeUrl = "";
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
if (settled)
|
|
75
|
+
return;
|
|
76
|
+
settled = true;
|
|
77
|
+
server.close();
|
|
78
|
+
fail(new VotrixError("timeout", "Sign-in timed out.", "Run votrix login --no-browser and open the link on this computer."));
|
|
79
|
+
}, timeoutMs);
|
|
80
|
+
server.on("error", () => fail(usage(`Cannot listen on 127.0.0.1:${port}. Free the port or pass --port.`)));
|
|
81
|
+
server.listen(port, "127.0.0.1", () => {
|
|
82
|
+
const host = `127.0.0.1:${server.address().port}`;
|
|
83
|
+
authorizeUrl = authorize(`http://${host}${CALLBACK}?state=${encodeURIComponent(nonce)}`);
|
|
84
|
+
note(`Open this link in a browser on this computer and sign in with Google:\n${authorizeUrl}`);
|
|
85
|
+
if (!noBrowser)
|
|
86
|
+
openBrowser(`http://${host}${START}?state=${encodeURIComponent(nonce)}`);
|
|
87
|
+
note(`Waiting for sign-in (up to ${Math.round(timeoutMs / 1000)} seconds; Ctrl-C to cancel)...`);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
// By default the Google sign-in that redirects to this computer and keys every
|
|
92
|
+
// workspace (as in 0.2.0); --key saves a key made in the app.
|
|
93
|
+
// --code-flow / --code: approve in the app for one workspace and paste the
|
|
94
|
+
// one-time code it shows. Not documented until the app's approval page ships.
|
|
95
|
+
export async function login(client, options) {
|
|
96
|
+
for (const name of ["VOTRIX_ACCESS_TOKEN", "VOTRIX_API_KEY"]) {
|
|
97
|
+
if (process.env[name])
|
|
98
|
+
throw usage(`Unset ${name} before running votrix login.`);
|
|
99
|
+
}
|
|
100
|
+
const chosen = ["code", "key", "codeFlow"].filter((k) => options[k] !== undefined && options[k] !== false);
|
|
101
|
+
if (chosen.length > 1)
|
|
102
|
+
throw usage("Pass only one way to sign in.");
|
|
103
|
+
if (options.key !== undefined)
|
|
104
|
+
return saveKey(client, String(options.key));
|
|
105
|
+
if (options.code !== undefined)
|
|
106
|
+
return exchangeCode(client, String(options.code));
|
|
107
|
+
if (!options.codeFlow)
|
|
108
|
+
return loginWithCallback(client, options);
|
|
109
|
+
const { verifier, challenge } = pkce();
|
|
110
|
+
const started = await (await client.raw("POST", `${client.cfg.backend}/cli/logins`, {
|
|
111
|
+
body: { code_challenge: challenge, device_id: deviceId(), device_name: clean(hostname()).slice(0, 120) },
|
|
112
|
+
})).json();
|
|
113
|
+
if (typeof started?.url !== "string" || !started.login_id) {
|
|
114
|
+
throw new VotrixError("server", "The backend did not start a sign-in.");
|
|
115
|
+
}
|
|
116
|
+
client.state.update({ pending_login: { login_id: started.login_id, verifier, expires_at: started.expires_at } });
|
|
117
|
+
note(`Open this link in a browser, sign in, choose a workspace and approve:\n${started.url}`);
|
|
118
|
+
if (!options.noBrowser)
|
|
119
|
+
openBrowser(started.url);
|
|
120
|
+
if (!options.interactive) {
|
|
121
|
+
return { status: "waiting_for_code", url: started.url, expires_at: started.expires_at,
|
|
122
|
+
next: "After approving, the page shows a code. Run: votrix login --code <CODE>" };
|
|
123
|
+
}
|
|
124
|
+
const code = await prompt("Paste the code shown after you approve: ");
|
|
125
|
+
if (!code.trim())
|
|
126
|
+
throw usage("No code was pasted.", "Run votrix login --code <CODE> with the code from the page.");
|
|
127
|
+
return exchangeCode(client, code);
|
|
128
|
+
}
|
|
129
|
+
function prompt(question) {
|
|
130
|
+
return new Promise((done) => {
|
|
131
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
132
|
+
rl.question(question, (answer) => { rl.close(); done(answer); });
|
|
133
|
+
rl.on("close", () => done(""));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
async function exchangeCode(client, code) {
|
|
137
|
+
const pending = client.state.read().pending_login;
|
|
138
|
+
if (!pending?.verifier) {
|
|
139
|
+
throw usage("No sign-in is waiting for a code on this machine.", "Run votrix login first, then paste the code it asks for.");
|
|
140
|
+
}
|
|
141
|
+
if (pending.expires_at && Date.parse(pending.expires_at) < Date.now()) {
|
|
142
|
+
client.state.update({ pending_login: undefined });
|
|
143
|
+
throw new VotrixError("expired", "That sign-in expired.", "Run votrix login again.");
|
|
144
|
+
}
|
|
145
|
+
// A refusal (wrong, used or expired code) arrives as the backend's type, message and fix.
|
|
146
|
+
const minted = await (await client.raw("POST", `${client.cfg.backend}/cli/logins/exchange`, {
|
|
147
|
+
body: { code: code.trim(), code_verifier: pending.verifier },
|
|
148
|
+
})).json();
|
|
149
|
+
if (!String(minted?.key ?? "").startsWith("vtx_") || !minted.workspace?.id) {
|
|
150
|
+
throw new VotrixError("server", "The backend returned no key. Sign-in was not saved.");
|
|
151
|
+
}
|
|
152
|
+
return remember(client, minted.user, minted.workspace, minted);
|
|
153
|
+
}
|
|
154
|
+
// A key made in the Votrix App for one workspace; checked before it is saved.
|
|
155
|
+
async function saveKey(client, key) {
|
|
156
|
+
key = key.trim();
|
|
157
|
+
if (!key.startsWith("vtx_"))
|
|
158
|
+
throw usage("--key takes a Votrix API key, which starts with vtx_.");
|
|
159
|
+
const current = await (await client.raw("GET", `${client.cfg.backend}/api-keys/current`, { auth: key })).json();
|
|
160
|
+
if (!current?.workspace_id)
|
|
161
|
+
throw new VotrixError("unauthorized", "That key was not accepted.");
|
|
162
|
+
return remember(client, undefined, { id: current.workspace_id, display_name: current.workspace_name ?? "", role: "" }, { key, id: current.id, prefix: current.prefix, expires_at: current.expires_at });
|
|
163
|
+
}
|
|
164
|
+
// Add one workspace's key beside the others and make it the default.
|
|
165
|
+
function remember(client, user, workspace, key) {
|
|
166
|
+
const previous = client.state.read();
|
|
167
|
+
const sameUser = !user || !previous.user || previous.user.id === user.id;
|
|
168
|
+
const state = sameUser ? { ...previous } : {};
|
|
169
|
+
if (user?.id)
|
|
170
|
+
state.user = { id: clean(user.id), ...(user.email ? { email: clean(user.email) } : {}) };
|
|
171
|
+
const entry = { id: workspace.id, display_name: clean(workspace.display_name ?? ""), role: clean(workspace.role ?? "") };
|
|
172
|
+
state.workspaces = [...(state.workspaces ?? []).filter((w) => w.id !== workspace.id), entry];
|
|
173
|
+
state.api_keys = { ...(state.api_keys ?? {}), [workspace.id]: { key: key.key, id: key.id, prefix: key.prefix, expires_at: key.expires_at } };
|
|
174
|
+
state.workspace_id = workspace.id;
|
|
175
|
+
delete state.pending_login;
|
|
176
|
+
client.state.write(state);
|
|
177
|
+
return { ...(state.user ?? {}), workspace: entry, key_expires_at: key.expires_at ?? null,
|
|
178
|
+
workspaces: state.workspaces.map((w) => w.display_name || w.id) };
|
|
179
|
+
}
|
|
180
|
+
async function loginWithCallback(client, options) {
|
|
181
|
+
if (!client.cfg.publicKey)
|
|
182
|
+
throw usage("Set VOTRIX_SUPABASE_KEY to your public publishable key.");
|
|
183
|
+
const { verifier, challenge } = pkce();
|
|
184
|
+
const code = await awaitCode(options.port ?? 8765, (options.timeout ?? 180) * 1000, (callback) => `${client.cfg.auth}/auth/v1/authorize?` + new URLSearchParams({
|
|
185
|
+
provider: "google", redirect_to: callback, code_challenge: challenge, code_challenge_method: "s256",
|
|
186
|
+
}), Boolean(options.noBrowser));
|
|
187
|
+
const session = await (await client.raw("POST", `${client.cfg.auth}/auth/v1/token?grant_type=pkce`, {
|
|
188
|
+
headers: { apikey: client.cfg.publicKey }, body: { auth_code: code, code_verifier: verifier },
|
|
189
|
+
})).json();
|
|
190
|
+
const token = session?.access_token ?? session?.session?.access_token;
|
|
191
|
+
if (!token)
|
|
192
|
+
throw new VotrixError("unauthorized", "The sign-in response had no token.");
|
|
193
|
+
const user = await (await client.raw("GET", `${client.cfg.auth}/auth/v1/user`, {
|
|
194
|
+
headers: { apikey: client.cfg.publicKey }, auth: token,
|
|
195
|
+
})).json();
|
|
196
|
+
if (!user?.id)
|
|
197
|
+
throw new VotrixError("unauthorized", "The auth service returned no user. Sign-in was not saved.");
|
|
198
|
+
const who = { id: clean(user.id), ...(user.email ? { email: clean(user.email) } : {}) };
|
|
199
|
+
const { workspaces, keys } = await mintDeviceKeys(client, token);
|
|
200
|
+
const previous = client.state.read();
|
|
201
|
+
const state = previous.user?.id === who.id ? previous : {};
|
|
202
|
+
state.user = who;
|
|
203
|
+
state.workspaces = workspaces;
|
|
204
|
+
state.api_keys = keys;
|
|
205
|
+
if (!state.workspace_id || !keys[state.workspace_id]) {
|
|
206
|
+
delete state.workspace_id;
|
|
207
|
+
if (Object.keys(keys).length === 1)
|
|
208
|
+
state.workspace_id = Object.keys(keys)[0];
|
|
209
|
+
}
|
|
210
|
+
client.state.write(state);
|
|
211
|
+
const expiries = Object.values(keys).map((k) => k.expires_at).filter(Boolean).sort();
|
|
212
|
+
return { ...who, workspaces: workspaces.map((w) => w.display_name || w.id), keys_expire_at: expiries[0] ?? null };
|
|
213
|
+
}
|
|
214
|
+
// `/users/me` first: for a brand-new account it creates the first workspace.
|
|
215
|
+
export async function mintDeviceKeys(client, token) {
|
|
216
|
+
const backend = client.cfg.backend;
|
|
217
|
+
await client.raw("GET", `${backend}/users/me`, { auth: token });
|
|
218
|
+
const listed = await (await client.raw("GET", `${backend}/workspaces`, { auth: token })).json();
|
|
219
|
+
// Only workspaces the account belongs to: a super admin is listed every
|
|
220
|
+
// workspace in the installation, with an empty role where not a member.
|
|
221
|
+
const rows = Array.isArray(listed) ? listed.filter((row) => String(row?.role ?? "").trim()) : [];
|
|
222
|
+
if (!rows.length) {
|
|
223
|
+
throw new VotrixError("not_found", "This account has no workspace.", "Open the Votrix App once, then log in again.");
|
|
224
|
+
}
|
|
225
|
+
const device = deviceId();
|
|
226
|
+
const name = `CLI - ${clean(hostname()).slice(0, 60) || "unknown device"}`;
|
|
227
|
+
const workspaces = [];
|
|
228
|
+
const keys = {};
|
|
229
|
+
for (const row of rows) {
|
|
230
|
+
const minted = await (await client.raw("POST", `${backend}/workspaces/${row.id}/api-keys`, {
|
|
231
|
+
auth: token, body: { name, kind: "cli", device_id: device },
|
|
232
|
+
})).json();
|
|
233
|
+
if (!String(minted?.key ?? "").startsWith("vtx_")) {
|
|
234
|
+
throw new VotrixError("server", "The backend returned an invalid API key. Sign-in was not saved.");
|
|
235
|
+
}
|
|
236
|
+
workspaces.push({ id: row.id, display_name: clean(row.display_name ?? ""), role: clean(row.role ?? "") });
|
|
237
|
+
keys[row.id] = { key: minted.key, id: minted.id, prefix: minted.prefix, expires_at: minted.expires_at };
|
|
238
|
+
}
|
|
239
|
+
return { workspaces, keys };
|
|
240
|
+
}
|
|
241
|
+
export async function whoami(client, workspace) {
|
|
242
|
+
const current = await client.currentKey(workspace);
|
|
243
|
+
const summary = Object.fromEntries(["workspace_id", "workspace_name", "name", "kind", "prefix", "scopes",
|
|
244
|
+
"expires_at"].map((k) => [k, current[k]]));
|
|
245
|
+
if (process.env.VOTRIX_API_KEY)
|
|
246
|
+
return { source: "VOTRIX_API_KEY", ...summary };
|
|
247
|
+
const user = client.state.read().user ?? {};
|
|
248
|
+
return { ...user, ...summary };
|
|
249
|
+
}
|
|
250
|
+
// Revoke this device's keys on the backend, then forget them. The device id stays.
|
|
251
|
+
export async function logout(client) {
|
|
252
|
+
const keys = Object.values(client.state.read().api_keys ?? {});
|
|
253
|
+
let revoked = 0, unrevoked = 0;
|
|
254
|
+
for (const entry of keys) {
|
|
255
|
+
try {
|
|
256
|
+
await client.raw("DELETE", `${client.cfg.backend}/api-keys/current`, { auth: entry.key });
|
|
257
|
+
revoked++;
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
if (error instanceof ApiError && error.status === 401)
|
|
261
|
+
revoked++; // already gone
|
|
262
|
+
else
|
|
263
|
+
unrevoked++;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
client.state.clear();
|
|
267
|
+
return { logged_out: true, revoked_keys: revoked, unrevoked_keys: unrevoked,
|
|
268
|
+
environment_token_active: Boolean(process.env.VOTRIX_ACCESS_TOKEN || process.env.VOTRIX_API_KEY) };
|
|
269
|
+
}
|
|
270
|
+
// The workspaces this credential can act in.
|
|
271
|
+
export async function workspaces(client) {
|
|
272
|
+
if (process.env.VOTRIX_API_KEY) {
|
|
273
|
+
const current = await client.currentKey();
|
|
274
|
+
return [{ id: current.workspace_id, display_name: current.workspace_name, role: "" }];
|
|
275
|
+
}
|
|
276
|
+
if (process.env.VOTRIX_ACCESS_TOKEN)
|
|
277
|
+
return client.request("GET", "/workspaces");
|
|
278
|
+
const state = client.state.read();
|
|
279
|
+
const keys = state.api_keys ?? {};
|
|
280
|
+
if (!Object.keys(keys).length)
|
|
281
|
+
throw new VotrixError("unauthorized", "Run votrix login first.");
|
|
282
|
+
return (state.workspaces ?? []).filter((w) => keys[w.id]);
|
|
283
|
+
}
|