@vellumai/cli 0.5.6 → 0.5.8

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/src/index.ts CHANGED
@@ -68,16 +68,16 @@ function printHelp(): void {
68
68
  " ps List assistants (or processes for a specific assistant)",
69
69
  );
70
70
  console.log(" recover Restore a previously retired local assistant");
71
- console.log(" restore Restore a .vbundle backup into a running assistant");
72
- console.log(" retire Delete an assistant instance");
73
71
  console.log(
74
- " rollback Roll back a Docker assistant to the previous version",
72
+ " restore Restore data (and optionally version) from a .vbundle backup",
75
73
  );
74
+ console.log(" retire Delete an assistant instance");
75
+ console.log(" rollback Roll back an assistant to a previous version");
76
76
  console.log(" setup Configure API keys interactively");
77
77
  console.log(" sleep Stop the assistant process");
78
78
  console.log(" ssh SSH into a remote assistant instance");
79
79
  console.log(" tunnel Create a tunnel for a locally hosted assistant");
80
- console.log(" upgrade Upgrade an assistant to the latest version");
80
+ console.log(" upgrade Upgrade an assistant to a newer version");
81
81
  console.log(" use Set the active assistant for commands");
82
82
  console.log(" wake Start the assistant and gateway");
83
83
  console.log(" whoami Show current logged-in user");
@@ -1,4 +1,12 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
1
+ import { randomBytes } from "crypto";
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "fs";
2
10
  import { homedir } from "os";
3
11
  import { join } from "path";
4
12
 
@@ -82,6 +90,14 @@ export interface AssistantEntry {
82
90
  previousServiceGroupVersion?: string;
83
91
  /** Docker image metadata from before the last upgrade. Enables rollback to the prior version. */
84
92
  previousContainerInfo?: ContainerInfo;
93
+ /** Path to the .vbundle backup created for the most recent upgrade. Used by rollback to restore
94
+ * only the backup from the specific upgrade being rolled back — never a stale backup from a
95
+ * previous upgrade cycle. */
96
+ preUpgradeBackupPath?: string;
97
+ /** Pre-upgrade DB migration version — used by rollback to know how far back to revert. */
98
+ previousDbMigrationVersion?: number;
99
+ /** Pre-upgrade workspace migration ID — used by rollback to know how far back to revert. */
100
+ previousWorkspaceMigrationId?: string;
85
101
  [key: string]: unknown;
86
102
  }
87
103
 
@@ -92,7 +108,7 @@ interface LockfileData {
92
108
  [key: string]: unknown;
93
109
  }
94
110
 
95
- function getBaseDir(): string {
111
+ export function getBaseDir(): string {
96
112
  return process.env.BASE_DATA_DIR?.trim() || homedir();
97
113
  }
98
114
 
@@ -124,7 +140,16 @@ function readLockfile(): LockfileData {
124
140
 
125
141
  function writeLockfile(data: LockfileData): void {
126
142
  const lockfilePath = join(getLockfileDir(), ".vellum.lock.json");
127
- writeFileSync(lockfilePath, JSON.stringify(data, null, 2) + "\n");
143
+ const tmpPath = `${lockfilePath}.${randomBytes(4).toString("hex")}.tmp`;
144
+ try {
145
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2) + "\n");
146
+ renameSync(tmpPath, lockfilePath);
147
+ } catch (err) {
148
+ try {
149
+ unlinkSync(tmpPath);
150
+ } catch {}
151
+ throw err;
152
+ }
128
153
  }
129
154
 
130
155
  /**
@@ -412,12 +437,14 @@ export async function allocateLocalResources(
412
437
  instanceName: string,
413
438
  ): Promise<LocalInstanceResources> {
414
439
  // First local assistant gets the home directory with default ports.
440
+ // Respect BASE_DATA_DIR when set (e.g. in e2e tests) so the daemon,
441
+ // gateway, and keychain broker all resolve paths under the same root.
415
442
  const existingLocals = loadAllAssistants().filter((e) => e.cloud === "local");
416
443
  if (existingLocals.length === 0) {
417
- const home = homedir();
418
- const vellumDir = join(home, ".vellum");
444
+ const baseDir = getBaseDir();
445
+ const vellumDir = join(baseDir, ".vellum");
419
446
  return {
420
- instanceDir: home,
447
+ instanceDir: baseDir,
421
448
  daemonPort: DEFAULT_DAEMON_PORT,
422
449
  gatewayPort: DEFAULT_GATEWAY_PORT,
423
450
  qdrantPort: DEFAULT_QDRANT_PORT,
package/src/lib/aws.ts CHANGED
@@ -374,6 +374,7 @@ export async function hatchAws(
374
374
  species: Species,
375
375
  detached: boolean,
376
376
  name: string | null,
377
+ configValues: Record<string, string> = {},
377
378
  ): Promise<void> {
378
379
  const startTime = Date.now();
379
380
  try {
@@ -442,13 +443,15 @@ export async function hatchAws(
442
443
  console.log("\u{1F50D} Finding latest Debian AMI...");
443
444
  const amiId = await getLatestDebianAmi(region);
444
445
 
445
- const startupScript = await buildStartupScript(
446
- species,
447
- sshUser,
448
- providerApiKeys,
449
- instanceName,
450
- "aws",
451
- );
446
+ const { script: startupScript, laptopBootstrapSecret } =
447
+ await buildStartupScript(
448
+ species,
449
+ sshUser,
450
+ providerApiKeys,
451
+ instanceName,
452
+ "aws",
453
+ configValues,
454
+ );
452
455
  const startupScriptPath = join(tmpdir(), `${instanceName}-startup.sh`);
453
456
  writeFileSync(startupScriptPath, startupScript);
454
457
 
@@ -537,7 +540,11 @@ export async function hatchAws(
537
540
  }
538
541
 
539
542
  try {
540
- await leaseGuardianToken(runtimeUrl, instanceName);
543
+ await leaseGuardianToken(
544
+ runtimeUrl,
545
+ instanceName,
546
+ laptopBootstrapSecret,
547
+ );
541
548
  } catch (err) {
542
549
  console.warn(
543
550
  `\u26a0\ufe0f Could not lease guardian token: ${err instanceof Error ? err.message : err}`,
@@ -0,0 +1,213 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readdirSync,
5
+ readFileSync,
6
+ unlinkSync,
7
+ writeFileSync,
8
+ } from "fs";
9
+ import { homedir } from "os";
10
+ import { dirname, join } from "path";
11
+
12
+ import { loadGuardianToken, leaseGuardianToken } from "./guardian-token.js";
13
+
14
+ /** Default backup directory following XDG convention */
15
+ export function getBackupsDir(): string {
16
+ const dataHome =
17
+ process.env.XDG_DATA_HOME?.trim() || join(homedir(), ".local", "share");
18
+ return join(dataHome, "vellum", "backups");
19
+ }
20
+
21
+ /** Human-readable file size */
22
+ export function formatSize(bytes: number): string {
23
+ if (bytes < 1024) return `${bytes} B`;
24
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
25
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
26
+ }
27
+
28
+ /** Obtain a valid guardian access token (cached or fresh lease) */
29
+ async function getGuardianAccessToken(
30
+ runtimeUrl: string,
31
+ assistantId: string,
32
+ forceRefresh?: boolean,
33
+ ): Promise<string> {
34
+ if (!forceRefresh) {
35
+ const tokenData = loadGuardianToken(assistantId);
36
+ if (tokenData && new Date(tokenData.accessTokenExpiresAt) > new Date()) {
37
+ return tokenData.accessToken;
38
+ }
39
+ }
40
+ const freshToken = await leaseGuardianToken(runtimeUrl, assistantId);
41
+ return freshToken.accessToken;
42
+ }
43
+
44
+ /**
45
+ * Create a .vbundle backup of a running assistant.
46
+ * Returns the path to the saved backup, or null if backup failed.
47
+ * Never throws — failures are logged as warnings.
48
+ */
49
+ export async function createBackup(
50
+ runtimeUrl: string,
51
+ assistantId: string,
52
+ options?: { prefix?: string; description?: string },
53
+ ): Promise<string | null> {
54
+ try {
55
+ let accessToken = await getGuardianAccessToken(runtimeUrl, assistantId);
56
+
57
+ let response = await fetch(`${runtimeUrl}/v1/migrations/export`, {
58
+ method: "POST",
59
+ headers: {
60
+ Authorization: `Bearer ${accessToken}`,
61
+ "Content-Type": "application/json",
62
+ },
63
+ body: JSON.stringify({
64
+ description: options?.description ?? "CLI backup",
65
+ }),
66
+ signal: AbortSignal.timeout(120_000),
67
+ });
68
+
69
+ // Retry once with a fresh token on 401 — the cached token may be stale
70
+ // after a container restart that generated a new gateway signing key.
71
+ if (response.status === 401) {
72
+ accessToken = await getGuardianAccessToken(runtimeUrl, assistantId, true);
73
+ response = await fetch(`${runtimeUrl}/v1/migrations/export`, {
74
+ method: "POST",
75
+ headers: {
76
+ Authorization: `Bearer ${accessToken}`,
77
+ "Content-Type": "application/json",
78
+ },
79
+ body: JSON.stringify({
80
+ description: options?.description ?? "CLI backup",
81
+ }),
82
+ signal: AbortSignal.timeout(120_000),
83
+ });
84
+ }
85
+
86
+ if (!response.ok) {
87
+ const body = await response.text();
88
+ console.warn(
89
+ `Warning: backup export failed (${response.status}): ${body}`,
90
+ );
91
+ return null;
92
+ }
93
+
94
+ const arrayBuffer = await response.arrayBuffer();
95
+ const data = new Uint8Array(arrayBuffer);
96
+
97
+ const isoTimestamp = new Date().toISOString().replace(/[:.]/g, "-");
98
+ const prefix = options?.prefix ?? assistantId;
99
+ const outputPath = join(
100
+ getBackupsDir(),
101
+ `${prefix}-${isoTimestamp}.vbundle`,
102
+ );
103
+
104
+ mkdirSync(dirname(outputPath), { recursive: true });
105
+ writeFileSync(outputPath, data);
106
+
107
+ return outputPath;
108
+ } catch (err) {
109
+ const msg = err instanceof Error ? err.message : String(err);
110
+ console.warn(`Warning: backup failed: ${msg}`);
111
+ return null;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Restore a .vbundle backup into a running assistant.
117
+ * Returns true if restore succeeded, false otherwise.
118
+ * Never throws — failures are logged as warnings.
119
+ */
120
+ export async function restoreBackup(
121
+ runtimeUrl: string,
122
+ assistantId: string,
123
+ backupPath: string,
124
+ ): Promise<boolean> {
125
+ try {
126
+ if (!existsSync(backupPath)) {
127
+ console.warn(`Warning: backup file not found: ${backupPath}`);
128
+ return false;
129
+ }
130
+
131
+ const bundleData = readFileSync(backupPath);
132
+ let accessToken = await getGuardianAccessToken(runtimeUrl, assistantId);
133
+
134
+ let response = await fetch(`${runtimeUrl}/v1/migrations/import`, {
135
+ method: "POST",
136
+ headers: {
137
+ Authorization: `Bearer ${accessToken}`,
138
+ "Content-Type": "application/octet-stream",
139
+ },
140
+ body: bundleData,
141
+ signal: AbortSignal.timeout(120_000),
142
+ });
143
+
144
+ // Retry once with a fresh token on 401 — the cached token may be stale
145
+ // after a container restart that generated a new gateway signing key.
146
+ if (response.status === 401) {
147
+ accessToken = await getGuardianAccessToken(runtimeUrl, assistantId, true);
148
+ response = await fetch(`${runtimeUrl}/v1/migrations/import`, {
149
+ method: "POST",
150
+ headers: {
151
+ Authorization: `Bearer ${accessToken}`,
152
+ "Content-Type": "application/octet-stream",
153
+ },
154
+ body: bundleData,
155
+ signal: AbortSignal.timeout(120_000),
156
+ });
157
+ }
158
+
159
+ if (!response.ok) {
160
+ const body = await response.text();
161
+ console.warn(`Warning: restore failed (${response.status}): ${body}`);
162
+ return false;
163
+ }
164
+
165
+ const result = (await response.json()) as {
166
+ success: boolean;
167
+ message?: string;
168
+ reason?: string;
169
+ };
170
+ if (!result.success) {
171
+ console.warn(
172
+ `Warning: restore failed — ${result.message ?? result.reason ?? "unknown reason"}`,
173
+ );
174
+ return false;
175
+ }
176
+
177
+ return true;
178
+ } catch (err) {
179
+ const msg = err instanceof Error ? err.message : String(err);
180
+ console.warn(`Warning: restore failed: ${msg}`);
181
+ return false;
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Keep only the N most recent pre-upgrade backups for an assistant,
187
+ * deleting older ones. Default: keep 3.
188
+ * Never throws — failures are silently ignored.
189
+ */
190
+ export function pruneOldBackups(assistantId: string, keep: number = 3): void {
191
+ try {
192
+ const backupsDir = getBackupsDir();
193
+ if (!existsSync(backupsDir)) return;
194
+
195
+ const prefix = `${assistantId}-pre-upgrade-`;
196
+ const entries = readdirSync(backupsDir)
197
+ .filter((f) => f.startsWith(prefix) && f.endsWith(".vbundle"))
198
+ .sort();
199
+
200
+ if (entries.length <= keep) return;
201
+
202
+ const toDelete = entries.slice(0, entries.length - keep);
203
+ for (const file of toDelete) {
204
+ try {
205
+ unlinkSync(join(backupsDir, file));
206
+ } catch {
207
+ // Best-effort cleanup — ignore individual file errors
208
+ }
209
+ }
210
+ } catch {
211
+ // Best-effort cleanup — never block the upgrade
212
+ }
213
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Structured CLI error reporting for upgrade/rollback commands.
3
+ *
4
+ * When a CLI command fails, it can emit a machine-readable JSON object
5
+ * prefixed with `CLI_ERROR:` to stderr so that consumers (e.g. the
6
+ * desktop app) can parse it reliably. Modeled after the DAEMON_ERROR
7
+ * protocol in `assistant/src/daemon/startup-error.ts`.
8
+ */
9
+
10
+ /** Known error categories emitted by CLI commands. */
11
+ export type CliErrorCategory =
12
+ | "DOCKER_NOT_RUNNING"
13
+ | "IMAGE_PULL_FAILED"
14
+ | "MISSING_VERSION"
15
+ | "READINESS_TIMEOUT"
16
+ | "ROLLBACK_FAILED"
17
+ | "ROLLBACK_NO_STATE"
18
+ | "VERSION_DIRECTION"
19
+ | "AUTH_FAILED"
20
+ | "NETWORK_ERROR"
21
+ | "UNSUPPORTED_TOPOLOGY"
22
+ | "ASSISTANT_NOT_FOUND"
23
+ | "PLATFORM_API_ERROR"
24
+ | "UNKNOWN";
25
+
26
+ interface CliErrorPayload {
27
+ error: CliErrorCategory;
28
+ message: string;
29
+ detail?: string;
30
+ }
31
+
32
+ const CLI_ERROR_PREFIX = "CLI_ERROR:";
33
+
34
+ /**
35
+ * Write a structured error line to stderr. The line is prefixed with
36
+ * `CLI_ERROR:` followed by JSON, making it unambiguous even if other
37
+ * stderr output precedes it.
38
+ */
39
+ export function emitCliError(
40
+ category: CliErrorCategory,
41
+ message: string,
42
+ detail?: string,
43
+ ): void {
44
+ const payload: CliErrorPayload = { error: category, message, detail };
45
+ const line = `${CLI_ERROR_PREFIX}${JSON.stringify(payload)}`;
46
+ process.stderr.write(line + "\n");
47
+ }
48
+
49
+ /**
50
+ * Inspect an error string and return the most appropriate
51
+ * {@link CliErrorCategory} for common upgrade/rollback failures.
52
+ */
53
+ export function categorizeUpgradeError(err: unknown): CliErrorCategory {
54
+ const msg = String(err).toLowerCase();
55
+
56
+ if (
57
+ msg.includes("cannot connect to the docker") ||
58
+ msg.includes("is docker running")
59
+ ) {
60
+ return "DOCKER_NOT_RUNNING";
61
+ }
62
+
63
+ if (
64
+ msg.includes("manifest unknown") ||
65
+ msg.includes("manifest not found") ||
66
+ msg.includes("pull access denied") ||
67
+ msg.includes("repository does not exist")
68
+ ) {
69
+ return "IMAGE_PULL_FAILED";
70
+ }
71
+
72
+ if (msg.includes("timeout") || msg.includes("readyz")) {
73
+ return "READINESS_TIMEOUT";
74
+ }
75
+
76
+ if (
77
+ msg.includes("401") ||
78
+ msg.includes("403") ||
79
+ msg.includes("unauthorized")
80
+ ) {
81
+ return "AUTH_FAILED";
82
+ }
83
+
84
+ if (
85
+ msg.includes("enotfound") ||
86
+ msg.includes("econnrefused") ||
87
+ msg.includes("network")
88
+ ) {
89
+ return "NETWORK_ERROR";
90
+ }
91
+
92
+ return "UNKNOWN";
93
+ }
@@ -0,0 +1,59 @@
1
+ import { writeFileSync } from "fs";
2
+ import { tmpdir } from "os";
3
+ import { join } from "path";
4
+
5
+ /**
6
+ * Convert flat dot-notation key=value pairs into a nested config object.
7
+ *
8
+ * e.g. {"services.inference.provider": "anthropic", "services.inference.model": "claude-opus-4-6"}
9
+ * → {services: {inference: {provider: "anthropic", model: "claude-opus-4-6"}}}
10
+ */
11
+ export function buildNestedConfig(
12
+ configValues: Record<string, string>,
13
+ ): Record<string, unknown> {
14
+ const config: Record<string, unknown> = {};
15
+ for (const [dotKey, value] of Object.entries(configValues)) {
16
+ const parts = dotKey.split(".");
17
+ let target: Record<string, unknown> = config;
18
+ for (let i = 0; i < parts.length - 1; i++) {
19
+ const part = parts[i];
20
+ const existing = target[part];
21
+ if (
22
+ existing == null ||
23
+ typeof existing !== "object" ||
24
+ Array.isArray(existing)
25
+ ) {
26
+ target[part] = {};
27
+ }
28
+ target = target[part] as Record<string, unknown>;
29
+ }
30
+ target[parts[parts.length - 1]] = value;
31
+ }
32
+ return config;
33
+ }
34
+
35
+ /**
36
+ * Write arbitrary key-value pairs to a temporary JSON file and return its
37
+ * path. The caller passes this path to the daemon via the
38
+ * VELLUM_DEFAULT_WORKSPACE_CONFIG_PATH env var so the daemon can merge the
39
+ * values into its workspace config on first boot.
40
+ *
41
+ * Keys use dot-notation to address nested fields. For example:
42
+ * "services.inference.provider" → {services: {inference: {provider: ...}}}
43
+ * "services.inference.model" → {services: {inference: {model: ...}}}
44
+ *
45
+ * Returns undefined when configValues is empty (nothing to write).
46
+ */
47
+ export function writeInitialConfig(
48
+ configValues: Record<string, string>,
49
+ ): string | undefined {
50
+ if (Object.keys(configValues).length === 0) return undefined;
51
+
52
+ const config = buildNestedConfig(configValues);
53
+ const tempPath = join(
54
+ tmpdir(),
55
+ `vellum-default-workspace-config-${process.pid}-${Date.now()}.json`,
56
+ );
57
+ writeFileSync(tempPath, JSON.stringify(config, null, 2) + "\n");
58
+ return tempPath;
59
+ }