@capybara-hq/device 0.1.0-rc.7 → 0.1.0-rc.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/README.md CHANGED
@@ -22,20 +22,25 @@ an existing connected one of yours) after reading what the program can do. Loggi
22
22
  another machine into the same device replaces the first machine (its credential is revoked).
23
23
  `stop` ends the running program, `drain` makes it accept no new commands and exit when the running
24
24
  ones finish (`drain --wait [--timeout <seconds>]` returns only once it has exited, at most 600 s by
25
- default). `logout` stops a running program, then forgets the credential (the machine stays
25
+ default). On macOS, when the login service is installed, launchd starts the program again after
26
+ `stop` or `drain`; run `capybara-device service uninstall` to keep it stopped. `logout` stops a
27
+ running program, then forgets the credential (the machine stays
26
28
  connected on the platform until it is revoked there). Deleting the device in the web app
27
29
  revokes the machine and stops the program; the files in the working directory stay on your machine.
28
30
 
29
31
  The deployment must route `/device/connect` on its public URL to the gateway role (see
30
32
  [Connected devices](https://github.com/capybara-hq/core/blob/main/docs/deploy/README.md#connected-devices)).
31
- While connecting keeps failing, `start` retries and prints why at most once a minute: the HTTP
32
- status (a 404 usually means that route is missing), the close reason, or the network error.
33
+ While connecting keeps failing, `start` retries with exponential backoff (capped at 60 s, with
34
+ jitter) and never gives up: a failure different from the last one is printed at once, the same one
35
+ at most once a minute. The message is the HTTP status (a 404 usually means that route is missing),
36
+ the close reason, or the network error.
33
37
 
34
38
  `start` exits 0, after printing why, when retrying cannot help: the machine was revoked or the
35
39
  device deleted, the program is too old for the deployment (426), another login replaced this
36
- connection, or the machine is not logged in. Other failures exit non-zero, so a service (below)
37
- restarts the program after those and leaves it stopped after the terminal ones; fix the cause
38
- (log in again, upgrade), then run `start` or `service install` again.
40
+ connection, or the machine is not logged in. Other failures exit non-zero. On macOS the login
41
+ service (below) restarts the program after any exit, at most every 30 s, so fix the cause (log in
42
+ again, upgrade): the running agent then reconnects by itself. `capybara-device service status`
43
+ shows whether the agent is loaded and the program running.
39
44
 
40
45
  If the working directory (or its marker `.capybara-device`, or one of `workspace/`, `skills/`,
41
46
  `tmp/`) is removed, the program never recreates it: operations answer that the files are lost and
@@ -46,7 +51,7 @@ and the platform rebuilds the device on its next use.
46
51
  Commands: `login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]`, `logout`,
47
52
  `status [--json]`, `start`, `stop`, `drain [--wait] [--timeout <seconds>]`,
48
53
  `policy [show | set <key> <value> [--yes] | add|remove <key> <value>]` and
49
- `service install|uninstall`.
54
+ `service install|uninstall|status`.
50
55
 
51
56
  State lives in `$XDG_CONFIG_HOME/capybara-device` (default `~/.config/capybara-device`):
52
57
  `credential.json` (mode 0600; the program refuses a file other users can read; it also holds the
@@ -306,9 +311,10 @@ commands to single domains.
306
311
 
307
312
  `capybara-device service install` makes the program start at login: on macOS a launchd agent
308
313
  (`~/Library/LaunchAgents/top.capybara.device.plist`, log `service.log` in the state directory), on
309
- Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). Both restart the
310
- program when it exits non-zero (systemd after 5 s) and leave it stopped after a terminal exit (code
311
- 0, see above); once the cause is fixed, `service install` again starts it. A user unit runs only
314
+ Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). The macOS agent
315
+ restarts the program after every exit, at most every 30 s (`ThrottleInterval`); systemd restarts it
316
+ when it exits non-zero, after 5 s. `capybara-device service status` reports whether the agent is
317
+ loaded and the program running. A user unit runs only
312
318
  while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
313
319
  running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
314
320
  starts. The service runs `node <bin> start` with the `PATH` of the shell that installed it (so
package/dist/args.d.ts CHANGED
@@ -33,11 +33,11 @@ export type Command = {
33
33
  yes?: true;
34
34
  } | {
35
35
  command: "service";
36
- action: "install" | "uninstall";
36
+ action: "install" | "uninstall" | "status";
37
37
  } | {
38
38
  command: "help";
39
39
  };
40
- export declare const USAGE = "Usage:\n capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]\n Connect this machine: approve the code in the browser\n capybara-device logout Forget the credential on this machine\n capybara-device status [--json] Show whether this machine is logged in\n capybara-device start Connect and serve the device\n capybara-device stop Stop the running program\n capybara-device drain [--wait] [--timeout <seconds>]\n Finish running commands, accept no new ones, then stop;\n --wait returns once it has stopped (default limit 600 s)\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n Replace one field (applies at the next command)\n capybara-device policy set tier strict|dev|open|default [--yes]\n Choose the sandbox tier (default: follow the organization)\n capybara-device policy set isolation sandbox|none [--yes]\n none: at tier open, run commands without a sandbox (OS mode)\n capybara-device policy set localhost auto|allow\n allow: reach localhost at tier dev or open despite a local proxy\n capybara-device policy set remoteGrants owner|off\n Let the device owner widen the network from the web, or not\n capybara-device policy add|remove allowedDomains <host>\n Allow or stop allowing a domain (applies at the next command)\n capybara-device service install|uninstall\n Run at login as a user service";
40
+ export declare const USAGE = "Usage:\n capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]\n Connect this machine: approve the code in the browser\n capybara-device logout Forget the credential on this machine\n capybara-device status [--json] Show whether this machine is logged in\n capybara-device start Connect and serve the device\n capybara-device stop Stop the running program\n capybara-device drain [--wait] [--timeout <seconds>]\n Finish running commands, accept no new ones, then stop;\n --wait returns once it has stopped (default limit 600 s)\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n Replace one field (applies at the next command)\n capybara-device policy set tier strict|dev|open|default [--yes]\n Choose the sandbox tier (default: follow the organization)\n capybara-device policy set isolation sandbox|none [--yes]\n none: at tier open, run commands without a sandbox (OS mode)\n capybara-device policy set localhost auto|allow\n allow: reach localhost at tier dev or open despite a local proxy\n capybara-device policy set remoteGrants owner|off\n Let the device owner widen the network from the web, or not\n capybara-device policy add|remove allowedDomains <host>\n Allow or stop allowing a domain (applies at the next command)\n capybara-device service install|uninstall\n Run at login as a user service\n capybara-device service status Report whether the login service is loaded and running";
41
41
  /** Thrown for a bad command line; the message is shown with the usage. */
42
42
  export declare class UsageError extends Error {
43
43
  }
package/dist/args.js CHANGED
@@ -23,7 +23,8 @@ export const USAGE = `Usage:
23
23
  capybara-device policy add|remove allowedDomains <host>
24
24
  Allow or stop allowing a domain (applies at the next command)
25
25
  capybara-device service install|uninstall
26
- Run at login as a user service`;
26
+ Run at login as a user service
27
+ capybara-device service status Report whether the login service is loaded and running`;
27
28
  /** Thrown for a bad command line; the message is shown with the usage. */
28
29
  export class UsageError extends Error {
29
30
  }
@@ -119,10 +120,11 @@ export function parseCommandLine(argv) {
119
120
  case "service": {
120
121
  const { positionals } = parse(rest, {});
121
122
  const [action, ...extra] = positionals;
122
- if ((action === "install" || action === "uninstall") && extra.length === 0) {
123
+ if ((action === "install" || action === "uninstall" || action === "status") &&
124
+ extra.length === 0) {
123
125
  return { command: "service", action };
124
126
  }
125
- throw new UsageError("usage: service install|uninstall");
127
+ throw new UsageError("usage: service install|uninstall|status");
126
128
  }
127
129
  default:
128
130
  throw new UsageError(`unknown command ${name}`);
package/dist/client.js CHANGED
@@ -272,12 +272,21 @@ export function connect(cred, executor, opts = {}) {
272
272
  let attempt = 0;
273
273
  /** When a failing connection was last reported; reset once a connection stays up. */
274
274
  let lastReport;
275
- /** Reports why connecting keeps failing, at most once a minute. */
275
+ /** The failure last reported: a different failure is reported at once, not after the interval. */
276
+ let lastReportText;
277
+ /**
278
+ * Reports why connecting keeps failing: a failure different from the last one is reported at
279
+ * once, the same one at most once a minute. A long outage therefore does not flood the log.
280
+ */
276
281
  const reportFailure = (why) => {
277
282
  const t = now();
278
- if (lastReport !== undefined && t - lastReport < FAILURE_REPORT_INTERVAL_MS)
283
+ if (why === lastReportText &&
284
+ lastReport !== undefined &&
285
+ t - lastReport < FAILURE_REPORT_INTERVAL_MS) {
279
286
  return;
287
+ }
280
288
  lastReport = t;
289
+ lastReportText = why;
281
290
  err(`${why} Retrying.`);
282
291
  };
283
292
  const runSession = () => new Promise((resolve) => {
@@ -304,8 +313,11 @@ export function connect(cred, executor, opts = {}) {
304
313
  opened = true;
305
314
  heard();
306
315
  stable = setTimeout(() => {
316
+ // A connection that stayed up enough is a success: the next failure starts at the
317
+ // base delay, and is reported again even if it is the same message as before.
307
318
  attempt = 0;
308
319
  lastReport = undefined;
320
+ lastReportText = undefined;
309
321
  }, stableMs);
310
322
  sock.send(JSON.stringify(hello()));
311
323
  if (opts.policy !== undefined)
@@ -1,3 +1,4 @@
1
+ export type ServiceAction = "install" | "uninstall" | "status";
1
2
  export interface ServiceDeps {
2
3
  stateDir: string;
3
4
  home: string;
@@ -25,7 +26,7 @@ export declare const SERVICE_GONE_TIMEOUT_MS = 10000;
25
26
  /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
26
27
  export declare const BOOTSTRAP_BACKOFF_MS: readonly [500, 1000, 2000];
27
28
  /**
28
- * `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd
29
- * user).
29
+ * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
30
+ * (systemd user), removes it, or reports whether it is loaded and running.
30
31
  */
31
- export declare function serviceCommand(action: "install" | "uninstall", deps: ServiceDeps): Promise<number>;
32
+ export declare function serviceCommand(action: ServiceAction, deps: ServiceDeps): Promise<number>;
@@ -2,6 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { readRunningPid } from "../pid.js";
5
6
  import { LAUNCHD_LABEL, plistContent, plistPath } from "../service/launchd.js";
6
7
  import { SYSTEMD_UNIT, unitContent, unitPath } from "../service/systemd.js";
7
8
  function defaultRun(cmd, args) {
@@ -28,8 +29,8 @@ export const SERVICE_GONE_TIMEOUT_MS = 10_000;
28
29
  /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
29
30
  export const BOOTSTRAP_BACKOFF_MS = [500, 1000, 2000];
30
31
  /**
31
- * `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd
32
- * user).
32
+ * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
33
+ * (systemd user), removes it, or reports whether it is loaded and running.
33
34
  */
34
35
  export async function serviceCommand(action, deps) {
35
36
  const run = deps.run ?? defaultRun;
@@ -65,6 +66,20 @@ function failureText(e) {
65
66
  function isBootstrapIoError(e) {
66
67
  return e.status === 5 || /Bootstrap failed: 5:/.test(failureText(e));
67
68
  }
69
+ /** One status report, once the caller knows whether launchd/systemd has the service loaded. */
70
+ function reportStatus(deps, loaded) {
71
+ if (!loaded) {
72
+ deps.out("capybara-device service is not loaded. Install it: capybara-device service install");
73
+ return 1;
74
+ }
75
+ const pid = readRunningPid(deps.stateDir);
76
+ if (pid === undefined) {
77
+ deps.out("capybara-device service is loaded, but no capybara-device process is running.");
78
+ return 1;
79
+ }
80
+ deps.out(`capybara-device service is loaded; capybara-device is running (pid ${pid}).`);
81
+ return 0;
82
+ }
68
83
  async function launchd(action, spec, deps, run) {
69
84
  const file = plistPath(deps.home);
70
85
  const domain = `gui/${deps.uid ?? process.getuid?.() ?? 501}`;
@@ -88,6 +103,8 @@ async function launchd(action, spec, deps, run) {
88
103
  return false;
89
104
  }
90
105
  };
106
+ if (action === "status")
107
+ return reportStatus(deps, loaded());
91
108
  /** Boots the service out and waits until launchd has let it go (bootout returns before that). */
92
109
  const bootout = async () => {
93
110
  tryRun(["bootout", service]);
@@ -133,6 +150,17 @@ async function launchd(action, spec, deps, run) {
133
150
  }
134
151
  function systemd(action, spec, deps, run) {
135
152
  const file = unitPath(deps.home);
153
+ if (action === "status") {
154
+ let active = false;
155
+ try {
156
+ run("systemctl", ["--user", "is-active", "--quiet", SYSTEMD_UNIT]);
157
+ active = true;
158
+ }
159
+ catch {
160
+ // Inactive or not installed.
161
+ }
162
+ return reportStatus(deps, active);
163
+ }
136
164
  if (action === "install") {
137
165
  mkdirSync(dirname(file), { recursive: true });
138
166
  writeFileSync(file, unitContent(spec));
@@ -1,4 +1,9 @@
1
1
  export declare const LAUNCHD_LABEL = "top.capybara.device";
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.
5
+ */
6
+ export declare const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
2
7
  export interface ServiceSpec {
3
8
  /** Absolute path of the node binary that runs the program. */
4
9
  nodePath: string;
@@ -10,7 +15,12 @@ export interface ServiceSpec {
10
15
  env: Record<string, string>;
11
16
  }
12
17
  export declare function plistPath(home: string): string;
13
- /** The launchd agent: `node <bin> start`, at login, restarted when it exits with a failure (a clean stop stays stopped). */
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.
23
+ */
14
24
  export declare function plistContent(spec: ServiceSpec): string;
15
25
  export declare const SERVICE_LOG_MAX_BYTES: number;
16
26
  /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
@@ -1,13 +1,23 @@
1
1
  import { copyFileSync, statSync, truncateSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  export const LAUNCHD_LABEL = "top.capybara.device";
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.
7
+ */
8
+ export const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
4
9
  export function plistPath(home) {
5
10
  return join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
6
11
  }
7
12
  function xml(s) {
8
13
  return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
9
14
  }
10
- /** The launchd agent: `node <bin> start`, at login, restarted when it exits with a failure (a clean stop stays stopped). */
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.
20
+ */
11
21
  export function plistContent(spec) {
12
22
  const env = Object.entries(spec.env)
13
23
  .map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
@@ -27,10 +37,9 @@ export function plistContent(spec) {
27
37
  <key>RunAtLoad</key>
28
38
  <true/>
29
39
  <key>KeepAlive</key>
30
- <dict>
31
- <key>SuccessfulExit</key>
32
- <false/>
33
- </dict>
40
+ <true/>
41
+ <key>ThrottleInterval</key>
42
+ <integer>${LAUNCHD_THROTTLE_INTERVAL_SECONDS}</integer>
34
43
  <key>EnvironmentVariables</key>
35
44
  <dict>
36
45
  ${env}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.1.0-rc.7",
3
+ "version": "0.1.0-rc.8",
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.20"
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.21"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/ws": "^8.5.13"