@capybara-hq/device 0.0.0-stage → 0.1.0-rc.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.
Files changed (61) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +103 -2
  4. package/bin/capybara-device.mjs +11 -0
  5. package/dist/api.d.ts +33 -0
  6. package/dist/api.js +48 -0
  7. package/dist/args.d.ts +39 -0
  8. package/dist/args.js +93 -0
  9. package/dist/cli.d.ts +18 -0
  10. package/dist/cli.js +93 -0
  11. package/dist/client.d.ts +39 -0
  12. package/dist/client.js +340 -0
  13. package/dist/command-log.d.ts +17 -0
  14. package/dist/command-log.js +28 -0
  15. package/dist/commands/drain.d.ts +2 -0
  16. package/dist/commands/drain.js +5 -0
  17. package/dist/commands/login.d.ts +20 -0
  18. package/dist/commands/login.js +132 -0
  19. package/dist/commands/logout.d.ts +13 -0
  20. package/dist/commands/logout.js +36 -0
  21. package/dist/commands/policy.d.ts +15 -0
  22. package/dist/commands/policy.js +74 -0
  23. package/dist/commands/service.d.ts +17 -0
  24. package/dist/commands/service.js +97 -0
  25. package/dist/commands/signal.d.ts +2 -0
  26. package/dist/commands/signal.js +18 -0
  27. package/dist/commands/start.d.ts +16 -0
  28. package/dist/commands/start.js +73 -0
  29. package/dist/commands/status.d.ts +2 -0
  30. package/dist/commands/status.js +32 -0
  31. package/dist/commands/stop.d.ts +2 -0
  32. package/dist/commands/stop.js +5 -0
  33. package/dist/exec/docker.d.ts +120 -0
  34. package/dist/exec/docker.js +673 -0
  35. package/dist/exec/fs-helper.d.ts +12 -0
  36. package/dist/exec/fs-helper.js +85 -0
  37. package/dist/exec/os.d.ts +80 -0
  38. package/dist/exec/os.js +398 -0
  39. package/dist/exec/procs.d.ts +11 -0
  40. package/dist/exec/procs.js +67 -0
  41. package/dist/exec/shared.d.ts +71 -0
  42. package/dist/exec/shared.js +240 -0
  43. package/dist/exec/types.d.ts +34 -0
  44. package/dist/exec/types.js +9 -0
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.js +3 -0
  47. package/dist/pid.d.ts +6 -0
  48. package/dist/pid.js +36 -0
  49. package/dist/policy.d.ts +42 -0
  50. package/dist/policy.js +97 -0
  51. package/dist/server-ops.d.ts +10 -0
  52. package/dist/server-ops.js +74 -0
  53. package/dist/service/launchd.d.ts +17 -0
  54. package/dist/service/launchd.js +59 -0
  55. package/dist/service/systemd.d.ts +5 -0
  56. package/dist/service/systemd.js +28 -0
  57. package/dist/state.d.ts +40 -0
  58. package/dist/state.js +117 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +11 -0
  61. package/package.json +42 -3
@@ -0,0 +1,59 @@
1
+ import { copyFileSync, statSync, truncateSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ export const LAUNCHD_LABEL = "top.capybara.device";
4
+ export function plistPath(home) {
5
+ return join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
6
+ }
7
+ function xml(s) {
8
+ return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
9
+ }
10
+ /** The launchd agent: `node <bin> start`, at login, restarted when it exits with a failure (a clean stop stays stopped). */
11
+ export function plistContent(spec) {
12
+ const env = Object.entries(spec.env)
13
+ .map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
14
+ .join("\n");
15
+ return `<?xml version="1.0" encoding="UTF-8"?>
16
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
17
+ <plist version="1.0">
18
+ <dict>
19
+ <key>Label</key>
20
+ <string>${LAUNCHD_LABEL}</string>
21
+ <key>ProgramArguments</key>
22
+ <array>
23
+ <string>${xml(spec.nodePath)}</string>
24
+ <string>${xml(spec.binPath)}</string>
25
+ <string>start</string>
26
+ </array>
27
+ <key>RunAtLoad</key>
28
+ <true/>
29
+ <key>KeepAlive</key>
30
+ <dict>
31
+ <key>SuccessfulExit</key>
32
+ <false/>
33
+ </dict>
34
+ <key>EnvironmentVariables</key>
35
+ <dict>
36
+ ${env}
37
+ </dict>
38
+ <key>StandardOutPath</key>
39
+ <string>${xml(join(spec.stateDir, "service.log"))}</string>
40
+ <key>StandardErrorPath</key>
41
+ <string>${xml(join(spec.stateDir, "service.log"))}</string>
42
+ </dict>
43
+ </plist>
44
+ `;
45
+ }
46
+ export const SERVICE_LOG_MAX_BYTES = 10 * 1024 * 1024;
47
+ /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
48
+ export function rotateServiceLog(stateDir, maxBytes = SERVICE_LOG_MAX_BYTES) {
49
+ const file = join(stateDir, "service.log");
50
+ try {
51
+ if (statSync(file).size < maxBytes)
52
+ return;
53
+ copyFileSync(file, `${file}.1`);
54
+ truncateSync(file, 0);
55
+ }
56
+ catch {
57
+ // No log yet, or not ours to rotate.
58
+ }
59
+ }
@@ -0,0 +1,5 @@
1
+ import type { ServiceSpec } from "./launchd.js";
2
+ export declare const SYSTEMD_UNIT = "capybara-device.service";
3
+ export declare function unitPath(home: string): string;
4
+ /** The systemd user unit: `node <bin> start`, restarted on failure, wanted by the default target. */
5
+ export declare function unitContent(spec: ServiceSpec): string;
@@ -0,0 +1,28 @@
1
+ import { join } from "node:path";
2
+ export const SYSTEMD_UNIT = "capybara-device.service";
3
+ export function unitPath(home) {
4
+ return join(home, ".config", "systemd", "user", SYSTEMD_UNIT);
5
+ }
6
+ /** A systemd word: quoted, with `\`, `"` and the specifier `%` escaped. */
7
+ function word(s) {
8
+ return `"${s.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%")}"`;
9
+ }
10
+ /** The systemd user unit: `node <bin> start`, restarted on failure, wanted by the default target. */
11
+ export function unitContent(spec) {
12
+ const env = Object.entries(spec.env)
13
+ .map(([k, v]) => `Environment=${word(`${k}=${v}`)}`)
14
+ .join("\n");
15
+ return `[Unit]
16
+ Description=capybara-device: connects this machine to a Capybara deployment
17
+ After=network-online.target
18
+
19
+ [Service]
20
+ ExecStart=${word(spec.nodePath)} ${word(spec.binPath)} start
21
+ Restart=on-failure
22
+ RestartSec=5
23
+ ${env}
24
+
25
+ [Install]
26
+ WantedBy=default.target
27
+ `;
28
+ }
@@ -0,0 +1,40 @@
1
+ import type { DeviceMode } from "./args.js";
2
+ /** What `login` stores: how to reach the deployment and who this machine is there. */
3
+ export interface Credential {
4
+ url: string;
5
+ connectUrl: string;
6
+ credential: string;
7
+ orgId: string;
8
+ environmentId: string;
9
+ dir: string;
10
+ mode: DeviceMode;
11
+ /** The deployment's `environments.device.reconnectGraceSeconds`, returned with the credential. */
12
+ reconnectGraceSeconds: number;
13
+ /** The deployment's `environments.device.maxFrameBytes`: no frame this program sends is larger. */
14
+ maxFrameBytes: number;
15
+ }
16
+ /** Local limits the person sets for this machine. */
17
+ export interface Policy {
18
+ allowedDomains: string[];
19
+ allowCredentials: string[];
20
+ cpu: number | null;
21
+ memoryMb: number | null;
22
+ }
23
+ export declare const DEFAULT_MAX_FRAME_BYTES: number;
24
+ export declare const DEFAULT_POLICY: Policy;
25
+ type Env = Record<string, string | undefined>;
26
+ /** `$XDG_CONFIG_HOME/capybara-device`, or `~/.config/capybara-device`. */
27
+ export declare function stateDir(env?: Env, home?: string): string;
28
+ export declare function credentialPath(dir: string): string;
29
+ export declare function policyPath(dir: string): string;
30
+ /** The default working directory of an environment: `~/capybara-device/<environmentId>`. */
31
+ export declare function defaultWorkDir(environmentId: string, home?: string): string;
32
+ export declare function writePrivate(file: string, text: string): void;
33
+ export declare function writeCredential(dir: string, cred: Credential): void;
34
+ /** The stored credential; undefined when absent. Throws on a file other users can read, or on bad content. */
35
+ export declare function readCredential(dir: string): Credential | undefined;
36
+ export declare function removeCredential(dir: string): boolean;
37
+ /** The local policy (defaults when absent). Throws, naming the file, on bad JSON or field types. */
38
+ export declare function readPolicy(dir: string): Policy;
39
+ export declare function writePolicy(dir: string, policy: Policy): void;
40
+ export {};
package/dist/state.js ADDED
@@ -0,0 +1,117 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ const DEFAULT_RECONNECT_GRACE_SECONDS = 120;
5
+ export const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;
6
+ export const DEFAULT_POLICY = {
7
+ allowedDomains: [],
8
+ allowCredentials: [],
9
+ cpu: null,
10
+ memoryMb: null,
11
+ };
12
+ /** `$XDG_CONFIG_HOME/capybara-device`, or `~/.config/capybara-device`. */
13
+ export function stateDir(env = process.env, home = homedir()) {
14
+ const xdg = env.XDG_CONFIG_HOME;
15
+ const base = xdg !== undefined && xdg !== "" ? xdg : join(home, ".config");
16
+ return join(base, "capybara-device");
17
+ }
18
+ export function credentialPath(dir) {
19
+ return join(dir, "credential.json");
20
+ }
21
+ export function policyPath(dir) {
22
+ return join(dir, "policy.json");
23
+ }
24
+ /** The default working directory of an environment: `~/capybara-device/<environmentId>`. */
25
+ export function defaultWorkDir(environmentId, home = homedir()) {
26
+ return join(home, "capybara-device", environmentId);
27
+ }
28
+ export function writePrivate(file, text) {
29
+ mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
30
+ const tmp = `${file}.${process.pid}.tmp`;
31
+ rmSync(tmp, { force: true });
32
+ try {
33
+ writeFileSync(tmp, text, { mode: 0o600, flag: "wx" });
34
+ chmodSync(tmp, 0o600);
35
+ renameSync(tmp, file);
36
+ }
37
+ finally {
38
+ rmSync(tmp, { force: true });
39
+ }
40
+ }
41
+ export function writeCredential(dir, cred) {
42
+ writePrivate(credentialPath(dir), `${JSON.stringify(cred, null, 2)}\n`);
43
+ }
44
+ /** The stored credential; undefined when absent. Throws on a file other users can read, or on bad content. */
45
+ export function readCredential(dir) {
46
+ const file = credentialPath(dir);
47
+ if (!existsSync(file))
48
+ return undefined;
49
+ if ((statSync(file).mode & 0o077) !== 0) {
50
+ throw new Error(`${file} is readable by other users; refusing to use it. Run chmod 600 ${file}, or log in again`);
51
+ }
52
+ let raw;
53
+ try {
54
+ raw = JSON.parse(readFileSync(file, "utf8"));
55
+ }
56
+ catch (e) {
57
+ throw new Error(`${file} is not valid JSON (${e.message})`);
58
+ }
59
+ for (const key of ["url", "connectUrl", "credential", "orgId", "environmentId", "dir", "mode"]) {
60
+ if (typeof raw[key] !== "string") {
61
+ throw new Error(`${file} is invalid: missing ${key}; log in again`);
62
+ }
63
+ }
64
+ const grace = raw.reconnectGraceSeconds ?? DEFAULT_RECONNECT_GRACE_SECONDS;
65
+ if (!Number.isInteger(grace) || grace <= 0) {
66
+ throw new Error(`${file} is invalid: reconnectGraceSeconds must be a positive integer`);
67
+ }
68
+ const maxFrameBytes = raw.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
69
+ if (!Number.isInteger(maxFrameBytes) || maxFrameBytes <= 0) {
70
+ throw new Error(`${file} is invalid: maxFrameBytes must be a positive integer`);
71
+ }
72
+ return { ...raw, reconnectGraceSeconds: grace, maxFrameBytes };
73
+ }
74
+ export function removeCredential(dir) {
75
+ const file = credentialPath(dir);
76
+ if (!existsSync(file))
77
+ return false;
78
+ rmSync(file);
79
+ return true;
80
+ }
81
+ const isStringList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
82
+ const isCeiling = (v) => v === null || (typeof v === "number" && Number.isFinite(v) && v > 0);
83
+ /** The local policy (defaults when absent). Throws, naming the file, on bad JSON or field types. */
84
+ export function readPolicy(dir) {
85
+ const file = policyPath(dir);
86
+ if (!existsSync(file))
87
+ return { ...DEFAULT_POLICY };
88
+ let raw;
89
+ try {
90
+ raw = JSON.parse(readFileSync(file, "utf8"));
91
+ }
92
+ catch (e) {
93
+ throw new Error(`${file} is not valid JSON (${e.message})`);
94
+ }
95
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
96
+ throw new Error(`${file} is invalid: expected a JSON object`);
97
+ }
98
+ const policy = { ...DEFAULT_POLICY, ...raw };
99
+ const bad = (key, want) => new Error(`${file} is invalid: ${key} must be ${want} (fix or delete the file)`);
100
+ if (!isStringList(policy.allowedDomains))
101
+ throw bad("allowedDomains", "a list of strings");
102
+ if (!isStringList(policy.allowCredentials))
103
+ throw bad("allowCredentials", "a list of strings");
104
+ if (!isCeiling(policy.cpu))
105
+ throw bad("cpu", "a positive number or null");
106
+ if (!isCeiling(policy.memoryMb))
107
+ throw bad("memoryMb", "a positive number or null");
108
+ return {
109
+ allowedDomains: policy.allowedDomains,
110
+ allowCredentials: policy.allowCredentials,
111
+ cpu: policy.cpu,
112
+ memoryMb: policy.memoryMb,
113
+ };
114
+ }
115
+ export function writePolicy(dir, policy) {
116
+ writePrivate(policyPath(dir), `${JSON.stringify(policy, null, 2)}\n`);
117
+ }
@@ -0,0 +1,2 @@
1
+ /** The version of this package (src/ and dist/ both sit one level below package.json). */
2
+ export declare const PROGRAM_VERSION: string;
@@ -0,0 +1,11 @@
1
+ import { readFileSync } from "node:fs";
2
+ /** The version of this package (src/ and dist/ both sit one level below package.json). */
3
+ export const PROGRAM_VERSION = (() => {
4
+ try {
5
+ const raw = readFileSync(new URL("../package.json", import.meta.url), "utf8");
6
+ return JSON.parse(raw).version;
7
+ }
8
+ catch {
9
+ return "0.0.0";
10
+ }
11
+ })();
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-rc.0",
4
+ "description": "capybara-device: connects a laptop or server to a Capybara deployment as an environment",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/capybara-hq/core.git",
9
+ "directory": "packages/device"
10
+ },
11
+ "homepage": "https://github.com/capybara-hq/core/tree/main/packages/device#readme",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=22.12"
15
+ },
16
+ "bin": {
17
+ "capybara-device": "./bin/capybara-device.mjs"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "dist",
31
+ "README.md",
32
+ "NOTICE"
33
+ ],
34
+ "dependencies": {
35
+ "@anthropic-ai/sandbox-runtime": "0.0.81",
36
+ "ws": "^8.18.0",
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.5"
38
+ },
39
+ "devDependencies": {
40
+ "@types/ws": "^8.5.13"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -b"
44
+ }
6
45
  }