@singularity-layer/agentvault 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,52 @@
1
+ export const LABEL = "com.agentvault.backup";
2
+ /** Generate a launchd plist that runs `agentvault backup --all --non-interactive` on schedule. */
3
+ export function launchdPlist(opts) {
4
+ const calendar = opts.frequency === "weekly"
5
+ ? " <key>Weekday</key>\n <integer>0</integer>\n <key>Hour</key>\n <integer>3</integer>\n <key>Minute</key>\n <integer>0</integer>"
6
+ : " <key>Hour</key>\n <integer>3</integer>\n <key>Minute</key>\n <integer>0</integer>";
7
+ return `<?xml version="1.0" encoding="UTF-8"?>
8
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
9
+ <plist version="1.0">
10
+ <dict>
11
+ <key>Label</key>
12
+ <string>${LABEL}</string>
13
+ <key>ProgramArguments</key>
14
+ <array>
15
+ <string>${opts.binPath}</string>
16
+ <string>backup</string>
17
+ <string>--all</string>
18
+ <string>--non-interactive</string>
19
+ </array>
20
+ <key>StartCalendarInterval</key>
21
+ <dict>
22
+ ${calendar}
23
+ </dict>
24
+ <key>RunAtLoad</key>
25
+ <false/>
26
+ </dict>
27
+ </plist>
28
+ `;
29
+ }
30
+ /** Generate a systemd user service unit. */
31
+ export function systemdService(opts) {
32
+ return `[Unit]
33
+ Description=Agent Vault automatic backup
34
+
35
+ [Service]
36
+ Type=oneshot
37
+ ExecStart=${opts.binPath} backup --all --non-interactive
38
+ `;
39
+ }
40
+ /** Generate a systemd user timer unit for the given frequency. */
41
+ export function systemdTimer(frequency) {
42
+ return `[Unit]
43
+ Description=Agent Vault automatic backup timer
44
+
45
+ [Timer]
46
+ OnCalendar=${frequency}
47
+ Persistent=true
48
+
49
+ [Install]
50
+ WantedBy=timers.target
51
+ `;
52
+ }
package/dist/deps.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { homedir } from "node:os";
2
+ import { encrypt, packAgent, restoreBlob, uploadBlob } from "@singularity-layer/agentvault-core";
3
+ import type { DetectedAgent } from "@singularity-layer/agentvault-core";
4
+ import { createClient } from "./client.js";
5
+ import { createConfigStore } from "./config.js";
6
+ import { createKeychain } from "./keychain.js";
7
+ export declare function defaultDiscover(): DetectedAgent[];
8
+ export declare function downloadBlob(url: string): Promise<Buffer>;
9
+ export declare function authedClient(): {
10
+ client: import("./client.js").ApiClient;
11
+ store: import("./config.js").ConfigStore;
12
+ };
13
+ export declare const realDaemonFs: {
14
+ writeFile(path: string, content: string): void;
15
+ removeFile(path: string): void;
16
+ exists(path: string): boolean;
17
+ };
18
+ export declare function realExec(cmd: string, args: string[]): Promise<{
19
+ code: number;
20
+ stdout: string;
21
+ }>;
22
+ /** Resolve an ABSOLUTE path to the agentvault binary for the daemon to exec. */
23
+ export declare function resolveBinPath(): string;
24
+ export declare const realCore: {
25
+ discover: typeof defaultDiscover;
26
+ packAgent: typeof packAgent;
27
+ encrypt: typeof encrypt;
28
+ uploadBlob: typeof uploadBlob;
29
+ restoreBlob: typeof restoreBlob;
30
+ downloadBlob: typeof downloadBlob;
31
+ };
32
+ export declare const realIo: {
33
+ prompter: import("./io.js").Prompter;
34
+ logger: import("./io.js").Logger;
35
+ };
36
+ export { createConfigStore, createClient, createKeychain };
37
+ export { homedir };
38
+ /** Best-effort browser open; the printed URL is the fallback on failure. */
39
+ export declare function openBrowser(url: string): void;
package/dist/deps.js ADDED
@@ -0,0 +1,104 @@
1
+ import { execFile, execFileSync, spawn } from "node:child_process";
2
+ import { existsSync, mkdirSync, realpathSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname } from "node:path";
5
+ import { createRegistry, discover, encrypt, hermesAdapter, openclawAdapter, packAgent, restoreBlob, uploadBlob, } from "@singularity-layer/agentvault-core";
6
+ import { createClient } from "./client.js";
7
+ import { createConfigStore } from "./config.js";
8
+ import { clackPrompter, consoleLogger } from "./io.js";
9
+ import { createKeychain } from "./keychain.js";
10
+ export function defaultDiscover() {
11
+ const registry = createRegistry();
12
+ registry.register(openclawAdapter);
13
+ registry.register(hermesAdapter);
14
+ return discover(registry);
15
+ }
16
+ export async function downloadBlob(url) {
17
+ const res = await fetch(url);
18
+ if (!res.ok)
19
+ throw new Error(`download failed: ${res.status}`);
20
+ return Buffer.from(await res.arrayBuffer());
21
+ }
22
+ export function authedClient() {
23
+ const store = createConfigStore();
24
+ const cfg = store.load();
25
+ if (!cfg.token)
26
+ throw new Error("Not logged in. Run `agentvault login` first.");
27
+ return { client: createClient(cfg.apiUrl, cfg.token), store };
28
+ }
29
+ export const realDaemonFs = {
30
+ writeFile(path, content) {
31
+ mkdirSync(dirname(path), { recursive: true });
32
+ writeFileSync(path, content);
33
+ },
34
+ removeFile(path) {
35
+ rmSync(path, { force: true });
36
+ },
37
+ exists(path) {
38
+ return existsSync(path);
39
+ },
40
+ };
41
+ export function realExec(cmd, args) {
42
+ return new Promise((resolve) => {
43
+ execFile(cmd, args, (err, stdout) => {
44
+ resolve({
45
+ code: err && typeof err.code === "number"
46
+ ? err.code
47
+ : err
48
+ ? 1
49
+ : 0,
50
+ stdout: stdout ?? "",
51
+ });
52
+ });
53
+ });
54
+ }
55
+ /** Resolve an ABSOLUTE path to the agentvault binary for the daemon to exec. */
56
+ export function resolveBinPath() {
57
+ const argv1 = process.argv[1];
58
+ if (argv1?.includes("agentvault")) {
59
+ try {
60
+ return realpathSync(argv1);
61
+ }
62
+ catch {
63
+ /* fall through */
64
+ }
65
+ }
66
+ try {
67
+ const found = execFileSync("which", ["agentvault"], {
68
+ encoding: "utf8",
69
+ }).trim();
70
+ if (found)
71
+ return found;
72
+ }
73
+ catch {
74
+ /* fall through */
75
+ }
76
+ return argv1 ?? "agentvault";
77
+ }
78
+ export const realCore = {
79
+ discover: defaultDiscover,
80
+ packAgent,
81
+ encrypt,
82
+ uploadBlob,
83
+ restoreBlob,
84
+ downloadBlob,
85
+ };
86
+ export const realIo = { prompter: clackPrompter, logger: consoleLogger };
87
+ export { createConfigStore, createClient, createKeychain };
88
+ export { homedir };
89
+ /** Best-effort browser open; the printed URL is the fallback on failure. */
90
+ export function openBrowser(url) {
91
+ const opener = process.platform === "darwin"
92
+ ? "open"
93
+ : process.platform === "win32"
94
+ ? "start"
95
+ : "xdg-open";
96
+ try {
97
+ const child = spawn(opener, [url], { detached: true, stdio: "ignore" });
98
+ child.unref();
99
+ child.on("error", () => { });
100
+ }
101
+ catch {
102
+ // headless box — the user opens the printed URL themselves
103
+ }
104
+ }
@@ -0,0 +1,23 @@
1
+ type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
2
+ export declare const DEFAULT_GRID_URL = "https://grid.x402compute.cc";
3
+ export interface DeviceStart {
4
+ deviceCode: string;
5
+ userCode: string;
6
+ verifyUrl: string;
7
+ intervalSeconds: number;
8
+ expiresInSeconds: number;
9
+ }
10
+ export type DevicePoll = {
11
+ status: "pending";
12
+ } | {
13
+ status: "expired";
14
+ } | {
15
+ status: "approved";
16
+ apiKey: string;
17
+ };
18
+ export interface DeviceAuthClient {
19
+ start(label: string): Promise<DeviceStart>;
20
+ poll(deviceCode: string): Promise<DevicePoll>;
21
+ }
22
+ export declare function createDeviceAuth(gridUrl?: string, fetchImpl?: FetchLike): DeviceAuthClient;
23
+ export {};
@@ -0,0 +1,42 @@
1
+ // Browser device-authorization login — the same flow `sgl login` (node) and
2
+ // `sglcode login` use. The CLI asks the grid orchestrator for a session, the
3
+ // user approves it in the cloud dashboard with their real wallet, and the
4
+ // orchestrator mints a compute API key delivered to the poll EXACTLY ONCE.
5
+ // Net result is identical to pasting an API key by hand; this is just the
6
+ // zero-copy-paste path.
7
+ export const DEFAULT_GRID_URL = "https://grid.x402compute.cc";
8
+ export function createDeviceAuth(gridUrl = DEFAULT_GRID_URL, fetchImpl = fetch) {
9
+ async function call(path, body) {
10
+ const res = await fetchImpl(`${gridUrl}${path}`, {
11
+ method: "POST",
12
+ headers: { "content-type": "application/json" },
13
+ body: JSON.stringify(body),
14
+ });
15
+ const data = (await res.json().catch(() => ({})));
16
+ if (!res.ok)
17
+ throw new Error(data.error ?? `device auth failed: ${res.status}`);
18
+ return data;
19
+ }
20
+ return {
21
+ async start(label) {
22
+ const d = await call("/grid/auth/device/start", { purpose: "cli", label });
23
+ if (!d.device_code || !d.verify_url)
24
+ throw new Error("device auth returned an incomplete session");
25
+ return {
26
+ deviceCode: d.device_code,
27
+ userCode: d.user_code,
28
+ verifyUrl: d.verify_url,
29
+ intervalSeconds: d.interval || 3,
30
+ expiresInSeconds: d.expires_in || 600,
31
+ };
32
+ },
33
+ async poll(deviceCode) {
34
+ const d = await call("/grid/auth/device/poll", { device_code: deviceCode });
35
+ if (d.status === "approved" && d.api_key)
36
+ return { status: "approved", apiKey: d.api_key };
37
+ if (d.status === "expired")
38
+ return { status: "expired" };
39
+ return { status: "pending" };
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ export declare function buildProgram(): Command;
package/dist/index.js ADDED
@@ -0,0 +1,164 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { createClient } from "./client.js";
4
+ import { runBackup } from "./commands/backup.js";
5
+ import { runDaemonInstall, runDaemonStatus, runDaemonUninstall, runOfferDaemon, } from "./commands/daemon.js";
6
+ import { runList } from "./commands/list.js";
7
+ import { runBrowserLogin, runLogin } from "./commands/login.js";
8
+ import { runLogout } from "./commands/logout.js";
9
+ import { createDeviceAuth } from "./deviceAuth.js";
10
+ import { openBrowser } from "./deps.js";
11
+ import { keychainPassphraseOrThrow, runPassphraseClear, runPassphraseSet, } from "./commands/passphrase.js";
12
+ import { runRestore } from "./commands/restore.js";
13
+ import { createConfigStore } from "./config.js";
14
+ import { authedClient, downloadBlob, homedir, realCore, realDaemonFs, realExec, realIo, resolveBinPath, } from "./deps.js";
15
+ import { createKeychain } from "./keychain.js";
16
+ export function buildProgram() {
17
+ const program = new Command();
18
+ program
19
+ .name("agentvault")
20
+ .description("Encrypted backups for local AI agents")
21
+ .version("0.0.0");
22
+ program
23
+ .command("login")
24
+ .description("Sign in (browser wallet approval; --api-key to paste a key)")
25
+ .option("--api-key", "paste a compute API key instead of the browser flow", false)
26
+ .action(async (opts) => {
27
+ const store = createConfigStore();
28
+ const verify = (apiKey) => createClient(store.load().apiUrl, apiKey).verifyKey();
29
+ if (opts.apiKey) {
30
+ await runLogin({
31
+ verify,
32
+ store,
33
+ prompter: realIo.prompter,
34
+ logger: realIo.logger,
35
+ });
36
+ return;
37
+ }
38
+ await runBrowserLogin({
39
+ device: createDeviceAuth(),
40
+ verify,
41
+ store,
42
+ logger: realIo.logger,
43
+ openUrl: openBrowser,
44
+ });
45
+ });
46
+ program
47
+ .command("logout")
48
+ .description("Log out")
49
+ .action(async () => {
50
+ await runLogout({ store: createConfigStore(), logger: realIo.logger });
51
+ });
52
+ program
53
+ .command("backup")
54
+ .description("Back up local agents")
55
+ .option("--all", "back up all detected agents", false)
56
+ .option("--non-interactive", "use the stored passphrase (no prompts)", false)
57
+ .action(async (opts) => {
58
+ const { client } = authedClient();
59
+ const keychain = createKeychain();
60
+ const nonInteractive = Boolean(opts.nonInteractive);
61
+ const resolvePassphrase = nonInteractive
62
+ ? () => keychainPassphraseOrThrow(keychain)
63
+ : () => realIo.prompter.password("Backup passphrase (you'll need this to restore)");
64
+ await runBackup({
65
+ client,
66
+ discover: realCore.discover,
67
+ packAgent: realCore.packAgent,
68
+ encrypt: realCore.encrypt,
69
+ uploadBlob: realCore.uploadBlob,
70
+ resolvePassphrase,
71
+ prompter: realIo.prompter,
72
+ logger: realIo.logger,
73
+ offerDaemon: () => runOfferDaemon({
74
+ platform: process.platform,
75
+ home: homedir(),
76
+ binPath: resolveBinPath(),
77
+ fs: realDaemonFs,
78
+ exec: realExec,
79
+ logger: realIo.logger,
80
+ prompter: realIo.prompter,
81
+ nonInteractive,
82
+ }),
83
+ }, { all: Boolean(opts.all) || nonInteractive });
84
+ });
85
+ program
86
+ .command("restore")
87
+ .description("Restore an agent backup")
88
+ .option("--dest <dir>", "destination directory", process.cwd())
89
+ .action(async (opts) => {
90
+ const { client } = authedClient();
91
+ await runRestore({
92
+ client,
93
+ downloadBlob,
94
+ restoreBlob: realCore.restoreBlob,
95
+ prompter: realIo.prompter,
96
+ logger: realIo.logger,
97
+ }, { dest: opts.dest });
98
+ });
99
+ program
100
+ .command("list")
101
+ .description("List agents and backups")
102
+ .action(async () => {
103
+ const { client } = authedClient();
104
+ await runList({ client, logger: realIo.logger });
105
+ });
106
+ const passphrase = program
107
+ .command("passphrase")
108
+ .description("Manage the stored backup passphrase");
109
+ passphrase
110
+ .command("set")
111
+ .description("Store a passphrase for automatic backups")
112
+ .action(async () => {
113
+ await runPassphraseSet({
114
+ keychain: createKeychain(),
115
+ prompter: realIo.prompter,
116
+ logger: realIo.logger,
117
+ });
118
+ });
119
+ passphrase
120
+ .command("clear")
121
+ .description("Remove the stored passphrase")
122
+ .action(async () => {
123
+ await runPassphraseClear({
124
+ keychain: createKeychain(),
125
+ logger: realIo.logger,
126
+ });
127
+ });
128
+ const daemon = program
129
+ .command("daemon")
130
+ .description("Manage automatic scheduled backups");
131
+ const daemonDeps = () => ({
132
+ platform: process.platform,
133
+ home: homedir(),
134
+ binPath: resolveBinPath(),
135
+ fs: realDaemonFs,
136
+ exec: realExec,
137
+ logger: realIo.logger,
138
+ });
139
+ daemon
140
+ .command("install")
141
+ .description("Install automatic backups")
142
+ .option("--frequency <freq>", "weekly or daily", "weekly")
143
+ .action(async (opts) => {
144
+ await runDaemonInstall(daemonDeps(), {
145
+ frequency: opts.frequency === "daily" ? "daily" : "weekly",
146
+ });
147
+ });
148
+ daemon
149
+ .command("uninstall")
150
+ .description("Remove automatic backups")
151
+ .action(async () => {
152
+ await runDaemonUninstall(daemonDeps());
153
+ });
154
+ daemon
155
+ .command("status")
156
+ .description("Show automatic backup status")
157
+ .action(async () => {
158
+ await runDaemonStatus(daemonDeps());
159
+ });
160
+ return program;
161
+ }
162
+ if (process.argv[1]?.endsWith("index.js")) {
163
+ buildProgram().parseAsync(process.argv);
164
+ }
package/dist/io.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ export interface SelectOption {
2
+ value: string;
3
+ label: string;
4
+ }
5
+ export interface Prompter {
6
+ text(message: string): Promise<string>;
7
+ password(message: string): Promise<string>;
8
+ select(message: string, options: SelectOption[]): Promise<string>;
9
+ confirm(message: string): Promise<boolean>;
10
+ }
11
+ export interface Logger {
12
+ info(text: string): void;
13
+ success(text: string): void;
14
+ error(text: string): void;
15
+ }
16
+ /** Real prompter backed by @clack/prompts. Cancelling (Ctrl-C) exits the process. */
17
+ export declare const clackPrompter: Prompter;
18
+ export declare const consoleLogger: Logger;
19
+ export declare function createFakePrompter(answers: {
20
+ text?: string[];
21
+ password?: string[];
22
+ select?: string[];
23
+ confirm?: boolean[];
24
+ }): Prompter;
25
+ export interface LoggedMessage {
26
+ level: "info" | "success" | "error";
27
+ text: string;
28
+ }
29
+ export interface MemoryLogger extends Logger {
30
+ messages: LoggedMessage[];
31
+ }
32
+ export declare function createMemoryLogger(): MemoryLogger;
package/dist/io.js ADDED
@@ -0,0 +1,76 @@
1
+ import { confirm, isCancel, password, select, text } from "@clack/prompts";
2
+ /** Real prompter backed by @clack/prompts. Cancelling (Ctrl-C) exits the process. */
3
+ export const clackPrompter = {
4
+ async text(message) {
5
+ const v = await text({ message });
6
+ if (isCancel(v))
7
+ process.exit(1);
8
+ return v;
9
+ },
10
+ async password(message) {
11
+ const v = await password({ message });
12
+ if (isCancel(v))
13
+ process.exit(1);
14
+ return v;
15
+ },
16
+ async select(message, options) {
17
+ const v = await select({ message, options });
18
+ if (isCancel(v))
19
+ process.exit(1);
20
+ return v;
21
+ },
22
+ async confirm(message) {
23
+ const v = await confirm({ message });
24
+ if (isCancel(v))
25
+ process.exit(1);
26
+ return v;
27
+ },
28
+ };
29
+ export const consoleLogger = {
30
+ info: (t) => console.log(t),
31
+ success: (t) => console.log(`✓ ${t}`),
32
+ error: (t) => console.error(`✗ ${t}`),
33
+ };
34
+ // ---- test helpers ----
35
+ export function createFakePrompter(answers) {
36
+ const q = {
37
+ text: [...(answers.text ?? [])],
38
+ password: [...(answers.password ?? [])],
39
+ select: [...(answers.select ?? [])],
40
+ confirm: [...(answers.confirm ?? [])],
41
+ };
42
+ const next = (arr, kind) => {
43
+ if (arr.length === 0)
44
+ throw new Error(`fake prompter: no more ${kind} answers queued`);
45
+ return arr.shift();
46
+ };
47
+ return {
48
+ async text() {
49
+ return next(q.text, "text");
50
+ },
51
+ async password() {
52
+ return next(q.password, "password");
53
+ },
54
+ async select() {
55
+ return next(q.select, "select");
56
+ },
57
+ async confirm() {
58
+ return next(q.confirm, "confirm");
59
+ },
60
+ };
61
+ }
62
+ export function createMemoryLogger() {
63
+ const messages = [];
64
+ return {
65
+ messages,
66
+ info: (t) => {
67
+ messages.push({ level: "info", text: t });
68
+ },
69
+ success: (t) => {
70
+ messages.push({ level: "success", text: t });
71
+ },
72
+ error: (t) => {
73
+ messages.push({ level: "error", text: t });
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,20 @@
1
+ export interface Keychain {
2
+ get(account: string): Promise<string | null>;
3
+ set(account: string, secret: string): Promise<void>;
4
+ delete(account: string): Promise<void>;
5
+ }
6
+ export interface KeychainCommand {
7
+ cmd: string;
8
+ args: string[];
9
+ secretViaStdin: boolean;
10
+ secretAsLastArg: boolean;
11
+ /** How many newline-terminated copies of the secret stdin expects (macOS `security` asks twice). */
12
+ secretStdinRepeat?: number;
13
+ }
14
+ /** Build the OS keychain CLI invocation for an operation. Pure + testable. */
15
+ export declare function buildKeychainCommand(platform: NodeJS.Platform, op: "get" | "set" | "delete", account: string, service: string): KeychainCommand;
16
+ /** Real OS keychain backed by `security` (macOS) / `secret-tool` (Linux). */
17
+ export declare function createKeychain(platform?: NodeJS.Platform): Keychain;
18
+ /** In-memory keychain for tests. */
19
+ export declare function createFakeKeychain(): Keychain;
20
+ export declare const PASSPHRASE_ACCOUNT = "agentvault-passphrase";