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

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
@@ -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
@@ -88,7 +92,11 @@ If the OS sandbox is unavailable on the machine (an unsupported platform or miss
88
92
  such as `bwrap` / `socat` on Linux), the device still starts and serves: auto mode works, and every
89
93
  sandbox-mode command is refused with the reason and how to fix it (`capybara-device mode auto`, or
90
94
  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.
95
+ and the policy stays in auto; nothing ever runs unsandboxed by falling back. File operations
96
+ (read, write, stat) there follow only a fresh command decision (the latest command, within a
97
+ minute): without one they are refused, never served on the host. `login` into an organization that
98
+ forbids auto mode checks the OS sandbox first: when it is unavailable, no sandbox policy is written
99
+ and the login line says what to install (or to log in with `--mode docker`).
92
100
 
93
101
  ```bash
94
102
  capybara-device mode # print the current mode
@@ -135,8 +143,8 @@ lines (at most 21).
135
143
 
136
144
  In OS mode each command's result also carries the refused hosts and their layers, so the
137
145
  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`).
146
+ with a summary of its local policy: the owner's `mode`, never cut by an exec's ceiling (the
147
+ deployment applies its own), and the sandbox-mode `allowedDomains`).
140
148
 
141
149
  ### Sandbox mode details
142
150
 
@@ -222,22 +230,32 @@ need to allow single domains.
222
230
 
223
231
  `capybara-device service install` makes the program start at login: on macOS a launchd agent
224
232
  (`~/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.
233
+ Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). Both restart the
234
+ program only when it exits non-zero: the macOS agent uses `KeepAlive { SuccessfulExit: false }`, at
235
+ most every 30 s (`ThrottleInterval`); systemd `Restart=on-failure`, after 5 s. Exit 0 is a deliberate
236
+ stop and stays stopped.
228
237
 
229
238
  `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
239
+ service (the plist or unit stays) rather than signalling the program; running commands end with
240
+ it, and it reports a failure when the service is still loaded afterwards. `start` and `restart`
241
+ wait (up to 10 s) until the service manager runs the program and report a failure, pointing at
242
+ `service.log`, when it does not come back; `service start` refuses while a program started in a
243
+ terminal runs ("stop it first"). On macOS a loaded agent whose program exited is started again with
244
+ `launchctl kickstart`. `restart` reloads the program from the installed `bin`, so it is **the way to
245
+ apply a package upgrade**: `npm i -g @capybara-hq/device@latest && capybara-device service restart`.
246
+ The top-level `stop` refuses only when the service manager runs the program it would signal (launchd
247
+ has the agent loaded, or systemd the unit active, and its pid is the pid file's) and points at
248
+ `service stop`; a program started in a terminal is signalled as before. `start` in a terminal says
249
+ how to restart the installed service; started by the service manager (launchd sets
250
+ `XPC_SERVICE_NAME`, systemd `INVOCATION_ID`) it prints no such hint.
251
+
252
+ `capybara-device service status` says one of four things: not installed; installed but not loaded
253
+ (`service start`); loaded but the program is not running, i.e. it exited (the reason is at the end of
254
+ `service.log`; fix it, then `service restart`); or running, with the service manager's pid and the
255
+ program's **version**. When the package at the service file's `bin` path (its `package.json`) is a
256
+ different version from the running program, it adds the restart command: an upgrade the service has
257
+ not picked up yet. The pid file records the version (`{pid, version, startedAt}`); one written by an
258
+ older program reads as "version unknown". A user unit runs only
241
259
  while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
242
260
  running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
243
261
  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
@@ -33,9 +33,11 @@ export interface ConnectOptions {
33
33
  policyCheckMs?: number;
34
34
  }
35
35
  /**
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.
36
+ * A running connection. `done` resolves with the exit code once the program should end: 0 for a
37
+ * deliberate stop (revoked, replaced by a newer connection of this device, deleted, stopped,
38
+ * drained), which a service manager that restarts on failure leaves stopped; 1 when the deployment
39
+ * needs a newer program (426), which an upgrade in place recovers once the service starts it again.
40
+ * Connection failures never end it: they reconnect with backoff.
39
41
  */
40
42
  export interface Connection {
41
43
  readonly done: Promise<number>;
package/dist/client.js CHANGED
@@ -78,9 +78,9 @@ export function connect(cred, executor, opts = {}) {
78
78
  let sentPolicy;
79
79
  /**
80
80
  * 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.
81
+ * changed the mode or the policy on the machine (`capybara-device mode` / `policy ...`). Without
82
+ * it the deployment would learn the change only at the next connect. An exec's ceiling changes
83
+ * nothing here: the summary reports the owner's mode, which the kernel cuts itself.
84
84
  */
85
85
  const pushPolicy = () => {
86
86
  if (!isOpen())
@@ -197,8 +197,6 @@ export function connect(cred, executor, opts = {}) {
197
197
  sentPolicy = JSON.stringify(res.result.policy);
198
198
  }
199
199
  deliver(res);
200
- // an exec may have changed the ceiling (the effective mode)
201
- pushPolicy();
202
200
  }
203
201
  maybeFinishDrain();
204
202
  });
@@ -240,7 +238,7 @@ export function connect(cred, executor, opts = {}) {
240
238
  /**
241
239
  * The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
242
240
  * 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;
241
+ * policy summary is the store's policy now (the owner's mode, not cut by any ceiling);
244
242
  * then the outcomes of the latest policy ops by op id.
245
243
  */
246
244
  const hello = () => {
@@ -341,8 +339,10 @@ export function connect(cred, executor, opts = {}) {
341
339
  sock.terminate();
342
340
  if (status === 401)
343
341
  return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
342
+ // Not a deliberate stop: upgrading the package in place recovers it, so the exit is
343
+ // non-zero and the service manager starts the (new) program again.
344
344
  if (status === 426)
345
- return endSession({ exit: 0, message: OUTDATED_MESSAGE });
345
+ return endSession({ exit: 1, message: OUTDATED_MESSAGE });
346
346
  reportFailure(status === 404
347
347
  ? `Connecting to ${cred.connectUrl} failed: HTTP 404. The deployment must route ` +
348
348
  "/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
  /**