@capybara-hq/device 0.0.0-stage → 0.1.0-rc.0

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 (61) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +103 -2
  4. package/bin/capybara-device.mjs +11 -0
  5. package/dist/api.d.ts +33 -0
  6. package/dist/api.js +48 -0
  7. package/dist/args.d.ts +39 -0
  8. package/dist/args.js +93 -0
  9. package/dist/cli.d.ts +18 -0
  10. package/dist/cli.js +93 -0
  11. package/dist/client.d.ts +39 -0
  12. package/dist/client.js +340 -0
  13. package/dist/command-log.d.ts +17 -0
  14. package/dist/command-log.js +28 -0
  15. package/dist/commands/drain.d.ts +2 -0
  16. package/dist/commands/drain.js +5 -0
  17. package/dist/commands/login.d.ts +20 -0
  18. package/dist/commands/login.js +132 -0
  19. package/dist/commands/logout.d.ts +13 -0
  20. package/dist/commands/logout.js +36 -0
  21. package/dist/commands/policy.d.ts +15 -0
  22. package/dist/commands/policy.js +74 -0
  23. package/dist/commands/service.d.ts +17 -0
  24. package/dist/commands/service.js +97 -0
  25. package/dist/commands/signal.d.ts +2 -0
  26. package/dist/commands/signal.js +18 -0
  27. package/dist/commands/start.d.ts +16 -0
  28. package/dist/commands/start.js +73 -0
  29. package/dist/commands/status.d.ts +2 -0
  30. package/dist/commands/status.js +32 -0
  31. package/dist/commands/stop.d.ts +2 -0
  32. package/dist/commands/stop.js +5 -0
  33. package/dist/exec/docker.d.ts +120 -0
  34. package/dist/exec/docker.js +673 -0
  35. package/dist/exec/fs-helper.d.ts +12 -0
  36. package/dist/exec/fs-helper.js +85 -0
  37. package/dist/exec/os.d.ts +80 -0
  38. package/dist/exec/os.js +398 -0
  39. package/dist/exec/procs.d.ts +11 -0
  40. package/dist/exec/procs.js +67 -0
  41. package/dist/exec/shared.d.ts +71 -0
  42. package/dist/exec/shared.js +240 -0
  43. package/dist/exec/types.d.ts +34 -0
  44. package/dist/exec/types.js +9 -0
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.js +3 -0
  47. package/dist/pid.d.ts +6 -0
  48. package/dist/pid.js +36 -0
  49. package/dist/policy.d.ts +42 -0
  50. package/dist/policy.js +97 -0
  51. package/dist/server-ops.d.ts +10 -0
  52. package/dist/server-ops.js +74 -0
  53. package/dist/service/launchd.d.ts +17 -0
  54. package/dist/service/launchd.js +59 -0
  55. package/dist/service/systemd.d.ts +5 -0
  56. package/dist/service/systemd.js +28 -0
  57. package/dist/state.d.ts +40 -0
  58. package/dist/state.js +117 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +11 -0
  61. package/package.json +42 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Capybara
2
+ Copyright 2026 Meta-1 (Tianjin Yuanyilian Technology Co., Ltd.)
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @capybara-hq/device
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
6
+
7
+ Runs on macOS and Linux. Native Windows is refused: use WSL (then it is a Linux machine) or Docker
8
+ mode inside WSL. Node 22.12 or newer.
9
+
10
+ ```bash
11
+ npm i -g @capybara-hq/device
12
+ capybara-device login --url https://capybara.example.com # approve in the browser
13
+ capybara-device login --url https://capybara.example.com --no-browser # headless: prints a code
14
+ capybara-device start # connect and serve commands (runs in the foreground)
15
+ capybara-device status [--json]
16
+ capybara-device logout
17
+ ```
18
+
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
21
+ 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
+ `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
26
+ revokes the machine and stops the program; the files in the working directory stay on your machine.
27
+
28
+ The deployment must route `/device/connect` on its public URL to the gateway role (see
29
+ [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.
32
+
33
+ `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.
38
+
39
+ If the working directory (or its marker `.capybara-device`, or one of `workspace/`, `skills/`,
40
+ `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.
44
+
45
+ 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`.
48
+
49
+ State lives in `$XDG_CONFIG_HOME/capybara-device` (default `~/.config/capybara-device`):
50
+ `credential.json` (mode 0600; the program refuses a file other users can read; it also holds the
51
+ deployment's reconnect grace and frame limit: a result larger than the frame limit is answered
52
+ 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/`
55
+ and `tmp/`.
56
+
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:
63
+
64
+ ```bash
65
+ capybara-device policy set allowedDomains registry.npmjs.org,*.github.com
66
+ capybara-device policy show # changes apply at the next start
67
+ ```
68
+
69
+ Limits to know: the platform's `Grep` tool assumes GNU grep, so on macOS (BSD grep) in OS mode some
70
+ Grep options behave differently or fail. Docker mode (a Linux container) does not have this issue.
71
+
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).
77
+
78
+ ## Docker mode
79
+
80
+ `login --mode docker` runs every command with `docker exec` in one container per environment
81
+ (`capybara-device-<environmentId>`, started on first use from
82
+ `ghcr.io/capybara-hq/capybara-sandbox:<tag>`, the sandbox image of this release). On Linux commands
83
+ run as your own uid:gid, so they can write the mounted directories you own (a root user falls back to
84
+ 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
+ at `/workspace`, `/skills` and `/tmp`; the container has a read-only root file system, a pids limit of 1024, `--memory-swap` equal to
86
+ `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.
89
+
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.
93
+
94
+ ## Running at login
95
+
96
+ `capybara-device service install` makes the program start at login: on macOS a launchd agent
97
+ (`~/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
101
+ while you have a session, so run `loginctl enable-linger $USER` to start it at boot and keep it
102
+ running after you log out. `service.log` is emptied into `service.log.1` at 10 MiB when the program
103
+ 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.
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // The `capybara-device` bin: runs the compiled CLI (dist/cli.js, built by `tsc -b`).
3
+ import { existsSync } from "node:fs";
4
+
5
+ const dist = new URL("../dist/cli.js", import.meta.url);
6
+ if (!existsSync(dist)) {
7
+ process.stderr.write("capybara-device: dist/cli.js not found; build the package first\n");
8
+ process.exit(1);
9
+ }
10
+ const { runCli } = await import(dist.href);
11
+ process.exitCode = await runCli(process.argv.slice(2));
package/dist/api.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ export interface AuthorizeResponse {
2
+ deviceCode: string;
3
+ userCode: string;
4
+ verificationUri: string;
5
+ verificationUriComplete: string;
6
+ interval: number;
7
+ expiresIn: number;
8
+ }
9
+ export interface TokenResponse {
10
+ credential: string;
11
+ orgId: string;
12
+ environmentId: string;
13
+ connectUrl: string;
14
+ reconnectGraceSeconds: number;
15
+ /** The program uses 16 MiB when it is absent. */
16
+ maxFrameBytes?: number;
17
+ }
18
+ /** An error response of the kernel: `{ error: { code, message } }`. */
19
+ export declare class ApiError extends Error {
20
+ readonly code: string;
21
+ readonly status: number;
22
+ constructor(code: string, message: string, status: number);
23
+ }
24
+ export type FetchFn = typeof fetch;
25
+ /** The version in this package's package.json (src/ and dist/ are both one level below it). */
26
+ export declare function programVersion(): string;
27
+ export declare function authorize(fetchFn: FetchFn, baseUrl: string, body: {
28
+ name: string;
29
+ os: "darwin" | "linux";
30
+ arch: string;
31
+ programVersion: string;
32
+ }): Promise<AuthorizeResponse>;
33
+ export declare function token(fetchFn: FetchFn, baseUrl: string, deviceCode: string): Promise<TokenResponse>;
package/dist/api.js ADDED
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from "node:fs";
2
+ /** An error response of the kernel: `{ error: { code, message } }`. */
3
+ export class ApiError extends Error {
4
+ code;
5
+ status;
6
+ constructor(code, message, status) {
7
+ super(message);
8
+ this.code = code;
9
+ this.status = status;
10
+ }
11
+ }
12
+ /** The version in this package's package.json (src/ and dist/ are both one level below it). */
13
+ export function programVersion() {
14
+ const file = new URL("../package.json", import.meta.url);
15
+ return JSON.parse(readFileSync(file, "utf8")).version;
16
+ }
17
+ async function post(fetchFn, url, body) {
18
+ let res;
19
+ try {
20
+ res = await fetchFn(url, {
21
+ method: "POST",
22
+ headers: { "content-type": "application/json", "x-capybara-csrf": "1" },
23
+ body: JSON.stringify(body),
24
+ });
25
+ }
26
+ catch (e) {
27
+ throw new ApiError("network", `cannot reach ${url}: ${e.message}`, 0);
28
+ }
29
+ const text = await res.text();
30
+ let json;
31
+ try {
32
+ json = text === "" ? undefined : JSON.parse(text);
33
+ }
34
+ catch {
35
+ json = undefined;
36
+ }
37
+ if (!res.ok) {
38
+ const err = json?.error;
39
+ throw new ApiError(typeof err?.code === "string" ? err.code : `http_${res.status}`, typeof err?.message === "string" ? err.message : `${url} answered ${res.status}`, res.status);
40
+ }
41
+ return json;
42
+ }
43
+ export function authorize(fetchFn, baseUrl, body) {
44
+ return post(fetchFn, `${baseUrl}/api/v1/device/authorize`, body);
45
+ }
46
+ export function token(fetchFn, baseUrl, deviceCode) {
47
+ return post(fetchFn, `${baseUrl}/api/v1/device/token`, { deviceCode });
48
+ }
package/dist/args.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ export type DeviceMode = "os" | "docker";
2
+ /** A parsed command line. */
3
+ export type Command = {
4
+ command: "login";
5
+ url: string;
6
+ browser: boolean;
7
+ dir?: string;
8
+ mode: DeviceMode;
9
+ } | {
10
+ command: "logout";
11
+ } | {
12
+ command: "status";
13
+ json: boolean;
14
+ } | {
15
+ command: "start";
16
+ } | {
17
+ command: "stop";
18
+ } | {
19
+ command: "drain";
20
+ } | {
21
+ command: "policy";
22
+ action: "show";
23
+ } | {
24
+ command: "policy";
25
+ action: "set";
26
+ key: string;
27
+ value: string;
28
+ } | {
29
+ command: "service";
30
+ action: "install" | "uninstall";
31
+ } | {
32
+ command: "help";
33
+ };
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";
35
+ /** Thrown for a bad command line; the message is shown with the usage. */
36
+ export declare class UsageError extends Error {
37
+ }
38
+ /** Parses `argv` (without the node and script entries); throws {@link UsageError}. */
39
+ export declare function parseCommandLine(argv: string[]): Command;
package/dist/args.js ADDED
@@ -0,0 +1,93 @@
1
+ import { parseArgs } from "node:util";
2
+ export const USAGE = `Usage:
3
+ capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker]
4
+ Connect this machine: approve the code in the browser
5
+ capybara-device logout Forget the credential on this machine
6
+ capybara-device status [--json] Show whether this machine is logged in
7
+ capybara-device start Connect and serve the environment
8
+ capybara-device stop Stop the running program
9
+ capybara-device drain Finish running commands, accept no new ones, then stop
10
+ capybara-device policy [show] Show the local policy
11
+ capybara-device policy set <key> <value>
12
+ capybara-device service install|uninstall
13
+ Run at login as a user service`;
14
+ /** Thrown for a bad command line; the message is shown with the usage. */
15
+ export class UsageError extends Error {
16
+ }
17
+ function parse(argv, options) {
18
+ try {
19
+ return parseArgs({ args: argv, options, allowPositionals: true, strict: true });
20
+ }
21
+ catch (e) {
22
+ throw new UsageError(e.message);
23
+ }
24
+ }
25
+ /** Parses `argv` (without the node and script entries); throws {@link UsageError}. */
26
+ export function parseCommandLine(argv) {
27
+ const [name, ...rest] = argv;
28
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
29
+ return { command: "help" };
30
+ }
31
+ const noArgs = (command) => {
32
+ const { positionals } = parse(rest, {});
33
+ if (positionals.length > 0)
34
+ throw new UsageError(`${command} takes no arguments`);
35
+ return { command };
36
+ };
37
+ switch (name) {
38
+ case "login": {
39
+ const { values, positionals } = parse(rest, {
40
+ url: { type: "string" },
41
+ "no-browser": { type: "boolean" },
42
+ dir: { type: "string" },
43
+ mode: { type: "string" },
44
+ });
45
+ if (positionals.length > 0)
46
+ throw new UsageError("login takes no positional arguments");
47
+ if (values.url === undefined || values.url === "")
48
+ throw new UsageError("login needs --url");
49
+ const mode = values.mode ?? "os";
50
+ if (mode !== "os" && mode !== "docker")
51
+ throw new UsageError("--mode must be os or docker");
52
+ return {
53
+ command: "login",
54
+ url: String(values.url),
55
+ browser: values["no-browser"] !== true,
56
+ ...(values.dir !== undefined && { dir: String(values.dir) }),
57
+ mode,
58
+ };
59
+ }
60
+ case "status": {
61
+ const { values, positionals } = parse(rest, { json: { type: "boolean" } });
62
+ if (positionals.length > 0)
63
+ throw new UsageError("status takes no arguments");
64
+ return { command: "status", json: values.json === true };
65
+ }
66
+ case "logout":
67
+ case "start":
68
+ case "stop":
69
+ case "drain":
70
+ return noArgs(name);
71
+ case "policy": {
72
+ const { positionals } = parse(rest, {});
73
+ const [action, key, value, ...extra] = positionals;
74
+ if (action === undefined || (action === "show" && key === undefined && extra.length === 0)) {
75
+ return { command: "policy", action: "show" };
76
+ }
77
+ if (action === "set" && key !== undefined && value !== undefined && extra.length === 0) {
78
+ return { command: "policy", action: "set", key, value };
79
+ }
80
+ throw new UsageError("usage: policy [show | set <key> <value>]");
81
+ }
82
+ case "service": {
83
+ const { positionals } = parse(rest, {});
84
+ const [action, ...extra] = positionals;
85
+ if ((action === "install" || action === "uninstall") && extra.length === 0) {
86
+ return { command: "service", action };
87
+ }
88
+ throw new UsageError("usage: service install|uninstall");
89
+ }
90
+ default:
91
+ throw new UsageError(`unknown command ${name}`);
92
+ }
93
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { Executor } from "./exec/types.js";
2
+ import { type Credential, type Policy } from "./state.js";
3
+ export interface CliEnv {
4
+ env?: Record<string, string | undefined>;
5
+ home?: string;
6
+ platform?: NodeJS.Platform;
7
+ fetch?: typeof fetch;
8
+ sleep?: (ms: number) => Promise<void>;
9
+ openBrowser?: (url: string) => void;
10
+ out?: (line: string) => void;
11
+ err?: (line: string) => void;
12
+ createExecutor?: (cred: Credential, policy: Policy) => Promise<Executor> | Executor;
13
+ kill?: typeof process.kill;
14
+ /** Runs a system command for `service` (default: execFileSync). */
15
+ runSystem?: (cmd: string, args: string[]) => void;
16
+ }
17
+ /** Runs one command line and returns the exit code. */
18
+ export declare function runCli(argv: string[], io?: CliEnv): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,93 @@
1
+ import { homedir } from "node:os";
2
+ import { parseCommandLine, USAGE, UsageError } from "./args.js";
3
+ import { drain } from "./commands/drain.js";
4
+ import { login } from "./commands/login.js";
5
+ import { logout } from "./commands/logout.js";
6
+ import { policyCommand } from "./commands/policy.js";
7
+ import { serviceCommand } from "./commands/service.js";
8
+ import { start } from "./commands/start.js";
9
+ import { status } from "./commands/status.js";
10
+ import { stop } from "./commands/stop.js";
11
+ 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) => {
15
+ if (cred.mode === "docker") {
16
+ const { createDockerExecutor } = await import("./exec/docker.js");
17
+ return createDockerExecutor({
18
+ dir: cred.dir,
19
+ environmentId: cred.environmentId,
20
+ policy,
21
+ });
22
+ }
23
+ // 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] });
26
+ };
27
+ }
28
+ /** Runs one command line and returns the exit code. */
29
+ export async function runCli(argv, io = {}) {
30
+ const out = io.out ?? ((l) => console.log(l));
31
+ const err = io.err ?? ((l) => console.error(l));
32
+ const platform = io.platform ?? process.platform;
33
+ if (platform !== "darwin" && platform !== "linux") {
34
+ err("capybara-device runs on macOS and Linux. On Windows use WSL or Docker.");
35
+ return 1;
36
+ }
37
+ let cmd;
38
+ try {
39
+ cmd = parseCommandLine(argv);
40
+ }
41
+ catch (e) {
42
+ if (!(e instanceof UsageError))
43
+ throw e;
44
+ err(`${e.message}\n${USAGE}`);
45
+ return 2;
46
+ }
47
+ const home = io.home ?? homedir();
48
+ const dir = stateDir(io.env ?? process.env, home);
49
+ switch (cmd.command) {
50
+ case "help":
51
+ out(USAGE);
52
+ return 0;
53
+ case "login":
54
+ return login(cmd, {
55
+ stateDir: dir,
56
+ home,
57
+ platform,
58
+ out,
59
+ err,
60
+ ...(io.fetch && { fetch: io.fetch }),
61
+ ...(io.sleep && { sleep: io.sleep }),
62
+ ...(io.openBrowser && { openBrowser: io.openBrowser }),
63
+ });
64
+ case "logout":
65
+ return logout(dir, { out, err, ...(io.kill && { kill: io.kill }) });
66
+ case "status":
67
+ return status(dir, cmd.json, out, err);
68
+ case "start":
69
+ return start({
70
+ stateDir: dir,
71
+ out,
72
+ err,
73
+ createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home),
74
+ ...(io.kill && { kill: io.kill }),
75
+ });
76
+ case "stop":
77
+ return stop(dir, out, err, io.kill);
78
+ case "drain":
79
+ return drain(dir, out, err, io.kill);
80
+ case "policy":
81
+ return policyCommand(cmd, { stateDir: dir, out, err });
82
+ case "service":
83
+ return serviceCommand(cmd.action, {
84
+ stateDir: dir,
85
+ home,
86
+ platform,
87
+ env: io.env ?? process.env,
88
+ out,
89
+ err,
90
+ ...(io.runSystem && { run: io.runSystem }),
91
+ });
92
+ }
93
+ }