@capybara-hq/device 0.1.0-rc.10 → 0.1.0-rc.12

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 (45) hide show
  1. package/README.md +51 -27
  2. package/dist/cli.d.ts +13 -2
  3. package/dist/cli.js +25 -4
  4. package/dist/client.d.ts +11 -3
  5. package/dist/client.js +18 -8
  6. package/dist/commands/drain.d.ts +3 -3
  7. package/dist/commands/drain.js +5 -4
  8. package/dist/commands/login.d.ts +3 -0
  9. package/dist/commands/login.js +33 -5
  10. package/dist/commands/logout.d.ts +2 -0
  11. package/dist/commands/logout.js +1 -1
  12. package/dist/commands/mode.d.ts +23 -6
  13. package/dist/commands/mode.js +24 -3
  14. package/dist/commands/service.d.ts +11 -4
  15. package/dist/commands/service.js +122 -65
  16. package/dist/commands/signal.d.ts +6 -2
  17. package/dist/commands/signal.js +7 -4
  18. package/dist/commands/start.d.ts +4 -0
  19. package/dist/commands/start.js +12 -5
  20. package/dist/commands/stop.d.ts +18 -7
  21. package/dist/commands/stop.js +20 -8
  22. package/dist/exec/docker.d.ts +24 -2
  23. package/dist/exec/docker.js +176 -2
  24. package/dist/exec/fs-helper.d.ts +7 -3
  25. package/dist/exec/fs-helper.js +70 -2
  26. package/dist/exec/host.d.ts +9 -1
  27. package/dist/exec/host.js +20 -0
  28. package/dist/exec/listing.d.ts +35 -0
  29. package/dist/exec/listing.js +157 -0
  30. package/dist/exec/os.d.ts +14 -2
  31. package/dist/exec/os.js +59 -13
  32. package/dist/exec/switch.d.ts +20 -4
  33. package/dist/exec/switch.js +39 -4
  34. package/dist/exec/types.d.ts +13 -1
  35. package/dist/pid.d.ts +33 -4
  36. package/dist/pid.js +91 -35
  37. package/dist/server-ops.d.ts +6 -4
  38. package/dist/server-ops.js +90 -17
  39. package/dist/service/launchd.d.ts +9 -6
  40. package/dist/service/launchd.js +22 -7
  41. package/dist/service/manager.d.ts +41 -0
  42. package/dist/service/manager.js +91 -0
  43. package/dist/service/systemd.d.ts +2 -0
  44. package/dist/service/systemd.js +8 -0
  45. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  export declare const LAUNCHD_LABEL = "top.capybara.device";
2
2
  /**
3
- * Minimum seconds between launchd restarts of the agent. Together with unconditional KeepAlive
4
- * this restarts the program after any exit, without spinning when it crashes during startup.
3
+ * Minimum seconds between launchd restarts of the agent: a program that keeps failing (exit code
4
+ * not 0) is started again at most this often, so a fast crash loop cannot spin.
5
5
  */
6
6
  export declare const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
7
7
  export interface ServiceSpec {
@@ -16,12 +16,15 @@ export interface ServiceSpec {
16
16
  }
17
17
  export declare function plistPath(home: string): string;
18
18
  /**
19
- * The launchd agent: `node <bin> start`, at login and after every exit. `KeepAlive` is
20
- * unconditional on purpose: the program only exits for a shutdown or a terminal condition, and a
21
- * clean exit must not leave the machine offline until someone bootstraps the agent again.
22
- * `ThrottleInterval` keeps a fast crash loop from spinning.
19
+ * The launchd agent: `node <bin> start` at login, and again after every failing exit. The program
20
+ * exits 0 only for a deliberate stop (logout, a revoked credential, `drain`, not logged in, a
21
+ * newer connection of this device), which must stay stopped; every exit it must recover from (a
22
+ * crash, a deployment that needs a newer program) is non-zero, so `KeepAlive { SuccessfulExit:
23
+ * false }` restarts exactly those. `ThrottleInterval` keeps a fast crash loop from spinning.
23
24
  */
24
25
  export declare function plistContent(spec: ServiceSpec): string;
26
+ /** The bin script a plist runs (the second `ProgramArguments` string), or undefined. */
27
+ export declare function plistBinPath(content: string): string | undefined;
25
28
  export declare const SERVICE_LOG_MAX_BYTES: number;
26
29
  /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
27
30
  export declare function rotateServiceLog(stateDir: string, maxBytes?: number): void;
@@ -2,8 +2,8 @@ import { copyFileSync, statSync, truncateSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  export const LAUNCHD_LABEL = "top.capybara.device";
4
4
  /**
5
- * Minimum seconds between launchd restarts of the agent. Together with unconditional KeepAlive
6
- * this restarts the program after any exit, without spinning when it crashes during startup.
5
+ * Minimum seconds between launchd restarts of the agent: a program that keeps failing (exit code
6
+ * not 0) is started again at most this often, so a fast crash loop cannot spin.
7
7
  */
8
8
  export const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
9
9
  export function plistPath(home) {
@@ -13,10 +13,11 @@ function xml(s) {
13
13
  return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
14
14
  }
15
15
  /**
16
- * The launchd agent: `node <bin> start`, at login and after every exit. `KeepAlive` is
17
- * unconditional on purpose: the program only exits for a shutdown or a terminal condition, and a
18
- * clean exit must not leave the machine offline until someone bootstraps the agent again.
19
- * `ThrottleInterval` keeps a fast crash loop from spinning.
16
+ * The launchd agent: `node <bin> start` at login, and again after every failing exit. The program
17
+ * exits 0 only for a deliberate stop (logout, a revoked credential, `drain`, not logged in, a
18
+ * newer connection of this device), which must stay stopped; every exit it must recover from (a
19
+ * crash, a deployment that needs a newer program) is non-zero, so `KeepAlive { SuccessfulExit:
20
+ * false }` restarts exactly those. `ThrottleInterval` keeps a fast crash loop from spinning.
20
21
  */
21
22
  export function plistContent(spec) {
22
23
  const env = Object.entries(spec.env)
@@ -37,7 +38,10 @@ export function plistContent(spec) {
37
38
  <key>RunAtLoad</key>
38
39
  <true/>
39
40
  <key>KeepAlive</key>
40
- <true/>
41
+ <dict>
42
+ <key>SuccessfulExit</key>
43
+ <false/>
44
+ </dict>
41
45
  <key>ThrottleInterval</key>
42
46
  <integer>${LAUNCHD_THROTTLE_INTERVAL_SECONDS}</integer>
43
47
  <key>EnvironmentVariables</key>
@@ -52,6 +56,17 @@ ${env}
52
56
  </plist>
53
57
  `;
54
58
  }
59
+ function unxml(s) {
60
+ return s.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
61
+ }
62
+ /** The bin script a plist runs (the second `ProgramArguments` string), or undefined. */
63
+ export function plistBinPath(content) {
64
+ const args = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(content)?.[1];
65
+ if (args === undefined)
66
+ return undefined;
67
+ const strings = [...args.matchAll(/<string>([\s\S]*?)<\/string>/g)].map((m) => unxml(m[1] ?? ""));
68
+ return strings[1];
69
+ }
55
70
  export const SERVICE_LOG_MAX_BYTES = 10 * 1024 * 1024;
56
71
  /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
57
72
  export function rotateServiceLog(stateDir, maxBytes = SERVICE_LOG_MAX_BYTES) {
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Runs a system command and returns its standard output; throws when it fails (the default,
3
+ * execFileSync, throws an error carrying the exit `status` and `stderr`).
4
+ */
5
+ export type RunSystem = (cmd: string, args: string[]) => string;
6
+ export declare function defaultRunSystem(cmd: string, args: string[]): string;
7
+ /** Where the login service lives: the user's home, the platform, and (macOS) the GUI domain's uid. */
8
+ export interface ServiceWhere {
9
+ home: string;
10
+ platform: NodeJS.Platform;
11
+ uid?: number;
12
+ }
13
+ /** The launchd domain and service target of the agent. */
14
+ export declare function launchdTarget(uid: number | undefined): {
15
+ domain: string;
16
+ service: string;
17
+ };
18
+ /**
19
+ * What the service manager says of the login service: whether launchd has it loaded (systemd:
20
+ * whether the unit is active), and the pid of the program it runs now, if any.
21
+ */
22
+ export interface ManagerState {
23
+ loaded: boolean;
24
+ pid?: number;
25
+ }
26
+ /** Asks launchd or systemd about the login service; a manager that cannot be asked says "not loaded". */
27
+ export declare function managerState(where: ServiceWhere, run: RunSystem): ManagerState;
28
+ /** The bin script the installed service file runs, or undefined (no file, or unreadable). */
29
+ export declare function serviceBinPath(where: ServiceWhere): string | undefined;
30
+ /**
31
+ * The version of the package at `binPath` (`<package>/bin/capybara-device.mjs`), read from its
32
+ * `package.json`: what a restart of the service would run. Undefined when it cannot be read.
33
+ */
34
+ export declare function packageVersionAt(binPath: string): string | undefined;
35
+ /**
36
+ * Whether this process was started by the service manager: launchd sets `XPC_SERVICE_NAME` to the
37
+ * agent's label (a terminal on macOS sets it to `0` or the terminal app's), systemd sets
38
+ * `INVOCATION_ID`. A shell inside a systemd-run terminal inherits `INVOCATION_ID` too; systemd 248+
39
+ * also sets `SYSTEMD_EXEC_PID`, which names this process only when systemd started it.
40
+ */
41
+ export declare function startedByServiceManager(env: Record<string, string | undefined>, pid?: number): boolean;
@@ -0,0 +1,91 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { hasLoginService } from "./installed.js";
5
+ import { LAUNCHD_LABEL, plistBinPath, plistPath } from "./launchd.js";
6
+ import { SYSTEMD_UNIT, unitBinPath, unitPath } from "./systemd.js";
7
+ export function defaultRunSystem(cmd, args) {
8
+ return execFileSync(cmd, args, { stdio: "pipe", encoding: "utf8" });
9
+ }
10
+ /** The launchd domain and service target of the agent. */
11
+ export function launchdTarget(uid) {
12
+ const domain = `gui/${uid ?? process.getuid?.() ?? 501}`;
13
+ return { domain, service: `${domain}/${LAUNCHD_LABEL}` };
14
+ }
15
+ /** The job's own `pid = N` line in `launchctl print` output (absent while it is not running). */
16
+ function launchdPid(printed) {
17
+ const m = /^\s*pid = (\d+)\s*$/m.exec(printed);
18
+ const pid = m === null ? Number.NaN : Number(m[1]);
19
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined;
20
+ }
21
+ /** Asks launchd or systemd about the login service; a manager that cannot be asked says "not loaded". */
22
+ export function managerState(where, run) {
23
+ if (where.platform === "darwin") {
24
+ try {
25
+ const printed = run("launchctl", ["print", launchdTarget(where.uid).service]);
26
+ const pid = launchdPid(String(printed ?? ""));
27
+ return { loaded: true, ...(pid !== undefined && { pid }) };
28
+ }
29
+ catch {
30
+ return { loaded: false };
31
+ }
32
+ }
33
+ if (where.platform === "linux") {
34
+ try {
35
+ run("systemctl", ["--user", "is-active", "--quiet", SYSTEMD_UNIT]);
36
+ }
37
+ catch {
38
+ return { loaded: false };
39
+ }
40
+ try {
41
+ const out = run("systemctl", ["--user", "show", "-p", "MainPID", "--value", SYSTEMD_UNIT]);
42
+ const pid = Number(String(out ?? "").trim());
43
+ return { loaded: true, ...(Number.isInteger(pid) && pid > 0 && { pid }) };
44
+ }
45
+ catch {
46
+ return { loaded: true };
47
+ }
48
+ }
49
+ return { loaded: false };
50
+ }
51
+ /** The bin script the installed service file runs, or undefined (no file, or unreadable). */
52
+ export function serviceBinPath(where) {
53
+ if (!hasLoginService(where.home, where.platform))
54
+ return undefined;
55
+ try {
56
+ if (where.platform === "darwin") {
57
+ return plistBinPath(readFileSync(plistPath(where.home), "utf8"));
58
+ }
59
+ return unitBinPath(readFileSync(unitPath(where.home), "utf8"));
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
65
+ /**
66
+ * The version of the package at `binPath` (`<package>/bin/capybara-device.mjs`), read from its
67
+ * `package.json`: what a restart of the service would run. Undefined when it cannot be read.
68
+ */
69
+ export function packageVersionAt(binPath) {
70
+ try {
71
+ const raw = readFileSync(join(dirname(dirname(binPath)), "package.json"), "utf8");
72
+ const version = JSON.parse(raw).version;
73
+ return typeof version === "string" ? version : undefined;
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /**
80
+ * Whether this process was started by the service manager: launchd sets `XPC_SERVICE_NAME` to the
81
+ * agent's label (a terminal on macOS sets it to `0` or the terminal app's), systemd sets
82
+ * `INVOCATION_ID`. A shell inside a systemd-run terminal inherits `INVOCATION_ID` too; systemd 248+
83
+ * also sets `SYSTEMD_EXEC_PID`, which names this process only when systemd started it.
84
+ */
85
+ export function startedByServiceManager(env, pid = process.pid) {
86
+ if (env.XPC_SERVICE_NAME === LAUNCHD_LABEL)
87
+ return true;
88
+ if ((env.INVOCATION_ID ?? "") === "")
89
+ return false;
90
+ return env.SYSTEMD_EXEC_PID === undefined || env.SYSTEMD_EXEC_PID === String(pid);
91
+ }
@@ -3,3 +3,5 @@ export declare const SYSTEMD_UNIT = "capybara-device.service";
3
3
  export declare function unitPath(home: string): string;
4
4
  /** The systemd user unit: `node <bin> start`, restarted on failure, wanted by the default target. */
5
5
  export declare function unitContent(spec: ServiceSpec): string;
6
+ /** The bin script a unit runs (the second word of `ExecStart`), or undefined. */
7
+ export declare function unitBinPath(content: string): string | undefined;
@@ -26,3 +26,11 @@ ${env}
26
26
  WantedBy=default.target
27
27
  `;
28
28
  }
29
+ /** The bin script a unit runs (the second word of `ExecStart`), or undefined. */
30
+ export function unitBinPath(content) {
31
+ const line = /^ExecStart=(.*)$/m.exec(content)?.[1];
32
+ if (line === undefined)
33
+ return undefined;
34
+ const words = [...line.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => (m[1] ?? "").replace(/\\(.)/g, "$1").replaceAll("%%", "%"));
35
+ return words[1];
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.1.0-rc.10",
3
+ "version": "0.1.0-rc.12",
4
4
  "description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@anthropic-ai/sandbox-runtime": "0.0.81",
36
36
  "ws": "^8.18.0",
37
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.22"
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.24"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/ws": "^8.5.13"