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

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 (64) hide show
  1. package/README.md +187 -44
  2. package/dist/api.d.ts +6 -1
  3. package/dist/args.d.ts +14 -3
  4. package/dist/args.js +74 -10
  5. package/dist/cli.d.ts +14 -2
  6. package/dist/cli.js +59 -10
  7. package/dist/client.d.ts +14 -3
  8. package/dist/client.js +92 -18
  9. package/dist/command-log.d.ts +8 -0
  10. package/dist/commands/drain.d.ts +13 -0
  11. package/dist/commands/drain.js +28 -0
  12. package/dist/commands/login.js +68 -11
  13. package/dist/commands/mode.d.ts +52 -0
  14. package/dist/commands/mode.js +108 -0
  15. package/dist/commands/policy.d.ts +13 -4
  16. package/dist/commands/policy.js +162 -33
  17. package/dist/commands/service.d.ts +18 -3
  18. package/dist/commands/service.js +175 -9
  19. package/dist/commands/start.d.ts +14 -3
  20. package/dist/commands/start.js +37 -5
  21. package/dist/commands/status.js +12 -4
  22. package/dist/commands/stop.d.ts +9 -2
  23. package/dist/commands/stop.js +13 -2
  24. package/dist/exec/docker.d.ts +41 -13
  25. package/dist/exec/docker.js +123 -57
  26. package/dist/exec/fs-helper.d.ts +13 -8
  27. package/dist/exec/fs-helper.js +31 -13
  28. package/dist/exec/groups.d.ts +42 -0
  29. package/dist/exec/groups.js +100 -0
  30. package/dist/exec/host.d.ts +53 -0
  31. package/dist/exec/host.js +183 -0
  32. package/dist/exec/os.d.ts +85 -15
  33. package/dist/exec/os.js +208 -36
  34. package/dist/exec/reap.d.ts +41 -0
  35. package/dist/exec/reap.js +89 -0
  36. package/dist/exec/sandbox-messages.d.ts +14 -0
  37. package/dist/exec/sandbox-messages.js +21 -0
  38. package/dist/exec/shared.d.ts +42 -13
  39. package/dist/exec/shared.js +94 -16
  40. package/dist/exec/switch.d.ts +91 -0
  41. package/dist/exec/switch.js +164 -0
  42. package/dist/exec/types.d.ts +28 -4
  43. package/dist/index.d.ts +1 -1
  44. package/dist/network.d.ts +45 -0
  45. package/dist/network.js +154 -0
  46. package/dist/pid.d.ts +13 -1
  47. package/dist/pid.js +54 -7
  48. package/dist/policy-ops.d.ts +47 -0
  49. package/dist/policy-ops.js +90 -0
  50. package/dist/policy-store.d.ts +43 -0
  51. package/dist/policy-store.js +94 -0
  52. package/dist/policy.d.ts +36 -16
  53. package/dist/policy.js +77 -19
  54. package/dist/public-suffix.d.ts +6 -0
  55. package/dist/public-suffix.js +79 -0
  56. package/dist/server-ops.d.ts +46 -7
  57. package/dist/server-ops.js +285 -29
  58. package/dist/service/installed.d.ts +5 -0
  59. package/dist/service/installed.js +14 -0
  60. package/dist/service/launchd.d.ts +11 -1
  61. package/dist/service/launchd.js +14 -5
  62. package/dist/state.d.ts +50 -6
  63. package/dist/state.js +195 -16
  64. package/package.json +3 -3
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @capybara-hq/device
2
2
 
3
3
  `capybara-device` connects a laptop or server to a [Capybara](https://github.com/capybara-hq/core)
4
- deployment as an environment: the platform's agents run commands and read and write files on this
5
- machine, inside a sandbox, while the program is online.
4
+ deployment as a device: the platform's agents run commands and read and write files on this
5
+ machine, in auto mode (as you, with every command reviewed by the deployment) or inside an OS
6
+ sandbox, while the program is online.
6
7
 
7
8
  Runs on macOS and Linux. Native Windows is refused: use WSL (then it is a Linux machine) or Docker
8
9
  mode inside WSL. Node 22.12 or newer.
@@ -16,89 +17,231 @@ capybara-device status [--json]
16
17
  capybara-device logout
17
18
  ```
18
19
 
19
- `login` shows a code like `BCDF-GHJK`; with `--no-browser` it prints the address (`<url>/device`) and
20
- the code to enter on any signed-in browser, where you pick the org and the environment (a new one or
20
+ `login` shows a code like `BCDF-GHJK`; with `--no-browser` it prints the address (`<url>/devices/link`) and
21
+ the code to enter on any signed-in browser, where you pick the org and the device (a new one or
21
22
  an existing connected one of yours) after reading what the program can do. Logging in again from
22
- another machine into the same environment replaces the first machine (its credential is revoked).
23
+ another machine into the same device replaces the first machine (its credential is revoked).
23
24
  `stop` ends the running program, `drain` makes it accept no new commands and exit when the running
24
- ones finish. `logout` stops a running program, then forgets the credential (the machine stays
25
- connected on the platform until it is revoked there). Deleting the environment in the web app
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
28
+ running program, then forgets the credential (the machine stays
29
+ connected on the platform until it is revoked there). Deleting the device in the web app
26
30
  revokes the machine and stops the program; the files in the working directory stay on your machine.
27
31
 
28
32
  The deployment must route `/device/connect` on its public URL to the gateway role (see
29
33
  [Connected devices](https://github.com/capybara-hq/core/blob/main/docs/deploy/README.md#connected-devices)).
30
- While connecting keeps failing, `start` retries and prints why at most once a minute: the HTTP
31
- status (a 404 usually means that route is missing), the close reason, or the network error.
34
+ While connecting keeps failing, `start` retries with exponential backoff (capped at 60 s, with
35
+ jitter) and never gives up: a failure different from the last one is printed at once, the same one
36
+ at most once a minute. The message is the HTTP status (a 404 usually means that route is missing),
37
+ the close reason, or the network error.
32
38
 
33
39
  `start` exits 0, after printing why, when retrying cannot help: the machine was revoked or the
34
- environment deleted, the program is too old for the deployment (426), another login replaced this
35
- connection, or the machine is not logged in. Other failures exit non-zero, so a service (below)
36
- restarts the program after those and leaves it stopped after the terminal ones; fix the cause
37
- (log in again, upgrade), then run `start` or `service install` again.
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.
38
45
 
39
46
  If the working directory (or its marker `.capybara-device`, or one of `workspace/`, `skills/`,
40
47
  `tmp/`) is removed, the program never recreates it: operations answer that the files are lost and
41
- the environment page says so. To start afresh, run `capybara-device logout` and then
42
- `capybara-device login` into the same environment: login recreates the directory and the marker,
43
- and the platform rebuilds the environment on its next use.
48
+ the device page says so. To start afresh, run `capybara-device logout` and then
49
+ `capybara-device login` into the same device: login recreates the directory and the marker,
50
+ and the platform rebuilds the device on its next use.
44
51
 
45
52
  Commands: `login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]`, `logout`,
46
- `status [--json]`, `start`, `stop`, `drain`, `policy [show|set <key> <value>]` and
47
- `service install|uninstall`.
53
+ `status [--json]` (it prints the command mode too), `start`, `stop`,
54
+ `drain [--wait] [--timeout <seconds>]`, `mode [auto|sandbox] [--yes]`,
55
+ `policy [show | set <key> <value> [--yes] | add|remove <key> <value>]` and
56
+ `service install|uninstall|start|stop|restart|status`.
57
+ `mode` is the only way to switch the command mode (`policy set mode` points there); `mode auto`
58
+ prints the risk text and asks for confirmation unless `--yes` is given.
48
59
 
49
60
  State lives in `$XDG_CONFIG_HOME/capybara-device` (default `~/.config/capybara-device`):
50
61
  `credential.json` (mode 0600; the program refuses a file other users can read; it also holds the
51
62
  deployment's reconnect grace and frame limit: a result larger than the frame limit is answered
52
63
  with an error instead) and `policy.json` (a file with wrong field types stops `start` with an
53
- error naming it).
54
- The working directory (default `~/capybara-device/<environmentId>`) holds `workspace/`, `skills/`
64
+ error naming it; once running, the program re-reads the file when it changes, and a broken edit
65
+ keeps the last valid policy and logs one error). Changes made with `capybara-device policy` take
66
+ `policy.json.lock`, so two writers never lose an update; keys this version does not know are kept.
67
+ The working directory (default `~/capybara-device/<deviceId>`) holds `workspace/`, `skills/`
55
68
  and `tmp/`.
56
69
 
57
- In OS mode every command runs inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux
58
- bubblewrap; Linux needs `bwrap` and `socat`): writes only under `workspace/` and `tmp/`,
59
- `skills/` read only, `~/.ssh`, cloud CLI credentials, `~/.netrc`, `~/.gnupg`, browser profiles and
60
- this program's state directory unreadable. Network is limited to the domains of the local policy
61
- that the environment's egress also allows; with an empty policy (the default) commands reach no
62
- network at all. Only you edit the policy, the platform can never widen it:
70
+ In OS mode a device runs every command in one of two modes (`mode` in `policy.json`; switch it
71
+ with `capybara-device mode`):
72
+
73
+ - **auto** (the default of a new login): commands run directly on this computer as you — your real
74
+ `HOME`, `PATH`, environment, caches, credentials (SSH keys, `gh`, cloud CLIs), Docker and any
75
+ network. It is what a coding agent without an OS sandbox has, and what Claude Code calls auto
76
+ mode. The deployment reviews every command before it runs and blocks, or asks about, the
77
+ 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.
79
+ - **sandbox**: today's strict `@anthropic-ai/sandbox-runtime` profile (macOS Seatbelt, Linux
80
+ bubblewrap; Linux needs `bwrap` and `socat`). Writes only under `workspace/` and `tmp/`,
81
+ `skills/` read only, `HOME` = the workspace, `~/.ssh`, cloud CLI credentials, `~/.netrc`,
82
+ `~/.gnupg`, browser profiles and this program's state directory unreadable, no local binding or
83
+ unix sockets, and network only to the domains of the local policy that the organization's
84
+ allowlist also admits (with an empty list, no network at all). Commands keep their package
85
+ caches in the workspace like any other file.
86
+
87
+ If the OS sandbox is unavailable on the machine (an unsupported platform or missing dependencies,
88
+ such as `bwrap` / `socat` on Linux), the device still starts and serves: auto mode works, and every
89
+ sandbox-mode command is refused with the reason and how to fix it (`capybara-device mode auto`, or
90
+ 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.
63
92
 
64
93
  ```bash
65
- capybara-device policy set allowedDomains registry.npmjs.org,*.github.com
66
- capybara-device policy show # changes apply at the next start
94
+ capybara-device mode # print the current mode
95
+ capybara-device mode sandbox # switch to the sandbox
96
+ capybara-device mode auto # prints the risk text and asks; or add --yes
97
+ capybara-device policy add allowedDomains files.slack.com # sandbox mode
98
+ capybara-device policy remove allowedDomains files.slack.com
99
+ capybara-device policy show
67
100
  ```
68
101
 
102
+ A change applies at the next command; a running program does not need a restart. Turning the
103
+ sandbox back on stops the commands still running in auto mode. Auto mode is set only on the
104
+ machine: the deployment may narrow a device to `sandbox` but never turn auto mode on. An
105
+ organization can allow or forbid auto mode; when it forbids it, this device runs in the sandbox
106
+ and its summary says so, and the device's own `mode sandbox` always wins. `add` and `remove` work
107
+ on `allowedDomains` and `allowCredentials`; every domain must be a lowercase host name (optionally
108
+ `*.` for subdomains, never the apex), never an IP address or an internal name. They apply in
109
+ sandbox mode only.
110
+
111
+ A command ends with everything it started: once it returns (or times out, or is stopped), the
112
+ program kills what it left running, such as `server &` or `nohup …`, because inside the sandbox no
113
+ later command may signal another command's processes. Its process group goes at once, and a process
114
+ that left the group (`setsid`) is found by the marker every process of the command carries. On
115
+ macOS only a background task launch (`Bash` with `run_in_background`, whose command starts with the
116
+ line `# capybara: background task launch`) keeps what it starts. On Linux the sandbox's pid
117
+ namespace already ends every process with its command. In Docker mode and without a sandbox, a
118
+ later command can stop what an earlier one left, so nothing is killed.
119
+
120
+ When a command is refused a domain, the program says why. Clients that print the proxy's answer
121
+ show a reason such as `capybara: files.slack.com is not in this device's allowed domains`, and
122
+ after the command its stderr ends with a trailer naming each refused host (at most 20) and who can
123
+ lift it:
124
+
125
+ ```text
126
+ [capybara-device] Network access was blocked:
127
+ - files.slack.com:443: not in this device's allowed domains. Only the device owner can allow it (capybara-device policy add allowedDomains files.slack.com, or the device page).
128
+ - api.foo.com:443: not in the organization's network allowlist. Only an organization admin can add it.
129
+ - 10.0.0.5:22: a private or local address; commands can never reach it.
130
+ ```
131
+
132
+ The trailer is part of the command's output, so the agent reads it too. It comes after the
133
+ output the deployment asked for (`maxOutputBytes`), so stderr can exceed that cap by the trailer's
134
+ lines (at most 21).
135
+
136
+ In OS mode each command's result also carries the refused hosts and their layers, so the
137
+ 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`).
140
+
141
+ ### Sandbox mode details
142
+
143
+ In sandbox mode commands keep `HOME` = `workspace/`, writes stay inside the device directory, the
144
+ secret paths stay unreadable, and the network proxy refuses loopback, private addresses and
145
+ internal names as destinations. The device's `allowedDomains` are intersected with the
146
+ organization's allowlist; a host either list refuses is reported as described above.
147
+
148
+ Version managers (asdf, nvm, pyenv, mise, …) find their data under the real home, read only, so
149
+ their shims work with `HOME` = the workspace. Git can read a repository, but `.git/config` and
150
+ `.git/hooks` stay unwritable: a hook or `core.sshCommand` a command wrote would run when you later
151
+ run git there. When you want git to write (init, clone, remotes) or commands to use your
152
+ credentials, use auto mode.
153
+
154
+ ### The auto mode risk
155
+
156
+ In auto mode agent commands have your full capability. The deployment reviews every command and
157
+ blocks or asks about the dangerous ones, but that review is the boundary, not an OS sandbox: prompt
158
+ injection can still make an agent attempt to delete files or send your credentials away. Commands
159
+ can also read this program's own credential (`credential.json`): if you suspect misuse, run
160
+ `capybara-device logout` and log in again, which revokes it. Keep auto mode to your own development
161
+ machine, with agents and material you trust; `capybara-device mode sandbox` turns the sandbox back
162
+ on.
163
+
164
+ ### Changes from the deployment
165
+
166
+ The deployment changes the local policy only by narrowing it: it may add or remove
167
+ `allowedDomains` (an approval adds an exact host; the device page may add a `*.` wildcard) and set
168
+ `mode: "sandbox"`. It can never set `mode: "auto"` — that is `capybara-device mode auto` on the
169
+ machine, with its risk text and confirmation. Every host is validated like a local one, the change
170
+ is written under `policy.json.lock`, and it applies at the next command. Each change from the
171
+ deployment is recorded in the local command log (`commands.log`, next to `policy.json`) with who
172
+ decided it, and so is a refused attempt and the grants a command was given:
173
+
174
+ ```text
175
+ {"op":"policy","detail":"policy add files.slack.com by Ada Lovelace (acc_123) via web, approval apr_456",...}
176
+ {"op":"policy","detail":"policy refused mode auto by Ada Lovelace (acc_123) via web",...}
177
+ {"op":"exec","detail":"grants run run_789 by acc_123: files.slack.com",...}
178
+ ```
179
+
180
+ A run's or a scheduled task's network grants apply in sandbox mode only, within the organization's
181
+ allowlist; auto mode has the machine's own network, so grants do nothing there.
182
+
183
+ Limit to know: commands of one device run as the same user, and the sandbox runtime ties a
184
+ command's list (including its run grants) to the proxy credentials it hands that command. Another
185
+ command running at the same time on the same device could reuse them, so a run's grants may be
186
+ usable by a concurrent command of another run on that device: same owner, same device.
187
+
69
188
  Limits to know: the platform's `Grep` tool assumes GNU grep, so on macOS (BSD grep) in OS mode some
70
189
  Grep options behave differently or fail. Docker mode (a Linux container) does not have this issue.
71
190
 
72
- Not enforced yet in OS mode: the `cpu` and `memoryMb` ceilings, and `allowCredentials` (commands
73
- get no local credentials at all). Processes a command leaves running are killed with it by tag;
74
- on macOS a child that leaves the command's process group and runs only Apple system binaries
75
- cannot be found again (Linux runs each command in its own pid namespace, which takes every child
76
- down with it).
191
+ Not enforced yet in OS mode: the `cpu` and `memoryMb` ceilings. In auto mode commands already see
192
+ the owner's credentials, so `allowCredentials` has nothing to add; in sandbox mode they get none.
193
+ Processes a command leaves running are killed when it ends; on macOS a child that leaves the
194
+ command's process group and runs only Apple system binaries cannot be found by its marker
195
+ (`ps -E` hides their environment), so it survives (Linux runs each command in its own pid
196
+ namespace, which takes every child down with it).
77
197
 
78
198
  ## Docker mode
79
199
 
80
- `login --mode docker` runs every command with `docker exec` in one container per environment
81
- (`capybara-device-<environmentId>`, started on first use from
200
+ `login --mode docker` runs every command with `docker exec` in one container per device
201
+ (`capybara-device-<deviceId>`, started on first use from
82
202
  `ghcr.io/capybara-hq/capybara-sandbox:<tag>`, the sandbox image of this release). On Linux commands
83
203
  run as your own uid:gid, so they can write the mounted directories you own (a root user falls back to
84
204
  the image's `sandbox` user, uid 1000); on macOS as the image's `sandbox` user. `<dir>/workspace`, `<dir>/skills` (read only) and `<dir>/tmp` are mounted
85
205
  at `/workspace`, `/skills` and `/tmp`; the container has a read-only root file system, a pids limit of 1024, `--memory-swap` equal to
86
206
  `memoryMb`, `--cap-drop ALL` and `no-new-privileges`. The policy's `cpu` and
87
- `memoryMb` become `--cpus` and `--memory`. The container is reused while its mounts and limits
88
- match and recreated when they change; it stays running (idle) between starts.
207
+ `memoryMb` become `--cpus` and `--memory`. The container is reused while its mounts and flags
208
+ match and recreated when they change (at the next command that finds it idle); it stays running
209
+ (idle) between starts. Commands always have the container's own localhost and unix sockets.
210
+
211
+ Docker mode has no per-domain network filter, so the mode alone decides:
212
+
213
+ - **auto**: the container runs on Docker's default bridge (the whole internet and this machine's
214
+ network), and the platform's file tools reach any absolute path in the container.
215
+ - **sandbox**: the container has no network at all, and file operations stay in the mounted roots.
89
216
 
90
- Docker mode has no domain allowlist: a command has either no network (`--network none`, when the
91
- local policy or the environment's egress allows no domain) or the default bridge, with the whole
92
- internet. Use OS mode to limit commands to the domains of the local policy.
217
+ The network is switched between the two without recreating the container (a container disconnected
218
+ from every network has no network, the same as `--network none`). Use OS mode's sandbox when you
219
+ need to allow single domains.
93
220
 
94
221
  ## Running at login
95
222
 
96
223
  `capybara-device service install` makes the program start at login: on macOS a launchd agent
97
224
  (`~/Library/LaunchAgents/top.capybara.device.plist`, log `service.log` in the state directory), on
98
- Linux a systemd user unit (`~/.config/systemd/user/capybara-device.service`). Both restart the
99
- program when it exits non-zero (systemd after 5 s) and leave it stopped after a terminal exit (code
100
- 0, see above); once the cause is fixed, `service install` again starts it. A user unit runs only
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.
228
+
229
+ `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
101
241
  while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
102
242
  running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
103
243
  starts. The service runs `node <bin> start` with the `PATH` of the shell that installed it (so
104
- `docker` is found). `service uninstall` reverses it.
244
+ `docker` is found). `service uninstall` reverses it. On macOS, installing again first boots the old
245
+ agent out and waits (up to 10 s) until launchd has let it go, because `launchctl bootout` returns
246
+ before that; a `bootstrap` that still fails with error 5 (Input/output error) is retried a few
247
+ times. On Linux, installing again restarts the unit so the new file applies.
package/dist/api.d.ts CHANGED
@@ -9,11 +9,16 @@ export interface AuthorizeResponse {
9
9
  export interface TokenResponse {
10
10
  credential: string;
11
11
  orgId: string;
12
- environmentId: string;
12
+ deviceId: string;
13
13
  connectUrl: string;
14
14
  reconnectGraceSeconds: number;
15
15
  /** The program uses 16 MiB when it is absent. */
16
16
  maxFrameBytes?: number;
17
+ /**
18
+ * Whether the organization allows auto mode (`allowed`, the default) or forbids it (`off`):
19
+ * `login` prints the matching line. Absent counts as allowed.
20
+ */
21
+ autoMode?: "allowed" | "off";
17
22
  }
18
23
  /** An error response of the kernel: `{ error: { code, message } }`. */
19
24
  export declare class ApiError extends Error {
package/dist/args.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SandboxMode } from "./state.js";
1
2
  export type DeviceMode = "os" | "docker";
2
3
  /** A parsed command line. */
3
4
  export type Command = {
@@ -17,21 +18,31 @@ export type Command = {
17
18
  command: "stop";
18
19
  } | {
19
20
  command: "drain";
21
+ /** `--wait`: wait until the program has exited. */
22
+ wait?: true;
23
+ /** `--timeout <seconds>` with `--wait` (default 600). */
24
+ timeoutSeconds?: number;
20
25
  } | {
21
26
  command: "policy";
22
27
  action: "show";
23
28
  } | {
24
29
  command: "policy";
25
- action: "set";
30
+ action: "set" | "add" | "remove";
26
31
  key: string;
27
32
  value: string;
33
+ } | {
34
+ command: "mode";
35
+ /** Absent: print the current mode. */
36
+ mode?: SandboxMode;
37
+ /** `--yes`: confirms `mode auto` without asking. */
38
+ yes?: true;
28
39
  } | {
29
40
  command: "service";
30
- action: "install" | "uninstall";
41
+ action: "install" | "uninstall" | "start" | "stop" | "restart" | "status";
31
42
  } | {
32
43
  command: "help";
33
44
  };
34
- 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 environment\n capybara-device stop Stop the running program\n capybara-device drain Finish running commands, accept no new ones, then stop\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n capybara-device service install|uninstall\n Run at login as a user service";
45
+ 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 mode [auto|sandbox] [--yes]\n Show or choose how commands run: auto (as you on this\n machine, every command reviewed) or sandbox (applies at\n the next command; auto needs --yes or a y at the prompt)\n capybara-device policy [show] Show the local policy\n capybara-device policy set <key> <value>\n Replace one field (cpu, memoryMb, allowCredentials)\n capybara-device policy add|remove allowedDomains <host>\n Allow or stop allowing a domain in sandbox mode\n capybara-device policy add|remove allowCredentials <name>\n Allow or stop allowing a credential in sandbox mode\n capybara-device service install|uninstall\n Run at login as a user service, or remove it\n capybara-device service start|stop|restart\n Start, stop or restart the login service\n capybara-device service status Report whether the login service is loaded, what is running,\n and whether it is older than the installed program";
35
46
  /** Thrown for a bad command line; the message is shown with the usage. */
36
47
  export declare class UsageError extends Error {
37
48
  }
package/dist/args.js CHANGED
@@ -4,13 +4,28 @@ export const USAGE = `Usage:
4
4
  Connect this machine: approve the code in the browser
5
5
  capybara-device logout Forget the credential on this machine
6
6
  capybara-device status [--json] Show whether this machine is logged in
7
- capybara-device start Connect and serve the environment
7
+ capybara-device start Connect and serve the device
8
8
  capybara-device stop Stop the running program
9
- capybara-device drain Finish running commands, accept no new ones, then stop
9
+ capybara-device drain [--wait] [--timeout <seconds>]
10
+ Finish running commands, accept no new ones, then stop;
11
+ --wait returns once it has stopped (default limit 600 s)
12
+ capybara-device mode [auto|sandbox] [--yes]
13
+ Show or choose how commands run: auto (as you on this
14
+ machine, every command reviewed) or sandbox (applies at
15
+ the next command; auto needs --yes or a y at the prompt)
10
16
  capybara-device policy [show] Show the local policy
11
17
  capybara-device policy set <key> <value>
18
+ Replace one field (cpu, memoryMb, allowCredentials)
19
+ capybara-device policy add|remove allowedDomains <host>
20
+ Allow or stop allowing a domain in sandbox mode
21
+ capybara-device policy add|remove allowCredentials <name>
22
+ Allow or stop allowing a credential in sandbox mode
12
23
  capybara-device service install|uninstall
13
- Run at login as a user service`;
24
+ Run at login as a user service, or remove it
25
+ capybara-device service start|stop|restart
26
+ Start, stop or restart the login service
27
+ capybara-device service status Report whether the login service is loaded, what is running,
28
+ and whether it is older than the installed program`;
14
29
  /** Thrown for a bad command line; the message is shown with the usage. */
15
30
  export class UsageError extends Error {
16
31
  }
@@ -66,26 +81,75 @@ export function parseCommandLine(argv) {
66
81
  case "logout":
67
82
  case "start":
68
83
  case "stop":
69
- case "drain":
70
84
  return noArgs(name);
85
+ case "drain": {
86
+ const { values, positionals } = parse(rest, {
87
+ wait: { type: "boolean" },
88
+ timeout: { type: "string" },
89
+ });
90
+ if (positionals.length > 0)
91
+ throw new UsageError("drain takes no positional arguments");
92
+ if (values.timeout !== undefined && values.wait !== true) {
93
+ throw new UsageError("--timeout needs --wait");
94
+ }
95
+ if (values.wait !== true)
96
+ return { command: "drain" };
97
+ if (values.timeout === undefined)
98
+ return { command: "drain", wait: true };
99
+ const seconds = Number(values.timeout);
100
+ if (!Number.isInteger(seconds) || seconds < 1) {
101
+ throw new UsageError("--timeout must be a whole number of seconds, at least 1");
102
+ }
103
+ return { command: "drain", wait: true, timeoutSeconds: seconds };
104
+ }
71
105
  case "policy": {
72
106
  const { positionals } = parse(rest, {});
73
107
  const [action, key, value, ...extra] = positionals;
74
- if (action === undefined || (action === "show" && key === undefined && extra.length === 0)) {
108
+ if (action === undefined)
109
+ return { command: "policy", action: "show" };
110
+ if (action === "show" && key === undefined && extra.length === 0) {
75
111
  return { command: "policy", action: "show" };
76
112
  }
77
- if (action === "set" && key !== undefined && value !== undefined && extra.length === 0) {
78
- return { command: "policy", action: "set", key, value };
113
+ if ((action === "set" || action === "add" || action === "remove") &&
114
+ key !== undefined &&
115
+ value !== undefined &&
116
+ extra.length === 0) {
117
+ return { command: "policy", action, key, value };
79
118
  }
80
- throw new UsageError("usage: policy [show | set <key> <value>]");
119
+ throw new UsageError("usage: policy [show | set <key> <value> | add|remove <key> <value>]");
120
+ }
121
+ case "mode": {
122
+ const { values, positionals } = parse(rest, { yes: { type: "boolean", short: "y" } });
123
+ const [which, ...extra] = positionals;
124
+ if (extra.length > 0) {
125
+ throw new UsageError("usage: mode [auto|sandbox] [--yes]");
126
+ }
127
+ if (which !== undefined && which !== "auto" && which !== "sandbox") {
128
+ throw new UsageError("mode must be auto or sandbox");
129
+ }
130
+ const yes = values.yes === true;
131
+ if (yes && which === undefined) {
132
+ throw new UsageError("--yes needs a mode: mode auto|sandbox");
133
+ }
134
+ return {
135
+ command: "mode",
136
+ ...(which !== undefined && { mode: which }),
137
+ ...(yes && which !== undefined && { yes: true }),
138
+ };
81
139
  }
82
140
  case "service": {
83
141
  const { positionals } = parse(rest, {});
84
142
  const [action, ...extra] = positionals;
85
- if ((action === "install" || action === "uninstall") && extra.length === 0) {
143
+ if ((action === "install" ||
144
+ action === "uninstall" ||
145
+ action === "start" ||
146
+ action === "stop" ||
147
+ action === "restart" ||
148
+ action === "status") &&
149
+ extra.length === 0) {
86
150
  return { command: "service", action };
87
151
  }
88
- throw new UsageError("usage: service install|uninstall");
152
+ throw new UsageError("usage: service install|uninstall|start|stop|restart|status");
89
153
  }
90
154
  default:
91
155
  throw new UsageError(`unknown command ${name}`);
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Executor } from "./exec/types.js";
2
- import { type Credential, type Policy } from "./state.js";
2
+ import type { PolicyStore } from "./policy-store.js";
3
+ import { type Credential } from "./state.js";
3
4
  export interface CliEnv {
4
5
  env?: Record<string, string | undefined>;
5
6
  home?: string;
@@ -9,10 +10,21 @@ export interface CliEnv {
9
10
  openBrowser?: (url: string) => void;
10
11
  out?: (line: string) => void;
11
12
  err?: (line: string) => void;
12
- createExecutor?: (cred: Credential, policy: Policy) => Promise<Executor> | Executor;
13
+ createExecutor?: (cred: Credential, policy: PolicyStore) => Promise<Executor> | Executor;
13
14
  kill?: typeof process.kill;
14
15
  /** Runs a system command for `service` (default: execFileSync). */
15
16
  runSystem?: (cmd: string, args: string[]) => void;
17
+ /** Standard input is a terminal (default: `process.stdin.isTTY`): a confirmation may be asked. */
18
+ stdinIsTTY?: boolean;
19
+ /** Asks one question on the terminal and resolves the answer (default: node:readline). */
20
+ ask?: (question: string) => Promise<string>;
16
21
  }
22
+ /**
23
+ * Logged when the local policy switches between auto and sandbox. It names the local choice, not
24
+ * the effective mode: the organization's ceiling still cuts it (a device whose org forbids auto
25
+ * runs in the sandbox even with this policy).
26
+ */
27
+ export declare const AUTO_MODE_ON = "This machine's local policy is auto mode; the deployment's ceiling applies.";
28
+ export declare const AUTO_MODE_OFF = "This machine's local policy is sandbox mode; commands still running in auto mode were stopped.";
17
29
  /** Runs one command line and returns the exit code. */
18
30
  export declare function runCli(argv: string[], io?: CliEnv): Promise<number>;
package/dist/cli.js CHANGED
@@ -1,28 +1,62 @@
1
1
  import { homedir } from "node:os";
2
2
  import { parseCommandLine, USAGE, UsageError } from "./args.js";
3
- import { drain } from "./commands/drain.js";
3
+ import { drain, drainAndWait } from "./commands/drain.js";
4
4
  import { login } from "./commands/login.js";
5
5
  import { logout } from "./commands/logout.js";
6
+ import { modeCommand } from "./commands/mode.js";
6
7
  import { policyCommand } from "./commands/policy.js";
7
8
  import { serviceCommand } from "./commands/service.js";
8
9
  import { start } from "./commands/start.js";
9
10
  import { status } from "./commands/status.js";
10
11
  import { stop } from "./commands/stop.js";
11
12
  import { stateDir } from "./state.js";
12
- /** The executor for the credential's mode; the program's state directory is unreadable to commands. */
13
- function defaultCreateExecutor(stateDir, home) {
14
- return async (cred, policy) => {
13
+ /** Asks one question on the process's terminal. */
14
+ async function askOnTerminal(question) {
15
+ const { createInterface } = await import("node:readline/promises");
16
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
17
+ try {
18
+ return await rl.question(question);
19
+ }
20
+ finally {
21
+ rl.close();
22
+ }
23
+ }
24
+ /**
25
+ * Logged when the local policy switches between auto and sandbox. It names the local choice, not
26
+ * the effective mode: the organization's ceiling still cuts it (a device whose org forbids auto
27
+ * runs in the sandbox even with this policy).
28
+ */
29
+ export const AUTO_MODE_ON = "This machine's local policy is auto mode; the deployment's ceiling applies.";
30
+ export const AUTO_MODE_OFF = "This machine's local policy is sandbox mode; commands still running in auto mode were stopped.";
31
+ /**
32
+ * The executor for the credential's mode; the program's state directory is unreadable to
33
+ * sandboxed commands. OS mode serves a {@link SwitchingExecutor}: the host (auto mode) or the OS
34
+ * sandbox (sandbox mode), chosen per command from the policy and the kernel's ceiling (spec §4.1).
35
+ */
36
+ function defaultCreateExecutor(stateDir, home, err) {
37
+ return async (cred, store) => {
38
+ const policy = () => store.current();
15
39
  if (cred.mode === "docker") {
16
40
  const { createDockerExecutor } = await import("./exec/docker.js");
17
41
  return createDockerExecutor({
18
42
  dir: cred.dir,
19
- environmentId: cred.environmentId,
43
+ deviceId: cred.deviceId,
20
44
  policy,
21
45
  });
22
46
  }
23
47
  // Loaded on demand: the sandbox runtime is only needed by start.
24
- const { createOsExecutor } = await import("./exec/os.js");
25
- return createOsExecutor({ dir: cred.dir, policy, home, denyRead: [stateDir] });
48
+ const [{ createOsExecutor }, { HostExecutor }, { SwitchingExecutor }] = await Promise.all([
49
+ import("./exec/os.js"),
50
+ import("./exec/host.js"),
51
+ import("./exec/switch.js"),
52
+ ]);
53
+ const sandboxed = await createOsExecutor({
54
+ dir: cred.dir,
55
+ policy,
56
+ home,
57
+ denyRead: [stateDir],
58
+ });
59
+ return new SwitchingExecutor(sandboxed, new HostExecutor({ dir: cred.dir }), policy, (mode) => err(mode === "auto" ? AUTO_MODE_ON : AUTO_MODE_OFF));
26
60
  };
27
61
  }
28
62
  /** Runs one command line and returns the exit code. */
@@ -67,18 +101,32 @@ export async function runCli(argv, io = {}) {
67
101
  return status(dir, cmd.json, out, err);
68
102
  case "start":
69
103
  return start({
104
+ service: { home, platform },
70
105
  stateDir: dir,
71
106
  out,
72
107
  err,
73
- createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home),
108
+ createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home, err),
74
109
  ...(io.kill && { kill: io.kill }),
75
110
  });
76
111
  case "stop":
77
- return stop(dir, out, err, io.kill);
112
+ return stop(dir, out, err, io.kill, { home, platform });
78
113
  case "drain":
79
- return drain(dir, out, err, io.kill);
114
+ if (cmd.wait !== true)
115
+ return drain(dir, out, err, io.kill);
116
+ return drainAndWait(dir, out, err, {
117
+ ...(io.kill && { kill: io.kill }),
118
+ ...(io.sleep && { sleep: io.sleep }),
119
+ ...(cmd.timeoutSeconds !== undefined && { timeoutMs: cmd.timeoutSeconds * 1000 }),
120
+ });
80
121
  case "policy":
81
122
  return policyCommand(cmd, { stateDir: dir, out, err });
123
+ case "mode":
124
+ return modeCommand(cmd, {
125
+ stateDir: dir,
126
+ out,
127
+ err,
128
+ ...((io.stdinIsTTY ?? process.stdin.isTTY === true) && { ask: io.ask ?? askOnTerminal }),
129
+ });
82
130
  case "service":
83
131
  return serviceCommand(cmd.action, {
84
132
  stateDir: dir,
@@ -88,6 +136,7 @@ export async function runCli(argv, io = {}) {
88
136
  out,
89
137
  err,
90
138
  ...(io.runSystem && { run: io.runSystem }),
139
+ ...(io.sleep && { sleep: io.sleep }),
91
140
  });
92
141
  }
93
142
  }