@capybara-hq/device 0.1.0-rc.6 → 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
@@ -241,7 +241,8 @@ export function connect(cred, executor, opts = {}) {
241
241
  /**
242
242
  * The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
243
243
  * mode has no per-host view); the device applies tiers (`limits.tier` / `defaultTier` /
244
- * `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen.
244
+ * `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen; then the
245
+ * outcomes of the latest policy ops by op id.
245
246
  */
246
247
  const hello = () => {
247
248
  const summary = summaryNow();
@@ -249,8 +250,9 @@ export function connect(cred, executor, opts = {}) {
249
250
  const features = [];
250
251
  if (executor.mode === "os")
251
252
  features.push("networkReport");
253
+ // the policy op, logged by its op id (policy-ops.json next to the policy)
252
254
  if (opts.policy !== undefined)
253
- features.push("policyOp");
255
+ features.push("policyOp", "policyOpId");
254
256
  features.push("tiers");
255
257
  return {
256
258
  type: "hello",
@@ -263,17 +265,28 @@ export function connect(cred, executor, opts = {}) {
263
265
  sessionIsolation: false,
264
266
  features,
265
267
  ...(summary !== undefined && { policy: summary }),
268
+ // what became of the latest policy ops, so an answer lost with a connection is not lost
269
+ ...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
266
270
  };
267
271
  };
268
272
  let attempt = 0;
269
273
  /** When a failing connection was last reported; reset once a connection stays up. */
270
274
  let lastReport;
271
- /** 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
+ */
272
281
  const reportFailure = (why) => {
273
282
  const t = now();
274
- if (lastReport !== undefined && t - lastReport < FAILURE_REPORT_INTERVAL_MS)
283
+ if (why === lastReportText &&
284
+ lastReport !== undefined &&
285
+ t - lastReport < FAILURE_REPORT_INTERVAL_MS) {
275
286
  return;
287
+ }
276
288
  lastReport = t;
289
+ lastReportText = why;
277
290
  err(`${why} Retrying.`);
278
291
  };
279
292
  const runSession = () => new Promise((resolve) => {
@@ -300,8 +313,11 @@ export function connect(cred, executor, opts = {}) {
300
313
  opened = true;
301
314
  heard();
302
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.
303
318
  attempt = 0;
304
319
  lastReport = undefined;
320
+ lastReportText = undefined;
305
321
  }, stableMs);
306
322
  sock.send(JSON.stringify(hello()));
307
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));
package/dist/exec/os.d.ts CHANGED
@@ -69,6 +69,13 @@ export declare class OsExecutor implements Executor {
69
69
  * running. The ask callback allows any public name only while one runs.
70
70
  */
71
71
  private readonly openCommands;
72
+ /**
73
+ * Background tasks launched on macOS that still run, by the command id of their launch, with
74
+ * the task's process group id (its sid). A task keeps its launch's network permissions (the
75
+ * per-command list and {@link openCommands}) until its group is gone: it uses the launch's proxy
76
+ * credentials long after the launch returned. Checked on the prune tick.
77
+ */
78
+ private readonly backgroundNet;
72
79
  constructor(opts: OsExecutorOptions);
73
80
  /**
74
81
  * The tier of work that has no limits of its own (the file helper): the device's choice cut to
@@ -131,6 +138,13 @@ export declare class OsExecutor implements Executor {
131
138
  * exported) and spawns it as the leader of a new process group.
132
139
  */
133
140
  private spawnSandboxed;
141
+ /** Drops a command's network permissions (its per-command list and any-host membership). */
142
+ private releaseNet;
143
+ /** Keeps a launched background task's network permissions while its group `sid` lives. */
144
+ private keepBackgroundNet;
145
+ /** Releases the network permissions of background tasks whose group is gone (all: `all`). */
146
+ private pruneBackgroundNet;
147
+ private startPruning;
134
148
  /** Tracks a spawned command's process group; returns the entry. */
135
149
  private track;
136
150
  /** Forgets finished groups with no members left (or whose id was taken by another process). */
@@ -155,6 +169,12 @@ export declare class OsExecutor implements Executor {
155
169
  /** Kills every running command and shuts the sandbox's proxies down. */
156
170
  dispose(): Promise<void>;
157
171
  }
172
+ /**
173
+ * The process group id a background task launch printed as its last line (the task's sid), on
174
+ * macOS only: there the sandbox shares the host's process ids, so the device can watch the group.
175
+ * Elsewhere (Linux: bwrap's own pid namespace) undefined, and the launch's permissions end with it.
176
+ */
177
+ export declare function launchedGroup(stdout: string, platform?: NodeJS.Platform): number | undefined;
158
178
  /**
159
179
  * The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
160
180
  * once for this process, and kills what a previous run of this device left running.
package/dist/exec/os.js CHANGED
@@ -99,6 +99,13 @@ export class OsExecutor {
99
99
  * running. The ask callback allows any public name only while one runs.
100
100
  */
101
101
  openCommands = new Set();
102
+ /**
103
+ * Background tasks launched on macOS that still run, by the command id of their launch, with
104
+ * the task's process group id (its sid). A task keeps its launch's network permissions (the
105
+ * per-command list and {@link openCommands}) until its group is gone: it uses the launch's proxy
106
+ * credentials long after the launch returned. Checked on the prune tick.
107
+ */
108
+ backgroundNet = new Map();
102
109
  constructor(opts) {
103
110
  this.opts = opts;
104
111
  this.reaper = new Reaper(opts.reaper);
@@ -312,16 +319,41 @@ export class OsExecutor {
312
319
  }
313
320
  return { child, commandId };
314
321
  }
322
+ /** Drops a command's network permissions (its per-command list and any-host membership). */
323
+ releaseNet(commandId) {
324
+ this.backgroundNet.delete(commandId);
325
+ this.openCommands.delete(commandId);
326
+ SandboxManager.unregisterCommandNetworkLists(commandId);
327
+ }
328
+ /** Keeps a launched background task's network permissions while its group `sid` lives. */
329
+ keepBackgroundNet(commandId, sid) {
330
+ if (!killGroupId(sid, 0)) {
331
+ this.releaseNet(commandId);
332
+ return;
333
+ }
334
+ this.backgroundNet.set(commandId, sid);
335
+ this.startPruning();
336
+ }
337
+ /** Releases the network permissions of background tasks whose group is gone (all: `all`). */
338
+ pruneBackgroundNet(all = false) {
339
+ for (const [commandId, sid] of [...this.backgroundNet]) {
340
+ if (all || !killGroupId(sid, 0))
341
+ this.releaseNet(commandId);
342
+ }
343
+ }
344
+ startPruning() {
345
+ if (this.pruneTimer === undefined) {
346
+ this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
347
+ this.pruneTimer.unref();
348
+ }
349
+ }
315
350
  /** Tracks a spawned command's process group; returns the entry. */
316
351
  track(tag, child) {
317
352
  if (child.pid === undefined)
318
353
  return undefined;
319
354
  const g = { tag, pgid: child.pid, exited: false };
320
355
  this.groups.add(g);
321
- if (this.pruneTimer === undefined) {
322
- this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
323
- this.pruneTimer.unref();
324
- }
356
+ this.startPruning();
325
357
  return g;
326
358
  }
327
359
  /** Forgets finished groups with no members left (or whose id was taken by another process). */
@@ -334,7 +366,8 @@ export class OsExecutor {
334
366
  if (pidAlive(g.pgid) || !killGroupId(g.pgid, 0))
335
367
  this.groups.delete(g);
336
368
  }
337
- if (this.groups.size === 0 && this.pruneTimer !== undefined) {
369
+ this.pruneBackgroundNet();
370
+ if (this.groups.size === 0 && this.backgroundNet.size === 0 && this.pruneTimer !== undefined) {
338
371
  clearInterval(this.pruneTimer);
339
372
  this.pruneTimer = undefined;
340
373
  }
@@ -402,7 +435,7 @@ export class OsExecutor {
402
435
  }, args.timeoutMs);
403
436
  const onAbort = () => kill();
404
437
  signal.addEventListener("abort", onAbort, { once: true });
405
- const cleanup = () => {
438
+ const cleanup = (keepFor) => {
406
439
  clearTimeout(timer);
407
440
  if (grace)
408
441
  clearTimeout(grace);
@@ -411,8 +444,10 @@ export class OsExecutor {
411
444
  group.exited = true;
412
445
  group.onKill = undefined;
413
446
  }
414
- this.openCommands.delete(commandId);
415
- SandboxManager.unregisterCommandNetworkLists(commandId);
447
+ if (keepFor !== undefined)
448
+ this.keepBackgroundNet(commandId, keepFor);
449
+ else
450
+ this.releaseNet(commandId);
416
451
  SandboxManager.cleanupAfterCommand();
417
452
  };
418
453
  const finish = () => {
@@ -428,7 +463,9 @@ export class OsExecutor {
428
463
  // The explanation is best effort: the command's result always comes back.
429
464
  }
430
465
  const trailer = networkTrailer(blocked);
431
- cleanup();
466
+ cleanup(reap || killed || timedOut || exit.code !== 0
467
+ ? undefined
468
+ : launchedGroup(cap.text("stdout")));
432
469
  child.stdout?.destroy();
433
470
  child.stderr?.destroy();
434
471
  let exitCode = exit.code;
@@ -577,6 +614,7 @@ export class OsExecutor {
577
614
  for (const g of [...this.groups])
578
615
  this.killGroup(g);
579
616
  await this.killLeftovers();
617
+ this.pruneBackgroundNet(true);
580
618
  }
581
619
  /** Kills every process carrying this device's marker (also a previous run's). */
582
620
  async killLeftovers() {
@@ -592,6 +630,17 @@ export class OsExecutor {
592
630
  await SandboxManager.reset();
593
631
  }
594
632
  }
633
+ /**
634
+ * The process group id a background task launch printed as its last line (the task's sid), on
635
+ * macOS only: there the sandbox shares the host's process ids, so the device can watch the group.
636
+ * Elsewhere (Linux: bwrap's own pid namespace) undefined, and the launch's permissions end with it.
637
+ */
638
+ export function launchedGroup(stdout, platform = process.platform) {
639
+ if (platform !== "darwin")
640
+ return undefined;
641
+ const last = stdout.trimEnd().split("\n").pop()?.trim() ?? "";
642
+ return /^[1-9][0-9]*$/.test(last) ? Number(last) : undefined;
643
+ }
595
644
  /**
596
645
  * The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
597
646
  * once for this process, and kills what a previous run of this device left running.
@@ -0,0 +1,47 @@
1
+ import { type DeviceErrorKind, type DevicePolicyOpOutcome, type DevicePolicyOpReport } from "@capybara-hq/plugin-sdk";
2
+ /** The most `policy` op outcomes the log keeps; the oldest is dropped first. */
3
+ export declare const MAX_LOGGED_POLICY_OPS = 100;
4
+ /** The longest refusal message the log keeps (characters); a longer one is cut. */
5
+ export declare const MAX_LOGGED_MESSAGE_LENGTH = 500;
6
+ /**
7
+ * One logged `policy` op: its id from the deployment, the outcome, and a refusal's message and
8
+ * error kind (a repeated op is answered with them).
9
+ */
10
+ export interface PolicyOpRecord {
11
+ opId: string;
12
+ outcome: DevicePolicyOpOutcome;
13
+ message?: string;
14
+ kind?: DeviceErrorKind;
15
+ time: string;
16
+ }
17
+ /**
18
+ * The outcomes of the latest `policy` ops, by the deployment's op id, in
19
+ * `<stateDir>/policy-ops.json` (oldest first, at most {@link MAX_LOGGED_POLICY_OPS}). An op is
20
+ * logged `started` before the policy is written, then `applied` or `refused`; one the program was
21
+ * stopped in the middle of stays `started`. The deployment reads it with `policyStatus` and in
22
+ * each hello (`recentOps`). Writes hold policy.json.lock, so they never interleave with a policy
23
+ * change.
24
+ */
25
+ export declare class PolicyOpLog {
26
+ private readonly dir;
27
+ private readonly file;
28
+ constructor(dir: string);
29
+ /** The logged ops, oldest first; a missing or unreadable file (or entry) reads as none. */
30
+ entries(): PolicyOpRecord[];
31
+ get(opId: string): PolicyOpRecord | undefined;
32
+ /** The outcomes a hello reports, oldest first. */
33
+ recent(): DevicePolicyOpReport[];
34
+ /** Logs an outcome under the policy lock. */
35
+ record(entry: Omit<PolicyOpRecord, "time">): void;
36
+ /**
37
+ * Logs an outcome; the caller holds policy.json.lock. A later outcome of the same op replaces
38
+ * its entry and moves it last.
39
+ */
40
+ recordHeld(entry: Omit<PolicyOpRecord, "time">): void;
41
+ /**
42
+ * Under the policy lock: the op's final outcome when it was applied or refused before (the
43
+ * caller answers from it), else logs it `started` and returns undefined (an op left `started`
44
+ * by an interrupted run is taken again: its content is idempotent).
45
+ */
46
+ claim(opId: string): PolicyOpRecord | undefined;
47
+ }
@@ -0,0 +1,90 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isPolicyOpId, } from "@capybara-hq/plugin-sdk";
3
+ import { policyOpsPath, withPolicyLock, writePrivate } from "./state.js";
4
+ /** The most `policy` op outcomes the log keeps; the oldest is dropped first. */
5
+ export const MAX_LOGGED_POLICY_OPS = 100;
6
+ /** The longest refusal message the log keeps (characters); a longer one is cut. */
7
+ export const MAX_LOGGED_MESSAGE_LENGTH = 500;
8
+ const KINDS = ["gone", "fs_gone", "policy", "error"];
9
+ const OUTCOMES = ["applied", "refused", "started"];
10
+ function isRecord(v) {
11
+ if (typeof v !== "object" || v === null || Array.isArray(v))
12
+ return false;
13
+ const o = v;
14
+ return (isPolicyOpId(o.opId) &&
15
+ OUTCOMES.includes(o.outcome) &&
16
+ (o.message === undefined || typeof o.message === "string") &&
17
+ (o.kind === undefined || KINDS.includes(o.kind)) &&
18
+ typeof o.time === "string");
19
+ }
20
+ /**
21
+ * The outcomes of the latest `policy` ops, by the deployment's op id, in
22
+ * `<stateDir>/policy-ops.json` (oldest first, at most {@link MAX_LOGGED_POLICY_OPS}). An op is
23
+ * logged `started` before the policy is written, then `applied` or `refused`; one the program was
24
+ * stopped in the middle of stays `started`. The deployment reads it with `policyStatus` and in
25
+ * each hello (`recentOps`). Writes hold policy.json.lock, so they never interleave with a policy
26
+ * change.
27
+ */
28
+ export class PolicyOpLog {
29
+ dir;
30
+ file;
31
+ constructor(dir) {
32
+ this.dir = dir;
33
+ this.file = policyOpsPath(dir);
34
+ }
35
+ /** The logged ops, oldest first; a missing or unreadable file (or entry) reads as none. */
36
+ entries() {
37
+ if (!existsSync(this.file))
38
+ return [];
39
+ let raw;
40
+ try {
41
+ raw = JSON.parse(readFileSync(this.file, "utf8"));
42
+ }
43
+ catch {
44
+ // a broken log is replaced at the next write: the deployment then learns less, never more
45
+ return [];
46
+ }
47
+ return Array.isArray(raw) ? raw.filter(isRecord).slice(-MAX_LOGGED_POLICY_OPS) : [];
48
+ }
49
+ get(opId) {
50
+ return this.entries().find((e) => e.opId === opId);
51
+ }
52
+ /** The outcomes a hello reports, oldest first. */
53
+ recent() {
54
+ return this.entries().map((e) => ({ opId: e.opId, outcome: e.outcome }));
55
+ }
56
+ /** Logs an outcome under the policy lock. */
57
+ record(entry) {
58
+ withPolicyLock(this.dir, () => this.recordHeld(entry));
59
+ }
60
+ /**
61
+ * Logs an outcome; the caller holds policy.json.lock. A later outcome of the same op replaces
62
+ * its entry and moves it last.
63
+ */
64
+ recordHeld(entry) {
65
+ const next = {
66
+ ...entry,
67
+ ...(entry.message !== undefined && {
68
+ message: entry.message.slice(0, MAX_LOGGED_MESSAGE_LENGTH),
69
+ }),
70
+ time: new Date().toISOString(),
71
+ };
72
+ const kept = this.entries().filter((e) => e.opId !== entry.opId);
73
+ kept.push(next);
74
+ writePrivate(this.file, `${JSON.stringify(kept.slice(-MAX_LOGGED_POLICY_OPS), null, 2)}\n`);
75
+ }
76
+ /**
77
+ * Under the policy lock: the op's final outcome when it was applied or refused before (the
78
+ * caller answers from it), else logs it `started` and returns undefined (an op left `started`
79
+ * by an interrupted run is taken again: its content is idempotent).
80
+ */
81
+ claim(opId) {
82
+ return withPolicyLock(this.dir, () => {
83
+ const known = this.get(opId);
84
+ if (known !== undefined && known.outcome !== "started")
85
+ return known;
86
+ this.recordHeld({ opId, outcome: "started" });
87
+ return undefined;
88
+ });
89
+ }
90
+ }
@@ -1,3 +1,4 @@
1
+ import { PolicyOpLog } from "./policy-ops.js";
1
2
  import { type Policy } from "./state.js";
2
3
  /**
3
4
  * The device's local policy as the running program sees it. Commands read {@link current} at
@@ -19,6 +20,8 @@ export declare class PolicyStore {
19
20
  * the key is dropped at the next write).
20
21
  */
21
22
  readonly legacyNetworkOpen: boolean;
23
+ /** The outcomes of the `policy` ops this machine served, by op id (next to policy.json). */
24
+ readonly ops: PolicyOpLog;
22
25
  constructor(dir: string, opts?: {
23
26
  err?: (line: string) => void;
24
27
  initial?: Policy;
@@ -32,7 +35,10 @@ export declare class PolicyStore {
32
35
  /**
33
36
  * Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
34
37
  * than overwrite it), writes the change atomically keeping unknown keys, and swaps the
35
- * in-memory policy. Returns the new policy.
38
+ * in-memory policy. `written` runs after that, still holding the lock (the `policy` op logs its
39
+ * outcome there, next to the change). Returns the new policy.
36
40
  */
37
- update(change: (p: Policy) => Policy): Policy;
41
+ update(change: (p: Policy) => Policy, opts?: {
42
+ written?: (p: Policy) => void;
43
+ }): Policy;
38
44
  }
@@ -1,4 +1,5 @@
1
1
  import { statSync } from "node:fs";
2
+ import { PolicyOpLog } from "./policy-ops.js";
2
3
  import { policyPath, readPolicyFile, withPolicyLock, writePolicy } from "./state.js";
3
4
  /** What identifies one version of policy.json: absent, or its inode, size and mtime. */
4
5
  function versionOf(file) {
@@ -31,10 +32,13 @@ export class PolicyStore {
31
32
  * the key is dropped at the next write).
32
33
  */
33
34
  legacyNetworkOpen;
35
+ /** The outcomes of the `policy` ops this machine served, by op id (next to policy.json). */
36
+ ops;
34
37
  constructor(dir, opts = {}) {
35
38
  this.dir = dir;
36
39
  this.file = policyPath(dir);
37
40
  this.err = opts.err ?? (() => { });
41
+ this.ops = new PolicyOpLog(dir);
38
42
  this.version = versionOf(this.file);
39
43
  // Without an initial policy, an unreadable file throws here: the program does not start.
40
44
  if (opts.initial !== undefined) {
@@ -77,15 +81,17 @@ export class PolicyStore {
77
81
  /**
78
82
  * Read-modify-write under policy.json.lock: reads the file (throws on an invalid one rather
79
83
  * than overwrite it), writes the change atomically keeping unknown keys, and swaps the
80
- * in-memory policy. Returns the new policy.
84
+ * in-memory policy. `written` runs after that, still holding the lock (the `policy` op logs its
85
+ * outcome there, next to the change). Returns the new policy.
81
86
  */
82
- update(change) {
87
+ update(change, opts = {}) {
83
88
  return withPolicyLock(this.dir, () => {
84
89
  const { policy, extra } = readPolicyFile(this.dir);
85
90
  const next = change(policy);
86
91
  writePolicy(this.dir, next, extra);
87
92
  this.policy = next;
88
93
  this.version = versionOf(this.file);
94
+ opts.written?.(next);
89
95
  return next;
90
96
  });
91
97
  }
@@ -57,7 +57,8 @@ export declare function summaryFacts(executor: Executor, ctx: OpContext): Summar
57
57
  /**
58
58
  * Runs one request and returns the answer plus its local audit line and, for an exec, its tier
59
59
  * and isolation (for the local command log). A vanished device
60
- * directory answers `fs_gone` for every operation except `stop` and `policy`. Never throws.
60
+ * directory answers `fs_gone` for every operation except `stop`, `policy` and `policyStatus`.
61
+ * Never throws.
61
62
  */
62
63
  export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
63
64
  res: DeviceRes;
@@ -1,4 +1,4 @@
1
- import { isSandboxTier, tierAtMost, validateAllowHost, } from "@capybara-hq/plugin-sdk";
1
+ import { isPolicyOpId, isSandboxTier, tierAtMost, validateAllowHost, } from "@capybara-hq/plugin-sdk";
2
2
  import { execIsolation } from "./exec/switch.js";
3
3
  import { DeviceOpError } from "./exec/types.js";
4
4
  import { grantedHosts, tierFacts } from "./policy.js";
@@ -121,7 +121,7 @@ function opHosts(list, key, fromApproval) {
121
121
  * Every host is validated; the op is idempotent. Returns the result and the local audit line; a
122
122
  * refusal carries its audit line too ({@link PolicyRefused}).
123
123
  */
124
- function applyPolicyOp(store, args, facts) {
124
+ function applyPolicyOp(store, args, facts, written) {
125
125
  const source = (args.source ?? {});
126
126
  const fromApproval = source.approvalId !== undefined;
127
127
  const add = [...new Set(opHosts(args.add, "add", fromApproval))];
@@ -173,7 +173,7 @@ function applyPolicyOp(store, args, facts) {
173
173
  return p.tier === undefined || !tierAtMost(nextTier, p.tier);
174
174
  };
175
175
  let sandboxBackOn = false;
176
- const next = store.update((p) => {
176
+ const change = (p) => {
177
177
  // Judged against the file as it is now, inside the lock: a local `remoteGrants off` wins.
178
178
  if (p.remoteGrants !== "owner") {
179
179
  if (add.length > 0)
@@ -199,13 +199,87 @@ function applyPolicyOp(store, args, facts) {
199
199
  isolation,
200
200
  allowedDomains: [...kept, ...add.filter((h) => !present.has(h))],
201
201
  };
202
- });
202
+ };
203
+ const next = store.update(change, { written });
203
204
  const also = sandboxBackOn ? "; isolation sandbox (tier changed by the deployment)" : "";
204
205
  return {
205
206
  result: { policy: policySummary(next, facts) },
206
207
  detail: `policy ${what}${also} ${by}${approval}`,
207
208
  };
208
209
  }
210
+ /** The answer to a `policy` op whose outcome is logged already: the change is not made again. */
211
+ function answerFromLog(req, known, store, facts) {
212
+ if (known.outcome === "applied") {
213
+ return {
214
+ type: "res",
215
+ id: req.id,
216
+ ok: true,
217
+ result: { policy: policySummary(store.current(), facts) },
218
+ };
219
+ }
220
+ return {
221
+ type: "res",
222
+ id: req.id,
223
+ ok: false,
224
+ error: { kind: known.kind ?? "policy", message: known.message ?? "refused" },
225
+ };
226
+ }
227
+ /**
228
+ * A `policy` op by its op id: logged `started` before anything is checked or written, then
229
+ * `applied` (inside the policy lock, right after the write) or `refused` with the message. An op
230
+ * id applied or refused before is answered from the log without applying it again. Throws like
231
+ * {@link applyPolicyOp}.
232
+ */
233
+ function servePolicyOp(req, store, facts) {
234
+ const opId = req.args.opId;
235
+ if (!isPolicyOpId(opId)) {
236
+ throw new DeviceOpError("error", 'invalid request: field "opId" must be a valid op id');
237
+ }
238
+ const known = store.ops.claim(opId);
239
+ if (known !== undefined)
240
+ return { res: answerFromLog(req, known, store, facts) };
241
+ try {
242
+ const { result, detail } = applyPolicyOp(store, req.args, facts, () => {
243
+ try {
244
+ store.ops.recordHeld({ opId, outcome: "applied" });
245
+ }
246
+ catch {
247
+ // the change stands; the log keeps `started` and the deployment learns it from the hello
248
+ }
249
+ });
250
+ return { res: { type: "res", id: req.id, ok: true, result }, detail };
251
+ }
252
+ catch (e) {
253
+ // an op the log already says was applied stays applied (the log reports what the file holds)
254
+ if (store.ops.get(opId)?.outcome !== "applied") {
255
+ try {
256
+ store.ops.record({
257
+ opId,
258
+ outcome: "refused",
259
+ message: e instanceof Error ? e.message : String(e),
260
+ kind: e instanceof DeviceOpError ? e.kind : "error",
261
+ });
262
+ }
263
+ catch {
264
+ // nothing was applied; the log keeps `started`
265
+ }
266
+ }
267
+ throw e;
268
+ }
269
+ }
270
+ /** What the log says of an op id, with the summary now. Read-only. */
271
+ function policyStatus(store, args, facts) {
272
+ const opId = args?.opId;
273
+ if (!isPolicyOpId(opId)) {
274
+ throw new DeviceOpError("error", 'invalid request: field "opId" must be a valid op id');
275
+ }
276
+ const known = store.ops.get(opId);
277
+ return {
278
+ outcome: known?.outcome ?? "unknown",
279
+ policy: policySummary(store.current(), facts),
280
+ ...(known?.outcome === "refused" && known.message !== undefined && { message: known.message }),
281
+ };
282
+ }
209
283
  /** The audit line of an exec whose grants applied (OS mode only: Docker mode ignores grants). */
210
284
  function grantsDetail(executor, args, policy) {
211
285
  if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
@@ -220,7 +294,8 @@ function grantsDetail(executor, args, policy) {
220
294
  /**
221
295
  * Runs one request and returns the answer plus its local audit line and, for an exec, its tier
222
296
  * and isolation (for the local command log). A vanished device
223
- * directory answers `fs_gone` for every operation except `stop` and `policy`. Never throws.
297
+ * directory answers `fs_gone` for every operation except `stop`, `policy` and `policyStatus`.
298
+ * Never throws.
224
299
  */
225
300
  export async function serveOp(executor, req, signal, ctx = {}) {
226
301
  const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
@@ -228,7 +303,7 @@ export async function serveOp(executor, req, signal, ctx = {}) {
228
303
  if (req.op === "stop")
229
304
  return { res: ok(null) };
230
305
  // The policy lives in the state directory, not the device directory.
231
- if (req.op === "policy") {
306
+ if (req.op === "policy" || req.op === "policyStatus") {
232
307
  if (ctx.policy === undefined) {
233
308
  return {
234
309
  res: {
@@ -239,8 +314,10 @@ export async function serveOp(executor, req, signal, ctx = {}) {
239
314
  },
240
315
  };
241
316
  }
242
- const { result, detail } = applyPolicyOp(ctx.policy, req.args, summaryFacts(executor, ctx));
243
- return { res: ok(result), detail };
317
+ const facts = summaryFacts(executor, ctx);
318
+ if (req.op === "policyStatus")
319
+ return { res: ok(policyStatus(ctx.policy, req.args, facts)) };
320
+ return servePolicyOp(req, ctx.policy, facts);
244
321
  }
245
322
  if ((await executor.ensureRoot()) === "gone") {
246
323
  return {
@@ -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/dist/state.d.ts CHANGED
@@ -43,6 +43,8 @@ type Env = Record<string, string | undefined>;
43
43
  export declare function stateDir(env?: Env, home?: string): string;
44
44
  export declare function credentialPath(dir: string): string;
45
45
  export declare function policyPath(dir: string): string;
46
+ /** The outcomes of the latest `policy` ops by op id (written under the policy lock). */
47
+ export declare function policyOpsPath(dir: string): string;
46
48
  /** The lock file that serializes read-modify-writes of policy.json across processes. */
47
49
  export declare function policyLockPath(dir: string): string;
48
50
  /** The default working directory of a device: `~/capybara-device/<deviceId>`. */
package/dist/state.js CHANGED
@@ -26,6 +26,10 @@ export function credentialPath(dir) {
26
26
  export function policyPath(dir) {
27
27
  return join(dir, "policy.json");
28
28
  }
29
+ /** The outcomes of the latest `policy` ops by op id (written under the policy lock). */
30
+ export function policyOpsPath(dir) {
31
+ return join(dir, "policy-ops.json");
32
+ }
29
33
  /** The lock file that serializes read-modify-writes of policy.json across processes. */
30
34
  export function policyLockPath(dir) {
31
35
  return join(dir, "policy.json.lock");
@@ -279,7 +283,12 @@ export function withPolicyLock(dir, fn, opts = {}) {
279
283
  catch {
280
284
  // Already gone.
281
285
  }
282
- closeSync(fd);
286
+ try {
287
+ closeSync(fd);
288
+ }
289
+ catch {
290
+ // `fn` ran (a policy write may have happened): a failed close must not turn it into an error
291
+ }
283
292
  }
284
293
  }
285
294
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.1.0-rc.6",
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.18"
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.21"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/ws": "^8.5.13"