@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
package/README.md CHANGED
@@ -23,8 +23,10 @@ an existing connected one of yours) after reading what the program can do. Loggi
23
23
  another machine into the same device replaces the first machine (its credential is revoked).
24
24
  `stop` ends the running program, `drain` makes it accept no new commands and exit when the running
25
25
  ones finish (`drain --wait [--timeout <seconds>]` returns only once it has exited, at most 600 s by
26
- default). On macOS, when the login service is installed, launchd starts the program again after
27
- `stop` or `drain`; run `capybara-device service uninstall` to keep it stopped. `logout` stops a
26
+ default). Both signal only a pid the pid file names **and** `ps` shows to be `capybara-device`,
27
+ started before the file was written; a stale file (a reused pid) is never signalled. When the login
28
+ service runs the program, `stop` refuses and points at `service stop`; `drain` exits 0, which the
29
+ service leaves stopped until `service start`. `logout` stops a
28
30
  running program, then forgets the credential (the machine stays
29
31
  connected on the platform until it is revoked there). Deleting the device in the web app
30
32
  revokes the machine and stops the program; the files in the working directory stay on your machine.
@@ -36,12 +38,14 @@ jitter) and never gives up: a failure different from the last one is printed at
36
38
  at most once a minute. The message is the HTTP status (a 404 usually means that route is missing),
37
39
  the close reason, or the network error.
38
40
 
39
- `start` exits 0, after printing why, when retrying cannot help: the machine was revoked or the
40
- device deleted, the program is too old for the deployment (426), another login replaced this
41
- connection, or the machine is not logged in. Other failures exit non-zero. On macOS the login
42
- service (below) restarts the program after any exit, at most every 30 s, so fix the cause (log in
43
- again, upgrade): the running agent then reconnects by itself. `capybara-device service status`
44
- shows whether the agent is loaded and the program running.
41
+ `start` exits 0 only for a deliberate stop: the machine was revoked or the device deleted, another
42
+ connection of this device replaced this one, `stop` / `drain` / `logout`, or the machine is not
43
+ logged in. The login service (below) leaves such an exit stopped. Every exit it must recover from is
44
+ non-zero, and the service restarts it: a crash, an invalid start (`Cannot start: …`), or a
45
+ deployment that needs a newer program (426: upgrade the package in place and the next restart runs
46
+ the new one). A failing connection never ends the program: it reconnects with backoff, so a kernel
47
+ restart needs no service restart. After logging in again, start the installed service with
48
+ `capybara-device service restart`; `capybara-device service status` shows what is true now.
45
49
 
46
50
  If the working directory (or its marker `.capybara-device`, or one of `workspace/`, `skills/`,
47
51
  `tmp/`) is removed, the program never recreates it: operations answer that the files are lost and
@@ -75,20 +79,27 @@ with `capybara-device mode`):
75
79
  network. It is what a coding agent without an OS sandbox has, and what Claude Code calls auto
76
80
  mode. The deployment reviews every command before it runs and blocks, or asks about, the
77
81
  dangerous ones (deleting outside the workspace, sending a secret away, force-pushing a protected
78
- branch). The platform's file tools reach any absolute path on the machine.
82
+ branch). The platform's file tools reach any absolute path on the machine. The hello reports
83
+ your home directory, and the deployment can list any directory you can read and scan your home
84
+ for projects (directory entries only, never file contents).
79
85
  - **sandbox**: today's strict `@anthropic-ai/sandbox-runtime` profile (macOS Seatbelt, Linux
80
86
  bubblewrap; Linux needs `bwrap` and `socat`). Writes only under `workspace/` and `tmp/`,
81
87
  `skills/` read only, `HOME` = the workspace, `~/.ssh`, cloud CLI credentials, `~/.netrc`,
82
88
  `~/.gnupg`, browser profiles and this program's state directory unreadable, no local binding or
83
89
  unix sockets, and network only to the domains of the local policy that the organization's
84
90
  allowlist also admits (with an empty list, no network at all). Commands keep their package
85
- caches in the workspace like any other file.
91
+ caches in the workspace like any other file. The hello still reports your home directory, but
92
+ the deployment's directory listing and project scan cover the workspace only.
86
93
 
87
94
  If the OS sandbox is unavailable on the machine (an unsupported platform or missing dependencies,
88
95
  such as `bwrap` / `socat` on Linux), the device still starts and serves: auto mode works, and every
89
96
  sandbox-mode command is refused with the reason and how to fix it (`capybara-device mode auto`, or
90
97
  install the dependencies and restart). `capybara-device mode sandbox` is refused on such a machine
91
- and the policy stays in auto; nothing ever runs unsandboxed by falling back.
98
+ and the policy stays in auto; nothing ever runs unsandboxed by falling back. File operations
99
+ (read, write, stat) there follow only a fresh command decision (the latest command, within a
100
+ minute): without one they are refused, never served on the host. `login` into an organization that
101
+ forbids auto mode checks the OS sandbox first: when it is unavailable, no sandbox policy is written
102
+ and the login line says what to install (or to log in with `--mode docker`).
92
103
 
93
104
  ```bash
94
105
  capybara-device mode # print the current mode
@@ -135,8 +146,8 @@ lines (at most 21).
135
146
 
136
147
  In OS mode each command's result also carries the refused hosts and their layers, so the
137
148
  deployment can ask the device owner on the spot (the device announces this in its hello, together
138
- with a summary of its local policy: the effective `mode` and the sandbox-mode
139
- `allowedDomains`).
149
+ with a summary of its local policy: the owner's `mode`, never cut by an exec's ceiling (the
150
+ deployment applies its own), and the sandbox-mode `allowedDomains`).
140
151
 
141
152
  ### Sandbox mode details
142
153
 
@@ -214,6 +225,9 @@ Docker mode has no per-domain network filter, so the mode alone decides:
214
225
  network), and the platform's file tools reach any absolute path in the container.
215
226
  - **sandbox**: the container has no network at all, and file operations stay in the mounted roots.
216
227
 
228
+ In both, the hello reports your home directory, while the deployment's directory listing and
229
+ project scan cover the container's `/workspace` only (directory entries, never file contents).
230
+
217
231
  The network is switched between the two without recreating the container (a container disconnected
218
232
  from every network has no network, the same as `--network none`). Use OS mode's sandbox when you
219
233
  need to allow single domains.
@@ -222,22 +236,32 @@ need to allow single domains.
222
236
 
223
237
  `capybara-device service install` makes the program start at login: on macOS a launchd agent
224
238
  (`~/Library/LaunchAgents/top.capybara.device.plist`, log `service.log` in the state directory), on
225
- Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). The macOS agent
226
- restarts the program after every exit, at most every 30 s (`ThrottleInterval`); systemd restarts it
227
- when it exits non-zero, after 5 s.
239
+ Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). Both restart the
240
+ program only when it exits non-zero: the macOS agent uses `KeepAlive { SuccessfulExit: false }`, at
241
+ most every 30 s (`ThrottleInterval`); systemd `Restart=on-failure`, after 5 s. Exit 0 is a deliberate
242
+ stop and stays stopped.
228
243
 
229
244
  `service start|stop|restart` control it without knowing launchctl or systemctl. `stop` unloads the
230
- service (the plist or unit stays) rather than signalling the program, which the service manager
231
- would start straight back up; running commands end with it. `restart` reloads the program from the
232
- installed `bin`, so it is **the way to apply a package upgrade**: `npm i -g
233
- @capybara-hq/device@latest && capybara-device service restart`. While a service is installed, the
234
- top-level `stop` refuses and points at `service stop` (a signal would be undone by the restart
235
- policy); `start` still runs, for a stopped service, and says how to restart the installed one.
236
-
237
- `capybara-device service status` reports whether the service is installed, whether the program is
238
- running and **at which version**, and when the running program is older than the installed package
239
- it says so with the restart command. The pid file records the version (`{pid, version, startedAt}`);
240
- one written by an older program reads as "version unknown". A user unit runs only
245
+ service (the plist or unit stays) rather than signalling the program; running commands end with
246
+ it, and it reports a failure when the service is still loaded afterwards. `start` and `restart`
247
+ wait (up to 10 s) until the service manager runs the program and report a failure, pointing at
248
+ `service.log`, when it does not come back; `service start` refuses while a program started in a
249
+ terminal runs ("stop it first"). On macOS a loaded agent whose program exited is started again with
250
+ `launchctl kickstart`. `restart` reloads the program from the installed `bin`, so it is **the way to
251
+ apply a package upgrade**: `npm i -g @capybara-hq/device@latest && capybara-device service restart`.
252
+ The top-level `stop` refuses only when the service manager runs the program it would signal (launchd
253
+ has the agent loaded, or systemd the unit active, and its pid is the pid file's) and points at
254
+ `service stop`; a program started in a terminal is signalled as before. `start` in a terminal says
255
+ how to restart the installed service; started by the service manager (launchd sets
256
+ `XPC_SERVICE_NAME`, systemd `INVOCATION_ID`) it prints no such hint.
257
+
258
+ `capybara-device service status` says one of four things: not installed; installed but not loaded
259
+ (`service start`); loaded but the program is not running, i.e. it exited (the reason is at the end of
260
+ `service.log`; fix it, then `service restart`); or running, with the service manager's pid and the
261
+ program's **version**. When the package at the service file's `bin` path (its `package.json`) is a
262
+ different version from the running program, it adds the restart command: an upgrade the service has
263
+ not picked up yet. The pid file records the version (`{pid, version, startedAt}`); one written by an
264
+ older program reads as "version unknown". A user unit runs only
241
265
  while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
242
266
  running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
243
267
  starts. The service runs `node <bin> start` with the `PATH` of the shell that installed it (so
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { Executor } from "./exec/types.js";
2
+ import type { ProcessLookup } from "./pid.js";
2
3
  import type { PolicyStore } from "./policy-store.js";
4
+ import type { RunSystem } from "./service/manager.js";
3
5
  import { type Credential } from "./state.js";
4
6
  export interface CliEnv {
5
7
  env?: Record<string, string | undefined>;
@@ -12,10 +14,19 @@ export interface CliEnv {
12
14
  err?: (line: string) => void;
13
15
  createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
14
16
  kill?: typeof process.kill;
15
- /** Runs a system command for `service` (default: execFileSync). */
16
- runSystem?: (cmd: string, args: string[]) => void;
17
+ /** Runs a system command for `service` and `stop` and returns its output (default: execFileSync). */
18
+ runSystem?: RunSystem;
19
+ /** Looks a process up by pid, to check a pid file names this program (default: `ps`). */
20
+ ps?: ProcessLookup;
17
21
  /** Standard input is a terminal (default: `process.stdin.isTTY`): a confirmation may be asked. */
18
22
  stdinIsTTY?: boolean;
23
+ /** Whether the OS sandbox can run here, for `login` and `mode` (default: the runtime's check). */
24
+ sandboxAvailable?: () => {
25
+ ok: true;
26
+ } | {
27
+ ok: false;
28
+ reason: string;
29
+ };
19
30
  /** Asks one question on the terminal and resolves the answer (default: node:readline). */
20
31
  ask?: (question: string) => Promise<string>;
21
32
  }
package/dist/cli.js CHANGED
@@ -94,9 +94,15 @@ export async function runCli(argv, io = {}) {
94
94
  ...(io.fetch && { fetch: io.fetch }),
95
95
  ...(io.sleep && { sleep: io.sleep }),
96
96
  ...(io.openBrowser && { openBrowser: io.openBrowser }),
97
+ ...(io.sandboxAvailable && { sandboxAvailable: io.sandboxAvailable }),
97
98
  });
98
99
  case "logout":
99
- return logout(dir, { out, err, ...(io.kill && { kill: io.kill }) });
100
+ return logout(dir, {
101
+ out,
102
+ err,
103
+ ...(io.kill && { kill: io.kill }),
104
+ ...(io.ps && { ps: io.ps }),
105
+ });
100
106
  case "status":
101
107
  return status(dir, cmd.json, out, err);
102
108
  case "start":
@@ -106,15 +112,27 @@ export async function runCli(argv, io = {}) {
106
112
  out,
107
113
  err,
108
114
  createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home, err),
115
+ ...(io.env && { env: io.env }),
109
116
  ...(io.kill && { kill: io.kill }),
117
+ ...(io.ps && { ps: io.ps }),
110
118
  });
111
119
  case "stop":
112
- return stop(dir, out, err, io.kill, { home, platform });
120
+ return stop(dir, out, err, {
121
+ service: { home, platform },
122
+ ...(io.kill && { kill: io.kill }),
123
+ ...(io.ps && { ps: io.ps }),
124
+ ...(io.runSystem && { run: io.runSystem }),
125
+ });
113
126
  case "drain":
114
- if (cmd.wait !== true)
115
- return drain(dir, out, err, io.kill);
127
+ if (cmd.wait !== true) {
128
+ return drain(dir, out, err, {
129
+ ...(io.kill && { kill: io.kill }),
130
+ ...(io.ps && { ps: io.ps }),
131
+ });
132
+ }
116
133
  return drainAndWait(dir, out, err, {
117
134
  ...(io.kill && { kill: io.kill }),
135
+ ...(io.ps && { ps: io.ps }),
118
136
  ...(io.sleep && { sleep: io.sleep }),
119
137
  ...(cmd.timeoutSeconds !== undefined && { timeoutMs: cmd.timeoutSeconds * 1000 }),
120
138
  });
@@ -125,6 +143,7 @@ export async function runCli(argv, io = {}) {
125
143
  stateDir: dir,
126
144
  out,
127
145
  err,
146
+ ...(io.sandboxAvailable && { sandboxAvailable: io.sandboxAvailable }),
128
147
  ...((io.stdinIsTTY ?? process.stdin.isTTY === true) && { ask: io.ask ?? askOnTerminal }),
129
148
  });
130
149
  case "service":
@@ -137,6 +156,8 @@ export async function runCli(argv, io = {}) {
137
156
  err,
138
157
  ...(io.runSystem && { run: io.runSystem }),
139
158
  ...(io.sleep && { sleep: io.sleep }),
159
+ ...(io.kill && { kill: io.kill }),
160
+ ...(io.ps && { ps: io.ps }),
140
161
  });
141
162
  }
142
163
  }
package/dist/client.d.ts CHANGED
@@ -20,6 +20,12 @@ export interface ConnectOptions {
20
20
  random?: () => number;
21
21
  now?: () => number;
22
22
  programVersion?: string;
23
+ /**
24
+ * The owner's home directory, reported in the hello (the base of an auto-mode project path).
25
+ * Defaults to the user's home; left out of the hello when it is not a clean absolute path, and
26
+ * by a docker-mode device (it offers its container's workspace only).
27
+ */
28
+ home?: string;
23
29
  /** A connection must stay up this long before the backoff resets (default 10 s). */
24
30
  stableMs?: number;
25
31
  /** Terminate a socket that heard nothing from the server for this long (default 60 s). */
@@ -33,9 +39,11 @@ export interface ConnectOptions {
33
39
  policyCheckMs?: number;
34
40
  }
35
41
  /**
36
- * A running connection. `done` resolves with the exit code once the program should end: 0 for the
37
- * terminal conditions (revoked, outdated, replaced, deleted, stopped, drained), so a service
38
- * manager that restarts on failure leaves it stopped.
42
+ * A running connection. `done` resolves with the exit code once the program should end: 0 for a
43
+ * deliberate stop (revoked, replaced by a newer connection of this device, deleted, stopped,
44
+ * drained), which a service manager that restarts on failure leaves stopped; 1 when the deployment
45
+ * needs a newer program (426), which an upgrade in place recovers once the service starts it again.
46
+ * Connection failures never end it: they reconnect with backoff.
39
47
  */
40
48
  export interface Connection {
41
49
  readonly done: Promise<number>;
package/dist/client.js CHANGED
@@ -1,4 +1,5 @@
1
- import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
1
+ import { homedir } from "node:os";
2
+ import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
3
  import WebSocket from "ws";
3
4
  import { logEntryFor, policySummary, serveOp, summaryFacts, } from "./server-ops.js";
4
5
  import { PROGRAM_VERSION } from "./version.js";
@@ -78,9 +79,9 @@ export function connect(cred, executor, opts = {}) {
78
79
  let sentPolicy;
79
80
  /**
80
81
  * Pushes the policy summary when it differs from the one the deployment last got: the owner
81
- * changed the mode or the policy on the machine (`capybara-device mode` / `policy ...`), or an
82
- * exec brought a new mode ceiling. Without it the deployment would learn the change only at the
83
- * next connect.
82
+ * changed the mode or the policy on the machine (`capybara-device mode` / `policy ...`). Without
83
+ * it the deployment would learn the change only at the next connect. An exec's ceiling changes
84
+ * nothing here: the summary reports the owner's mode, which the kernel cuts itself.
84
85
  */
85
86
  const pushPolicy = () => {
86
87
  if (!isOpen())
@@ -197,8 +198,6 @@ export function connect(cred, executor, opts = {}) {
197
198
  sentPolicy = JSON.stringify(res.result.policy);
198
199
  }
199
200
  deliver(res);
200
- // an exec may have changed the ceiling (the effective mode)
201
- pushPolicy();
202
201
  }
203
202
  maybeFinishDrain();
204
203
  });
@@ -240,9 +239,14 @@ export function connect(cred, executor, opts = {}) {
240
239
  /**
241
240
  * The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
242
241
  * mode has no per-host view); the device applies `limits.mode` / `limits.network` (`mode`); the
243
- * policy summary is the store's policy now, with the effective mode and the latest ceiling seen;
242
+ * policy summary is the store's policy now (the owner's mode, not cut by any ceiling);
244
243
  * then the outcomes of the latest policy ops by op id.
245
244
  */
245
+ // A container device offers only its container's workspace: the host's home is not its base.
246
+ const ownerHome = opts.home ?? homedir();
247
+ const home = executor.mode === "os" && validateSandboxPathShape(ownerHome).length === 0
248
+ ? ownerHome
249
+ : undefined;
246
250
  const hello = () => {
247
251
  const summary = summaryNow();
248
252
  sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
@@ -253,6 +257,9 @@ export function connect(cred, executor, opts = {}) {
253
257
  if (opts.policy !== undefined)
254
258
  features.push("policyOp", "policyOpId");
255
259
  features.push("mode");
260
+ // `list` and `scan`, read in each request's own mode (they need the owner's policy)
261
+ if (opts.policy !== undefined)
262
+ features.push("projects");
256
263
  return {
257
264
  type: "hello",
258
265
  protocol: DEVICE_PROTOCOL_VERSION,
@@ -263,6 +270,7 @@ export function connect(cred, executor, opts = {}) {
263
270
  roots: executor.roots,
264
271
  sessionIsolation: false,
265
272
  features,
273
+ ...(home !== undefined && { home }),
266
274
  ...(summary !== undefined && { policy: summary }),
267
275
  // what became of the latest policy ops, so an answer lost with a connection is not lost
268
276
  ...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
@@ -341,8 +349,10 @@ export function connect(cred, executor, opts = {}) {
341
349
  sock.terminate();
342
350
  if (status === 401)
343
351
  return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
352
+ // Not a deliberate stop: upgrading the package in place recovers it, so the exit is
353
+ // non-zero and the service manager starts the (new) program again.
344
354
  if (status === 426)
345
- return endSession({ exit: 0, message: OUTDATED_MESSAGE });
355
+ return endSession({ exit: 1, message: OUTDATED_MESSAGE });
346
356
  reportFailure(status === 404
347
357
  ? `Connecting to ${cred.connectUrl} failed: HTTP 404. The deployment must route ` +
348
358
  "/device/connect to its gateway (see the deployment docs)."
@@ -1,15 +1,15 @@
1
+ import { type ProcessChecks } from "../pid.js";
1
2
  /** How often `drain --wait` checks whether the program has exited. */
2
3
  export declare const DRAIN_POLL_MS = 500;
3
4
  /** How long `drain --wait` waits by default (commands may run long). */
4
5
  export declare const DRAIN_WAIT_DEFAULT_SECONDS = 600;
5
6
  /** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
6
- export declare function drain(stateDir: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill): number;
7
+ export declare function drain(stateDir: string, out: (line: string) => void, err: (line: string) => void, checks?: ProcessChecks): number;
7
8
  /**
8
9
  * `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
9
10
  * finished), at most `timeoutMs`. Exit code 1 when it still runs then.
10
11
  */
11
- export declare function drainAndWait(stateDir: string, out: (line: string) => void, err: (line: string) => void, o?: {
12
- kill?: typeof process.kill;
12
+ export declare function drainAndWait(stateDir: string, out: (line: string) => void, err: (line: string) => void, o?: ProcessChecks & {
13
13
  sleep?: (ms: number) => Promise<void>;
14
14
  timeoutMs?: number;
15
15
  }): Promise<number>;
@@ -5,8 +5,8 @@ export const DRAIN_POLL_MS = 500;
5
5
  /** How long `drain --wait` waits by default (commands may run long). */
6
6
  export const DRAIN_WAIT_DEFAULT_SECONDS = 600;
7
7
  /** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
8
- export function drain(stateDir, out, err, kill) {
9
- return signalRunning(stateDir, "SIGUSR2", "Draining capybara-device.", out, err, kill);
8
+ export function drain(stateDir, out, err, checks = {}) {
9
+ return signalRunning(stateDir, "SIGUSR2", "Draining capybara-device.", out, err, checks);
10
10
  }
11
11
  /**
12
12
  * `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
@@ -16,8 +16,9 @@ export async function drainAndWait(stateDir, out, err, o = {}) {
16
16
  const kill = o.kill ?? process.kill;
17
17
  const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
18
18
  const timeoutMs = o.timeoutMs ?? DRAIN_WAIT_DEFAULT_SECONDS * 1000;
19
- const pid = readRunningPid(stateDir, kill);
20
- const code = drain(stateDir, out, err, kill);
19
+ const checks = { kill, ...(o.ps && { ps: o.ps }) };
20
+ const pid = readRunningPid(stateDir, checks);
21
+ const code = drain(stateDir, out, err, checks);
21
22
  if (code !== 0 || pid === undefined)
22
23
  return code;
23
24
  for (let waited = 0; isAlive(pid, kill); waited += DRAIN_POLL_MS) {
@@ -1,5 +1,6 @@
1
1
  import { type FetchFn } from "../api.js";
2
2
  import type { Command } from "../args.js";
3
+ import { type SandboxCheck } from "./mode.js";
3
4
  export interface LoginDeps {
4
5
  stateDir: string;
5
6
  home: string;
@@ -11,6 +12,8 @@ export interface LoginDeps {
11
12
  platform?: NodeJS.Platform;
12
13
  arch?: string;
13
14
  hostname?: string;
15
+ /** Whether the OS sandbox can run here (default: the runtime's check); injectable for tests. */
16
+ sandboxAvailable?: SandboxCheck;
14
17
  }
15
18
  /** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
16
19
  export declare function normalizeUrl(raw: string): string;
@@ -4,8 +4,9 @@ import { hostname } from "node:os";
4
4
  import { isAbsolute, resolve } from "node:path";
5
5
  import { ApiError, authorize, programVersion, token } from "../api.js";
6
6
  import { prepareDeviceDir } from "../exec/shared.js";
7
+ import { hasLoginService } from "../service/installed.js";
7
8
  import { DEFAULT_MAX_FRAME_BYTES, DEFAULT_POLICY, defaultWorkDir, policyPath, readCredential, readPolicy, withPolicyLock, writeCredential, writePolicy, } from "../state.js";
8
- import { AUTO_MODE_LOGIN_LINE, AUTO_MODE_RISK_TEXT, AUTO_POLICY_REFUSED_LOGIN_LINE, SANDBOX_MODE_LOGIN_LINE, SANDBOX_POLICY_LOGIN_LINE, } from "./mode.js";
9
+ import { AUTO_MODE_LOGIN_LINE, AUTO_MODE_RISK_TEXT, AUTO_POLICY_REFUSED_LOGIN_LINE, checkSandbox, DOCKER_AUTO_MODE_LOGIN_LINE, DOCKER_SANDBOX_MODE_LOGIN_LINE, SANDBOX_MODE_LOGIN_LINE, SANDBOX_POLICY_LOGIN_LINE, sandboxUnavailableLoginLine, } from "./mode.js";
9
10
  const SLOW_DOWN_STEP_SECONDS = 5;
10
11
  function defaultOpen(platform) {
11
12
  return (url) => {
@@ -113,9 +114,22 @@ export async function login(cmd, deps) {
113
114
  // the login final. An existing policy is the owner's choice: the kernel refuses auto mode
114
115
  // at every command if the organization forbids it and the owner keeps auto.
115
116
  let mode = "auto";
117
+ /** Why no sandbox policy was written: the OS sandbox cannot run here (OS mode only). */
118
+ let noSandbox;
116
119
  if (granted.autoMode === "off") {
117
120
  try {
118
- mode = persistSandboxPolicy(deps.stateDir) ? "sandbox" : readPolicy(deps.stateDir).mode;
121
+ // A sandbox policy on a machine without the OS sandbox could not run a command either:
122
+ // it is not written, and the line says what to install (Docker needs no OS sandbox).
123
+ if (cmd.mode !== "docker" && !existsSync(policyPath(deps.stateDir))) {
124
+ const available = await checkSandbox(deps.sandboxAvailable);
125
+ if (!available.ok)
126
+ noSandbox = available.reason;
127
+ }
128
+ if (noSandbox === undefined) {
129
+ mode = persistSandboxPolicy(deps.stateDir)
130
+ ? "sandbox"
131
+ : readPolicy(deps.stateDir).mode;
132
+ }
119
133
  }
120
134
  catch (e) {
121
135
  err(`Cannot set the local policy in ${deps.stateDir}: ${e.message}`);
@@ -141,8 +155,18 @@ export async function login(cmd, deps) {
141
155
  maxFrameBytes: granted.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES,
142
156
  });
143
157
  out(`Logged in. Device ${granted.deviceId}, working directory ${dir}`);
144
- // The risk text is shown once at login (spec §8), and only when this machine runs auto.
145
- if (granted.autoMode === "off") {
158
+ // The risk text is shown once at login (spec §8), and only when commands run on this
159
+ // machine as the owner (auto mode outside Docker).
160
+ if (cmd.mode === "docker") {
161
+ if (granted.autoMode === "off" && mode !== "sandbox")
162
+ out(AUTO_POLICY_REFUSED_LOGIN_LINE);
163
+ else
164
+ out(mode === "sandbox" ? DOCKER_SANDBOX_MODE_LOGIN_LINE : DOCKER_AUTO_MODE_LOGIN_LINE);
165
+ }
166
+ else if (noSandbox !== undefined) {
167
+ out(sandboxUnavailableLoginLine(noSandbox));
168
+ }
169
+ else if (granted.autoMode === "off") {
146
170
  out(mode === "sandbox" ? SANDBOX_MODE_LOGIN_LINE : AUTO_POLICY_REFUSED_LOGIN_LINE);
147
171
  }
148
172
  else if (mode === "sandbox") {
@@ -152,7 +176,11 @@ export async function login(cmd, deps) {
152
176
  out(AUTO_MODE_LOGIN_LINE);
153
177
  out(AUTO_MODE_RISK_TEXT);
154
178
  }
155
- out("Run `capybara-device start` to bring it online (or `capybara-device service install` to connect at login).");
179
+ // An installed service stays stopped after a deliberate exit (not logged in, logged out):
180
+ // it needs starting again, not a second program.
181
+ out(hasLoginService(deps.home, platform)
182
+ ? "The login service is installed: bring it online with `capybara-device service restart`."
183
+ : "Run `capybara-device start` to bring it online (or `capybara-device service install` to connect at login).");
156
184
  return 0;
157
185
  }
158
186
  catch (e) {
@@ -1,7 +1,9 @@
1
+ import { type ProcessLookup } from "../pid.js";
1
2
  export interface LogoutDeps {
2
3
  out: (line: string) => void;
3
4
  err?: (line: string) => void;
4
5
  kill?: typeof process.kill;
6
+ ps?: ProcessLookup;
5
7
  sleep?: (ms: number) => Promise<void>;
6
8
  /** How long to wait for a running program to exit (default 5 s). */
7
9
  waitMs?: number;
@@ -10,7 +10,7 @@ export async function logout(stateDir, deps) {
10
10
  const err = deps.err ?? out;
11
11
  const kill = deps.kill ?? process.kill;
12
12
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13
- const pid = readRunningPid(stateDir, kill);
13
+ const pid = readRunningPid(stateDir, { kill, ...(deps.ps && { ps: deps.ps }) });
14
14
  if (pid !== undefined && pid !== process.pid) {
15
15
  out(`Stopping the running capybara-device (pid ${pid}).`);
16
16
  try {
@@ -26,6 +26,28 @@ export declare const SANDBOX_MODE_LOGIN_LINE: string;
26
26
  * auto policy: the kernel refuses every command until the owner switches the machine.
27
27
  */
28
28
  export declare const AUTO_POLICY_REFUSED_LOGIN_LINE: string;
29
+ /** The line `login --mode docker` prints when the device runs in auto mode. */
30
+ export declare const DOCKER_AUTO_MODE_LOGIN_LINE: string;
31
+ /** The line `login --mode docker` prints when the local policy is sandbox mode. */
32
+ export declare const DOCKER_SANDBOX_MODE_LOGIN_LINE: string;
33
+ /**
34
+ * The line `login` prints when the organization forbids auto mode and the OS sandbox cannot run
35
+ * here: no sandbox policy is written (it could not run a command either).
36
+ */
37
+ export declare function sandboxUnavailableLoginLine(reason: string): string;
38
+ /** The OS sandbox check `login` and `mode` use (default: the runtime's, loaded on demand). */
39
+ export type SandboxCheck = () => {
40
+ ok: true;
41
+ } | {
42
+ ok: false;
43
+ reason: string;
44
+ };
45
+ export declare function checkSandbox(check: SandboxCheck | undefined): Promise<{
46
+ ok: true;
47
+ } | {
48
+ ok: false;
49
+ reason: string;
50
+ }>;
29
51
  export interface ModeDeps {
30
52
  stateDir: string;
31
53
  out: (line: string) => void;
@@ -39,12 +61,7 @@ export interface ModeDeps {
39
61
  * Whether the OS sandbox can run here (default: the runtime's check). `mode sandbox` is refused
40
62
  * when it cannot; injectable for tests.
41
63
  */
42
- sandboxAvailable?: () => {
43
- ok: true;
44
- } | {
45
- ok: false;
46
- reason: string;
47
- };
64
+ sandboxAvailable?: SandboxCheck;
48
65
  }
49
66
  /** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
50
67
  export declare function modeCommand(cmd: Extract<Command, {
@@ -1,4 +1,4 @@
1
- import { sandboxUnavailableSwitchRefusal } from "../exec/sandbox-messages.js";
1
+ import { SANDBOX_INSTALL_HINT, sandboxUnavailableSwitchRefusal } from "../exec/sandbox-messages.js";
2
2
  import { PolicyStore } from "../policy-store.js";
3
3
  import { policyPath, readCredential } from "../state.js";
4
4
  /**
@@ -37,6 +37,28 @@ export const SANDBOX_MODE_LOGIN_LINE = "This organization does not allow auto mo
37
37
  */
38
38
  export const AUTO_POLICY_REFUSED_LOGIN_LINE = "This organization does not allow auto mode, but this machine's local policy is auto mode: the " +
39
39
  "deployment refuses every command until you run `capybara-device mode sandbox`.";
40
+ /** The line `login --mode docker` prints when the device runs in auto mode. */
41
+ export const DOCKER_AUTO_MODE_LOGIN_LINE = "New logins start in auto mode: agent commands run in this device's Docker container with its " +
42
+ "network, file operations reach any path in the container, and the deployment reviews every " +
43
+ "command. Switch with `capybara-device mode sandbox`.";
44
+ /** The line `login --mode docker` prints when the local policy is sandbox mode. */
45
+ export const DOCKER_SANDBOX_MODE_LOGIN_LINE = "This device runs in sandbox mode: agent commands run in this device's Docker container " +
46
+ "without a network, and file operations stay in the device's directories.";
47
+ /**
48
+ * The line `login` prints when the organization forbids auto mode and the OS sandbox cannot run
49
+ * here: no sandbox policy is written (it could not run a command either).
50
+ */
51
+ export function sandboxUnavailableLoginLine(reason) {
52
+ return ("This organization does not allow auto mode, and the OS sandbox is unavailable on this " +
53
+ `machine (${reason}), so no command can run here yet: ${SANDBOX_INSTALL_HINT}, then run ` +
54
+ "`capybara-device mode sandbox`; or log in again with --mode docker.");
55
+ }
56
+ export async function checkSandbox(check) {
57
+ if (check !== undefined)
58
+ return check();
59
+ const os = await import("../exec/os.js");
60
+ return os.sandboxAvailability();
61
+ }
40
62
  /** Whether this machine is logged in in Docker mode (false when unknown). */
41
63
  function dockerRunMode(stateDir) {
42
64
  try {
@@ -86,8 +108,7 @@ export async function modeCommand(cmd, deps) {
86
108
  if (mode === "sandbox" && !dockerRunMode(stateDir)) {
87
109
  // Sandbox mode cannot run a command without the OS sandbox; refuse the switch on such a
88
110
  // machine and leave the policy as it is (auto mode keeps working).
89
- const os = await import("../exec/os.js");
90
- const available = deps.sandboxAvailable?.() ?? os.sandboxAvailability();
111
+ const available = await checkSandbox(deps.sandboxAvailable);
91
112
  if (!available.ok) {
92
113
  err(sandboxUnavailableSwitchRefusal(available.reason));
93
114
  return 1;
@@ -1,3 +1,5 @@
1
+ import { type ProcessChecks } from "../pid.js";
2
+ import { type RunSystem } from "../service/manager.js";
1
3
  export type ServiceAction = "install" | "uninstall" | "start" | "stop" | "restart" | "status";
2
4
  export interface ServiceDeps {
3
5
  stateDir: string;
@@ -7,12 +9,15 @@ export interface ServiceDeps {
7
9
  out: (line: string) => void;
8
10
  err: (line: string) => void;
9
11
  /**
10
- * Runs a system command; throws when it fails (default: execFileSync, whose error carries the
11
- * exit `status` and `stderr`).
12
+ * Runs a system command and returns its output; throws when it fails (default: execFileSync,
13
+ * whose error carries the exit `status` and `stderr`).
12
14
  */
13
- run?: (cmd: string, args: string[]) => void;
14
- /** Waits between launchctl checks (default: setTimeout). */
15
+ run?: RunSystem;
16
+ /** Waits between service manager checks (default: setTimeout). */
15
17
  sleep?: (ms: number) => Promise<void>;
18
+ /** How the pid file's program is checked (default: `kill(pid, 0)` and `ps`). */
19
+ kill?: typeof process.kill;
20
+ ps?: ProcessChecks["ps"];
16
21
  uid?: number;
17
22
  nodePath?: string;
18
23
  binPath?: string;
@@ -23,6 +28,8 @@ export declare function serviceEnv(env: Record<string, string | undefined>): Rec
23
28
  export declare const SERVICE_POLL_MS = 200;
24
29
  /** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
25
30
  export declare const SERVICE_GONE_TIMEOUT_MS = 10000;
31
+ /** How long `service start|restart` wait for the program to be running. */
32
+ export declare const SERVICE_UP_TIMEOUT_MS = 10000;
26
33
  /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
27
34
  export declare const BOOTSTRAP_BACKOFF_MS: readonly [500, 1000, 2000];
28
35
  /**