@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.
package/README.md CHANGED
@@ -1,3 +1,190 @@
1
- # Temporary Holding Version
1
+ # Votrix AI CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Hand work to Votrix employees and run Votrix tools from a terminal or from another agent (Claude Code, Codex, a script). Node.js 18.17+ on macOS, Linux and Windows. No runtime dependencies.
4
+
5
+ ```bash
6
+ npm install -g @votrix-ai/cli # or run without installing: npx -y @votrix-ai/cli <command>
7
+ votrix login
8
+ votrix whoami
9
+ ```
10
+
11
+ ## Output contract
12
+
13
+ Commands print **one JSON object on stdout**, errors included:
14
+
15
+ ```json
16
+ {"error": {"type": "not_found", "message": "No employee called 'nobody'.", "fix": "votrix agent ls lists them: ..."}}
17
+ ```
18
+
19
+ Progress for people goes to stderr and `--help` prints plain text. Nothing ever prompts. Exit codes: `0` answered, `1` failed, `2` bad usage. Error types: `bad_input`, `not_found`, `unauthorized`, `forbidden`, `no_credits`, `busy`, `network`, `server`.
20
+
21
+ ## Sign-in and keys
22
+
23
+ `votrix login` opens Google sign-in (PKCE with a one-use callback on `127.0.0.1:8765`). The sign-in token is used once: the CLI calls `/users/me` (which creates the first workspace for a new account), mints one `cli` API key per workspace for this device, and discards the token. Keys live in `~/.config/votrix` (`%APPDATA%\votrix` on Windows) with mode `0600` and last 90 days; log in again to renew them. A random device id in the same folder makes a new login replace this device's earlier keys. `votrix logout` revokes the keys on the backend and removes local state.
24
+
25
+ ```bash
26
+ votrix login --no-browser # print the link only
27
+ votrix login --port 8766 --timeout 300
28
+ votrix workspaces
29
+ votrix workspace use <workspace-id>
30
+ ```
31
+
32
+ | Variable | Purpose |
33
+ |---|---|
34
+ | `VOTRIX_API_KEY` | Use this key (`vtx_...`) instead of the saved login; it acts in its workspace with its scopes |
35
+ | `VOTRIX_WORKSPACE_ID` | Default workspace (a `--workspace` flag overrides it) |
36
+ | `VOTRIX_BACKEND_URL`, `VOTRIX_SUPABASE_URL`, `VOTRIX_SUPABASE_KEY` | Another environment (HTTPS, or HTTP on localhost) |
37
+ | `VOTRIX_CONFIG_DIR` | Where keys and the device id are kept |
38
+
39
+ ## Hand work to an employee
40
+
41
+ ```bash
42
+ votrix agent ls # id, name, slug, role
43
+ votrix agent ask rebecca 'Make a 30-second launch video' --file ./product.png --out ./out
44
+ votrix agent ask rebecca 'Make it vertical' --session <id> --out ./out
45
+ printf 'Line one\nLine two\n' | votrix agent ask rebecca -
46
+ votrix agent sessions --employee rebecca # conversations, most recent first
47
+ votrix agent get <session> # where it stands, without waiting
48
+ votrix agent files <session> # every file in the session's outputs folder
49
+ votrix agent pull <asset-id> [<asset-id> ...] --out ./out
50
+ votrix agent history <session> --limit 20 [--before <seq>]
51
+ votrix agent stop <session>
52
+ ```
53
+
54
+ `ask` starts a new session (or continues `--session`) and **blocks until the whole session is done**: the employee's turns, its subagents, and background jobs such as a render that wake it again. It decides "done" with the backend's `GET /sessions/{id}/status`; a quiet stream during a long job is a poll, not a failure. Run it in the background if the caller cannot wait. Ctrl-C only stops waiting: the employee keeps working, and `get` picks it up.
55
+
56
+ ```json
57
+ {"session_id": "…", "employee": {"id": "…", "name": "Rebecca"}, "status": "idle", "reply": "Your video is ready",
58
+ "presented": [{"asset_id": "…", "filename": "launch.mp4", "kind": "file", "size_bytes": 48000000,
59
+ "path": "out/launch.mp4"}]}
60
+ ```
61
+
62
+ `status` is `idle` (done) or `failed`. `presented` holds the files the employee handed over in this task only; `--out` downloads them (a website or video project comes as its `<name>.website.zip` / `<name>.video.zip`). `files` lists everything in the session's outputs folder; pull any of it by asset id. `--file` takes a local path (uploaded, up to 500 MiB) or any asset id in the workspace, from any session. `history` pages back with the `before` it returns.
63
+
64
+ ## Tools
65
+
66
+ | Command group | Commands |
67
+ | --- | --- |
68
+ | [`votrix`](docs/cli/account.md) | `login`, `logout`, `whoami`, `workspaces`, `workspace use`, `credits` |
69
+ | [`votrix agent`](docs/cli/agent.md) | `ls`, `ask`, `wait`, `sessions`, `get`, `files`, `pull`, `history`, `stop` |
70
+ | [`votrix tools media`](docs/cli/media.md) | `list`, `explore`, `run` |
71
+ | [`votrix tools seo`](docs/cli/seo.md) | `list`, `explore`, `run` |
72
+ | [`votrix tools scraper`](docs/cli/scraper.md) | `list`, `explore`, `run` |
73
+ | [`votrix tools ui`](docs/cli/ui.md) | `list`, `explore`, `run` |
74
+ | [`votrix tools runs`](docs/cli/runs.md) | `list`, `get`, `stop` |
75
+ | [`votrix tools files`](docs/cli/files.md) | `upload`, `get`, `pull`, `publish`, `library` |
76
+ | [`votrix tools social`](docs/cli/social.md) | `accounts`, `posts create`, `posts update`, `posts list`, `posts get`, `posts results`, `posts cancel` |
77
+ | [`votrix tools site`](docs/cli/site.md) | `list`, `deploy`, `versions`, `status`, `env list`, `env set`, `domain add`, `domain status`, `track enable`, `track disable`, `track events`, `track funnel` |
78
+ | [`votrix tools integrations`](docs/cli/integrations.md) | `toolkits list`, `connections list`, `link`, `search`, `execute` |
79
+
80
+ ### Command guides
81
+
82
+ - [Account and workspace](docs/cli/account.md)
83
+ - [Employees and sessions](docs/cli/agent.md)
84
+ - [Media tools](docs/cli/media.md)
85
+ - [SEO tools](docs/cli/seo.md)
86
+ - [Scraper tools](docs/cli/scraper.md)
87
+ - [UI tools](docs/cli/ui.md)
88
+ - [Tool runs](docs/cli/runs.md)
89
+ - [Social publishing](docs/cli/social.md)
90
+ - [Workspace files](docs/cli/files.md)
91
+ - [Website deployment](docs/cli/site.md)
92
+ - [Connected applications](docs/cli/integrations.md)
93
+ - [Site analytics](SITE-TRACKING-CLI-DESIGN.md)
94
+ - [HTTP API reference](docs/API.md)
95
+
96
+ Use `votrix tools --help` or `votrix tools GROUP --help` for flags.
97
+
98
+ ```bash
99
+ votrix tools media list # models, aliases, defaults, as they are today
100
+ votrix tools media explore seedance # modes, parameters, price
101
+ votrix tools media run seedance --mode text_to_video --prompt 'A calm sea at dawn' --duration 5 --out ./out
102
+ votrix tools media run nano-banana-2.1 --prompt 'A red bicycle' --image-url ./ref.png --out ./out
103
+ votrix tools seo explore keyword_metrics
104
+ votrix tools seo run keyword_metrics --keywords '["restaurant pos"]'
105
+ votrix tools scraper run reddit-posts --where r/SEO --query 'new site not ranking' --limit 20
106
+ votrix tools ui run design --site-type 'online sneaker store' --story 'choosing a size, then adding to cart' --out ./out
107
+ votrix tools runs list | get <run> --out ./out | stop <run>
108
+ ```
109
+
110
+ Categories are fixed (`media`, `seo`, `scraper`, `ui`); what is inside them is read from the backend, so models can change without a new CLI. Media models have family aliases (`seedance`, `kling`) and domain defaults (`image`, `video`, `audio`). Every scraper source and SEO dataset states the exact fields a row carries (`returns` in `explore`).
111
+
112
+ Any `--<parameter> VALUE` goes into the run's input (`--image-url` becomes `image_url`, JSON values are parsed, a repeated flag is a list); `--input '{...}'` or `--input @file.json` gives it all at once. A value that is a local file is uploaded and passed as `asset:<id>`. `run` blocks until the run is done; `--no-wait` returns the run id at once, and `--max-cost USD` refuses a run estimated above it. Runs are billed to the workspace's credits.
113
+
114
+ ```bash
115
+ votrix tools social accounts --platform youtube
116
+ votrix tools social posts create --account <id> --caption 'Launch day' --media ./launch.mp4 --title 'Launch' --schedule-at 2030-01-01T12:00:00Z
117
+ votrix tools social posts list
118
+ votrix tools files upload ./brief.pdf
119
+ votrix tools files library --query launch
120
+ ```
121
+
122
+ ## Sites and visitor analytics
123
+
124
+ ```bash
125
+ votrix tools site deploy ./website --name my-site
126
+ votrix tools site track events my-site --by source
127
+ votrix tools site track funnel my-site --steps visit,login,signup_completed --where source=utm:instagram
128
+ ```
129
+
130
+ Deploy requests tracking by default. Use `--no-track` to opt out or
131
+ `site track enable` to install or upgrade tracking on a live site. See
132
+ [Site tracking CLI](SITE-TRACKING-CLI-DESIGN.md) for website instrumentation,
133
+ query inputs, and JSON replies.
134
+
135
+ ## Connected apps
136
+
137
+ The toolkit catalog is available offline. Connection, search, and execution
138
+ commands use the Votrix backend and the selected workspace. A scoped Votrix
139
+ API key needs `tools:integrations`.
140
+
141
+ ```bash
142
+ votrix tools integrations --help
143
+ votrix tools integrations toolkits list
144
+ votrix tools integrations connections list --toolkit gmail
145
+ votrix tools integrations link gmail --no-browser
146
+ votrix tools integrations search "find unread emails" --toolkits gmail
147
+ votrix tools integrations execute GMAIL_FETCH_EMAILS --get-schema
148
+ votrix tools integrations execute GMAIL_FETCH_EMAILS --dry-run -d '{"query":"is:unread"}'
149
+ votrix tools integrations execute GMAIL_FETCH_EMAILS -d '{"query":"is:unread"}'
150
+ ```
151
+
152
+ | Command | Input | JSON output |
153
+ | --- | --- | --- |
154
+ | `toolkits list` | No arguments | `toolkits` with each app's `slug` and `name` |
155
+ | `link` | App slug | `app`, `status`, hosted OAuth `url`, `account_id`, `expires_at` |
156
+ | `connections list` | Optional `--toolkit APP` | `apps` with the workspace's linked accounts and their statuses |
157
+ | `search` | Query, optional `--toolkits APP,APP` and `--limit N` | `actions` with executable action slugs, and `needs_connection` |
158
+ | `execute --get-schema` | Action slug | `input_schema`, `output_schema`, action metadata |
159
+ | `execute --dry-run` | Action slug, arguments and optional account ID | Argument validation result with `valid` |
160
+ | `execute` | Action slug, arguments and optional account ID | `ok`, `action`, and provider `data` or an `error` |
161
+
162
+ Give the authorization URL returned by `link` to the user. Run `connections list` after
163
+ they finish connecting. Use the action name and input schema returned by the
164
+ backend. For multiple accounts, pass the selected account ID using `--account`.
165
+ `--data` (or `-d`) accepts strict JSON, `@file.json`, or `-` for stdin.
166
+ Use `toolkits list` for app names and slugs. The catalog contains Gmail,
167
+ Outlook, Google Sheets, HubSpot, Google Calendar, Calendly, Slack, Search
168
+ Console, GA4, Semrush MCP, and Ahrefs MCP.
169
+ OAuth makes the connection available. Each app still controls what the account
170
+ can do through its granted permissions, roles, subscription, and limits.
171
+
172
+ ## Use with Claude Code / Codex
173
+
174
+ The skill is in [`skills/votrix/SKILL.md`](skills/votrix/SKILL.md). Link it into the tools' skill folders:
175
+
176
+ ```bash
177
+ mkdir -p ~/.claude/skills ~/.agents/skills
178
+ ln -s "$PWD/skills/votrix" ~/.claude/skills/votrix
179
+ ln -s "$PWD/skills/votrix" ~/.agents/skills/votrix
180
+ ```
181
+
182
+ ## Development
183
+
184
+ ```bash
185
+ npm install
186
+ npm test # builds, then runs the CLI against a local fake backend
187
+ node dist/src/cli.js --help
188
+ ```
189
+
190
+ Tests never call production. Signed storage URLs never receive the key, redirects are not followed with credentials, and server text is stripped of terminal escapes.
@@ -0,0 +1,117 @@
1
+ # Site tracking CLI
2
+
3
+ Use `votrix tools site track --help` to discover the tracking commands and the
4
+ browser API. The backend scopes queries to the selected workspace and site.
5
+ A scoped Votrix API key needs `tools:sites`.
6
+
7
+ ## Deploy and instrument
8
+
9
+ ```bash
10
+ votrix tools site deploy ./website --name my-site
11
+ votrix tools site track enable my-site
12
+ votrix tools site track disable my-site
13
+ votrix tools site status my-site
14
+ ```
15
+
16
+ New deployments request tracking by default. Pass `--no-track` to skip it.
17
+ Inspect the deployment's `tracking` result to confirm that the backend
18
+ installed the collector. Enable and disable may redeploy the live version.
19
+ They return `site`, `version`, `tracking`, and `changed`, with deployment
20
+ `status` when a redeployment starts.
21
+
22
+ The collector records page visits as `visit`. Add a label to the actual
23
+ control to record a click.
24
+
25
+ ```html
26
+ <a href="/login" data-track="login">Login</a>
27
+ ```
28
+
29
+ On the signup success path, after the app confirms signup, record the outcome.
30
+
31
+ ```js
32
+ window.votrix?.track?.("signup_completed");
33
+ ```
34
+
35
+ Use 1–40 lowercase ASCII letters, digits, or underscores. Reserve `visit`
36
+ for page views and use different names for clicks and outcomes. The collector
37
+ also recognizes the older `data-votrix-cta` attribute. Enable tracking to
38
+ upgrade an older collector before using `data-track` and `votrix.track()`.
39
+ Pass only the event name. For Instagram traffic, link to
40
+ `https://example.com/?utm_source=instagram&utm_campaign=bio`.
41
+
42
+ ## Query events
43
+
44
+ ```bash
45
+ votrix tools site track events my-site --period 30d
46
+ votrix tools site track events my-site --by source --event login --limit 20
47
+ ```
48
+
49
+ | Input | Meaning |
50
+ | --- | --- |
51
+ | `SITE` | The workspace's site name |
52
+ | `--period` | `7d`, `30d`, or `90d`. Default `30d` |
53
+ | `--by` | A grouping field. Default `name` |
54
+ | `--event` | Event to count for a grouping other than `name`. Default `visit` in those groupings |
55
+ | `--where FIELD=VALUE[,VALUE...]` | Exact values. Repeat to add fields or values |
56
+ | `--search` | Case-insensitive substring of the grouping value |
57
+ | `--limit` | 1–200 rows. Default 50 |
58
+
59
+ Example stdout (selected fields):
60
+
61
+ ```json
62
+ {
63
+ "site": "my-site",
64
+ "period": "30d",
65
+ "by": "name",
66
+ "data_status": "available",
67
+ "rows": [
68
+ {"name": "visit", "kind": "visit", "visitors": 120, "count": 160},
69
+ {"name": "login", "kind": "click", "visitors": 35, "count": 39}
70
+ ],
71
+ "has_more": false
72
+ }
73
+ ```
74
+
75
+ `visitors` measures distinct anonymous browser IDs and `count` measures
76
+ recorded events.
77
+
78
+ ## Query an ordered funnel
79
+
80
+ ```bash
81
+ votrix tools site track funnel my-site \
82
+ --steps visit,login,signup_completed \
83
+ --where source=utm:instagram --period 30d --window 7d
84
+ ```
85
+
86
+ Give 2–5 comma-separated event names in order. The period defaults to `30d`
87
+ and the window defaults to `7d` from the first step. Valid windows are `1h`,
88
+ `1d`, `7d`, and `30d`. Filters apply to the first step, so a browser that
89
+ first arrived via Instagram can still count if it returned directly to sign up.
90
+ Use `--by source` to compare groups using the first step's source.
91
+
92
+ Grouping and filter fields are `name`, `source`, `campaign`, `medium`,
93
+ `content`, `page`, `device`, `browser`, `os`, `country`, `city`, and `day`.
94
+ Funnel grouping accepts every field except `name`. For sources, use the exact
95
+ labels returned by the events command, such as `utm:instagram`, `direct` or
96
+ `referrer:example.com`.
97
+
98
+ Example stdout (selected fields):
99
+
100
+ ```json
101
+ {
102
+ "site": "my-site",
103
+ "period": "30d",
104
+ "window": "7d",
105
+ "filters_apply_to": "first_step",
106
+ "data_status": "available",
107
+ "steps": [
108
+ {"name": "visit", "visitors": 120, "of_previous_percent": 100, "of_first_percent": 100},
109
+ {"name": "login", "visitors": 35, "of_previous_percent": 29.2, "of_first_percent": 29.2},
110
+ {"name": "signup_completed", "visitors": 12, "of_previous_percent": 34.3, "of_first_percent": 10}
111
+ ]
112
+ }
113
+ ```
114
+
115
+ Grouped funnels return `groups` with their own `steps`. Queries can return
116
+ `data_status: "not_installed"` or `"no_events"`. Check installation and
117
+ record a real test visit and interaction before interpreting those results.
@@ -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
+ }