@capybara-hq/device 0.1.0-rc.16 → 0.1.0-rc.18

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 (65) hide show
  1. package/README.md +79 -0
  2. package/dist/activity.d.ts +31 -0
  3. package/dist/activity.js +62 -0
  4. package/dist/args.d.ts +18 -2
  5. package/dist/args.js +56 -8
  6. package/dist/cli.js +13 -2
  7. package/dist/commands/ceiling.js +22 -0
  8. package/dist/commands/keep-awake.d.ts +19 -0
  9. package/dist/commands/keep-awake.js +77 -0
  10. package/dist/commands/login.js +29 -16
  11. package/dist/commands/service.d.ts +3 -1
  12. package/dist/commands/service.js +35 -2
  13. package/dist/commands/start.d.ts +7 -0
  14. package/dist/commands/start.js +120 -1
  15. package/dist/commands/status.d.ts +8 -1
  16. package/dist/commands/status.js +50 -2
  17. package/dist/control/client.d.ts +12 -0
  18. package/dist/control/client.js +63 -0
  19. package/dist/control/protocol.d.ts +58 -0
  20. package/dist/control/protocol.js +16 -0
  21. package/dist/control/server.d.ts +28 -0
  22. package/dist/control/server.js +254 -0
  23. package/dist/exec/mac-operation-backend.d.ts +5 -0
  24. package/dist/exec/mac-operation-backend.js +26 -6
  25. package/dist/exec/native-helper-client.js +10 -2
  26. package/dist/exec/operation-supervisor.d.ts +30 -1
  27. package/dist/exec/operation-supervisor.js +60 -2
  28. package/dist/exec/operation-worker.js +3 -0
  29. package/dist/exec/transfer-timing.d.ts +16 -0
  30. package/dist/exec/transfer-timing.js +26 -0
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +1 -0
  33. package/dist/keep-awake.d.ts +39 -0
  34. package/dist/keep-awake.js +104 -0
  35. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.js +22 -4
  36. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/hooks.d.ts +4 -3
  37. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.d.ts +3 -1
  38. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.js +3 -1
  39. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/model.d.ts +1 -1
  40. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/permissions.js +3 -1
  41. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-capabilities.d.ts +80 -0
  42. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-capabilities.js +13 -0
  43. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-environment.d.ts +57 -0
  44. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-environment.js +16 -0
  45. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-slots.d.ts +12 -0
  46. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-slots.js +23 -0
  47. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui.d.ts +6 -1
  48. package/dist/node_modules/@capybara-hq/plugin-sdk/package.json +1 -1
  49. package/dist/runtime-manifest.json +1 -1
  50. package/dist/server-ops.d.ts +3 -0
  51. package/dist/server-ops.js +33 -0
  52. package/dist/service/launchd.d.ts +2 -0
  53. package/dist/service/launchd.js +10 -4
  54. package/dist/service/manager.d.ts +2 -0
  55. package/dist/service/manager.js +16 -2
  56. package/dist/service/systemd.d.ts +2 -0
  57. package/dist/service/systemd.js +8 -2
  58. package/dist/staged-connect.d.ts +9 -0
  59. package/dist/staged-connect.js +24 -2
  60. package/dist/staged-device.js +6 -0
  61. package/dist/state.d.ts +9 -0
  62. package/dist/state.js +9 -1
  63. package/dist/wake.d.ts +23 -0
  64. package/dist/wake.js +29 -0
  65. package/package.json +2 -2
package/README.md CHANGED
@@ -17,6 +17,12 @@ capybara-device status [--json]
17
17
  capybara-device logout
18
18
  ```
19
19
 
20
+ `login --json` is for programs that drive the CLI (the desktop app): it opens no browser and writes one
21
+ JSON object per line to stdout, the human lines going to stderr: `{"event":"verification","url":…,
22
+ "userCode":…,"expiresIn":…}`, then `{"event":"done","deviceId":…,"orgId":…,"dir":…}` or
23
+ `{"event":"error","code":…,"message":…}` (for example `device_sign_in.expired`, `device_sign_in.denied`).
24
+ It never prints the credential.
25
+
20
26
  `login` shows a code like `BCDF-GHJK`; with `--no-browser` it prints the address (`<url>/devices/link`) and
21
27
  the code to enter on any signed-in browser, where you pick the org and the device (a new one or
22
28
  an existing connected one of yours) after reading what the program can do. Logging in again from
@@ -93,6 +99,7 @@ the platform can switch Full access off on their side; the narrowest setting win
93
99
 
94
100
  ```bash
95
101
  capybara-device ceiling show # the owner ceiling, network baseline, revision
102
+ capybara-device ceiling show --json # {"fullAccess":…,"projectReach":…,"revision":…} (revision: string | null)
96
103
  capybara-device ceiling set --full-access deny --project-reach workspace # narrow
97
104
  capybara-device ceiling set --full-access allow --project-reach os-user --yes # widen
98
105
  capybara-device policy add allowedDomains files.slack.com
@@ -159,6 +166,73 @@ they left running survive the upgrade. Restart the machine, or kill such leftove
159
166
  upgrade yourself; this version never searches for them. In Docker mode the old container is
160
167
  recreated at the first operation, which ends whatever it still ran.
161
168
 
169
+ ## Control socket
170
+
171
+ While `start` serves, it answers on `<stateDir>/control.sock` (next to `credential.json`): a unix
172
+ socket of mode 0600, made only when the state directory belongs to you and has no group or other
173
+ permissions (mode 0700). A socket left by a program that crashed (nothing listens on it) is
174
+ replaced; one another running program answers on is never touched. When the path is longer than
175
+ 103 bytes (a long `XDG_CONFIG_HOME`) or the directory is open to other users, the program keeps
176
+ serving without the socket and says why once.
177
+
178
+ The protocol is JSON lines. A request is `{"id":<positive integer>,"op":"<op>"}`; each answer
179
+ carries the request's id: `{"id":1,"ok":true,"result":...}` or
180
+ `{"id":1,"ok":false,"error":{"code":"...","message":"..."}}` (`bad_request`, with id 0 for a line
181
+ without a usable id, `unknown_op`). A malformed line keeps the connection open; a line over 64 KiB,
182
+ or more than 1 MiB of answers a peer leaves unread, closes it.
183
+
184
+ | Op | Result |
185
+ |---|---|
186
+ | `status` | The live status: `pid`, `version`, `url`, `orgId`, `deviceId`, `mode` (`os` or `docker`), `connection` (`starting`, `online`, `offline` or `draining`), `offlineReason` (while offline), `since` (when `connection` last changed), `keepAwake` (`mode`, `held`, and `unavailable` with the reason when the holder cannot run), `lastWakeAt` (once the computer woke from sleep) |
187
+ | `running` | The operations executing now (an exec while it runs, a background task until it completes or is killed): `tag`, `conversationId`, `accountId`, `isolation` (`restricted` or `full`), `startedAt`; never a command's text, environment or output |
188
+ | `subscribe` | The live status now; afterwards the connection receives `{"event":"status","status":{...}}` after each change |
189
+ | `drain` | `null`; drains as `capybara-device drain` does |
190
+ | `stop` | `null`; stops as `capybara-device stop` does |
191
+
192
+ `status --json` asks the socket (for at most 500 ms) and adds:
193
+
194
+ - `control`: `ok` (the running program answered), `absent` (no program runs) or `unavailable`
195
+ (a program runs but has no socket, with the reason in `controlReason`);
196
+ - `live`: the live status above, or `null`.
197
+
198
+ The credential is never part of any answer.
199
+
200
+ ## Keep-awake
201
+
202
+ While the device serves, it can keep this computer from going to idle sleep, so a command a
203
+ conversation started is not cut off and the deployment can reach the device. `policy.json` holds
204
+ the mode in `keepAwake`:
205
+
206
+ - `off`: never;
207
+ - `while-busy` (the default): only while operations run (an exec, or a background task until it
208
+ ends);
209
+ - `connected`: the whole time the device is connected to the deployment.
210
+
211
+ ```bash
212
+ capybara-device keep-awake # show the mode (--json for one JSON object)
213
+ capybara-device keep-awake off # lower it: applies at once
214
+ capybara-device keep-awake connected --yes # raise it: asks on a terminal, needs --yes without one
215
+ ```
216
+
217
+ A running program applies a change within a few seconds, without a restart; the change is logged
218
+ in `commands.log`. The hold is a helper process: `/usr/bin/caffeinate -i -w <pid>` on macOS and
219
+ `systemd-inhibit --what=idle:sleep --mode=block --who=capybara-device --why="Capybara device is
220
+ serving" sleep infinity` on Linux. If it cannot start or ends early, the status says so
221
+ (`keepAwake.unavailable`); it is never reported as held then. The program also notices a wake from
222
+ sleep (a wall-clock jump of over 30 s): it writes `{ "op": "wake" }` to `commands.log` and sets
223
+ `lastWakeAt` in the live status.
224
+
225
+ A holder that cannot start or ends early is not started again while the same mode still wants it;
226
+ it is tried again after nothing is wanted for one check, or when the mode changes. On Linux a runner
227
+ killed with SIGKILL leaves `sleep infinity` holding the inhibitor until that process is killed (on
228
+ macOS `caffeinate -w` ends with the runner).
229
+
230
+ What this cannot prevent: closing the lid of a Mac on battery without an external display
231
+ (clamshell) still sleeps; so do choosing Sleep, a critically low battery and thermal emergencies;
232
+ on Linux, the lid switch as logind handles it (taking `handle-lid-switch` needs privileges the user
233
+ service lacks). While the computer sleeps the device's WebSocket stops, and the kernel sees a
234
+ sleeping machine as offline, as for a lost network.
235
+
162
236
  ## Docker mode
163
237
 
164
238
  `login --mode docker` runs every operation in one container per device
@@ -201,6 +275,11 @@ has the agent loaded, or systemd the unit active, and its pid is the pid file's)
201
275
  how to restart the installed service; started by the service manager (launchd sets
202
276
  `XPC_SERVICE_NAME`, systemd `INVOCATION_ID`) it prints no such hint.
203
277
 
278
+ `capybara-device service status --json` prints one object instead: `installed`, `loaded`, `running`,
279
+ `binExists` (false when the service file's `bin` path is gone, e.g. the app that installed it moved)
280
+ and, when known, `pid`, `runningVersion`, `installedVersion`, `nodePath`, `binPath`. The exit code is
281
+ the same as the human report's.
282
+
204
283
  `capybara-device service status` says one of four things: not installed; installed but not loaded
205
284
  (`service start`); loaded but the program is not running, i.e. it exited (the reason is at the end of
206
285
  `service.log`; fix it, then `service restart`); or running, with the service manager's pid and the
@@ -0,0 +1,31 @@
1
+ /**
2
+ * An operation executing on this machine now, as the control socket's `running` op lists it: who
3
+ * asked and how it runs. Never the command, its arguments, its environment or its output.
4
+ */
5
+ export interface RunningOperation {
6
+ tag: string;
7
+ conversationId: string | null;
8
+ accountId: string | null;
9
+ isolation: "restricted" | "full";
10
+ startedAt: string;
11
+ }
12
+ /**
13
+ * The operations executing in this process: an exec while it runs, a background task from its
14
+ * start until its worker is gone (completed or killed, reported by the backend). In-process by
15
+ * design: only this runner's control socket reads it, and it dies with the process whose
16
+ * operations it lists.
17
+ */
18
+ export declare class RunningOperations {
19
+ private readonly ops;
20
+ private readonly listeners;
21
+ /** Calls `fn` after every change of the list; returns how to stop. */
22
+ subscribe(fn: () => void): () => void;
23
+ private changed;
24
+ /** `operationId` lets {@link endOperation} end exactly this one. */
25
+ begin(op: RunningOperation, operationId?: string): void;
26
+ /** Ends the oldest running operation with this tag (tags may repeat); unknown tags are ignored. */
27
+ end(tag: string): void;
28
+ /** Ends the operation begun with this id; ids already ended are ignored. */
29
+ endOperation(operationId: string): void;
30
+ list(): RunningOperation[];
31
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The operations executing in this process: an exec while it runs, a background task from its
3
+ * start until its worker is gone (completed or killed, reported by the backend). In-process by
4
+ * design: only this runner's control socket reads it, and it dies with the process whose
5
+ * operations it lists.
6
+ */
7
+ export class RunningOperations {
8
+ ops = [];
9
+ listeners = new Set();
10
+ /** Calls `fn` after every change of the list; returns how to stop. */
11
+ subscribe(fn) {
12
+ this.listeners.add(fn);
13
+ return () => this.listeners.delete(fn);
14
+ }
15
+ changed() {
16
+ for (const fn of this.listeners) {
17
+ try {
18
+ fn();
19
+ }
20
+ catch {
21
+ // an observer never affects the operations
22
+ }
23
+ }
24
+ }
25
+ /** `operationId` lets {@link endOperation} end exactly this one. */
26
+ begin(op, operationId) {
27
+ // a retried start of the same operation replaces its entry instead of adding one
28
+ if (operationId !== undefined)
29
+ this.endOperation(operationId);
30
+ // copy only the known fields: whatever else the caller holds never reaches the socket
31
+ this.ops.push({
32
+ ...(operationId !== undefined && { operationId }),
33
+ op: {
34
+ tag: op.tag,
35
+ conversationId: op.conversationId,
36
+ accountId: op.accountId,
37
+ isolation: op.isolation,
38
+ startedAt: op.startedAt,
39
+ },
40
+ });
41
+ this.changed();
42
+ }
43
+ /** Ends the oldest running operation with this tag (tags may repeat); unknown tags are ignored. */
44
+ end(tag) {
45
+ const i = this.ops.findIndex((o) => o.op.tag === tag);
46
+ if (i >= 0) {
47
+ this.ops.splice(i, 1);
48
+ this.changed();
49
+ }
50
+ }
51
+ /** Ends the operation begun with this id; ids already ended are ignored. */
52
+ endOperation(operationId) {
53
+ const i = this.ops.findIndex((o) => o.operationId === operationId);
54
+ if (i >= 0) {
55
+ this.ops.splice(i, 1);
56
+ this.changed();
57
+ }
58
+ }
59
+ list() {
60
+ return this.ops.map((o) => ({ ...o.op }));
61
+ }
62
+ }
package/dist/args.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { RestrictedProjectReach } from "./state.js";
1
+ import { type KeepAwakeMode, type RestrictedProjectReach } from "./state.js";
2
2
  export type DeviceMode = "os" | "docker";
3
3
  /** A parsed command line. */
4
4
  export type Command = {
@@ -7,6 +7,8 @@ export type Command = {
7
7
  browser: boolean;
8
8
  dir?: string;
9
9
  mode: DeviceMode;
10
+ /** `--json`: one JSON event per line on stdout (implies `--no-browser`). */
11
+ json?: true;
10
12
  } | {
11
13
  command: "logout";
12
14
  } | {
@@ -33,6 +35,7 @@ export type Command = {
33
35
  } | {
34
36
  command: "ceiling";
35
37
  action: "show";
38
+ json?: true;
36
39
  } | {
37
40
  command: "ceiling";
38
41
  action: "set";
@@ -40,13 +43,26 @@ export type Command = {
40
43
  projectReach: RestrictedProjectReach;
41
44
  /** `--yes`: confirms a widening without asking. */
42
45
  yes?: true;
46
+ } | {
47
+ command: "keep-awake";
48
+ action: "show";
49
+ json?: true;
50
+ } | {
51
+ command: "keep-awake";
52
+ action: "set";
53
+ mode: KeepAwakeMode;
54
+ /** `--yes`: confirms keeping the computer awake more often without asking. */
55
+ yes?: true;
56
+ json?: true;
43
57
  } | {
44
58
  command: "service";
45
59
  action: "install" | "uninstall" | "start" | "stop" | "restart" | "status";
60
+ /** `service status --json`. */
61
+ json?: true;
46
62
  } | {
47
63
  command: "help";
48
64
  };
49
- 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 ceiling show Show this machine's owner ceiling (Full access, project reach)\n capybara-device ceiling set --full-access allow|deny --project-reach workspace|os-user [--yes]\n Set the owner ceiling; widening 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 for restricted work\n capybara-device policy add|remove allowCredentials <name>\n Allow or stop allowing a credential for restricted work\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";
65
+ export declare const USAGE = "Usage:\n capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker] [--json]\n Connect this machine: approve the code in the browser;\n --json prints one JSON event per line (no 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 ceiling show [--json]\n Show this machine's owner ceiling (Full access, project reach)\n capybara-device ceiling set --full-access allow|deny --project-reach workspace|os-user [--yes]\n Set the owner ceiling; widening needs --yes or a y at the prompt\n capybara-device keep-awake [show | off | while-busy | connected] [--yes] [--json]\n Show or set when this computer is kept awake; raising it\n 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 for restricted work\n capybara-device policy add|remove allowCredentials <name>\n Allow or stop allowing a credential for restricted work\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 [--json]\n Report whether the login service is loaded, what is running,\n and whether it is older than the installed program";
50
66
  /** Thrown for a bad command line; the message is shown with the usage. */
51
67
  export declare class UsageError extends Error {
52
68
  }
package/dist/args.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { parseArgs } from "node:util";
2
+ import { isKeepAwakeMode } from "./state.js";
2
3
  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
4
+ capybara-device login --url <url> [--no-browser] [--dir <path>] [--mode os|docker] [--json]
5
+ Connect this machine: approve the code in the browser;
6
+ --json prints one JSON event per line (no browser)
5
7
  capybara-device logout Forget the credential on this machine
6
8
  capybara-device status [--json] Show whether this machine is logged in
7
9
  capybara-device start Connect and serve the device
@@ -9,9 +11,13 @@ export const USAGE = `Usage:
9
11
  capybara-device drain [--wait] [--timeout <seconds>]
10
12
  Finish running commands, accept no new ones, then stop;
11
13
  --wait returns once it has stopped (default limit 600 s)
12
- capybara-device ceiling show Show this machine's owner ceiling (Full access, project reach)
14
+ capybara-device ceiling show [--json]
15
+ Show this machine's owner ceiling (Full access, project reach)
13
16
  capybara-device ceiling set --full-access allow|deny --project-reach workspace|os-user [--yes]
14
17
  Set the owner ceiling; widening needs --yes or a y at the prompt
18
+ capybara-device keep-awake [show | off | while-busy | connected] [--yes] [--json]
19
+ Show or set when this computer is kept awake; raising it
20
+ needs --yes or a y at the prompt
15
21
  capybara-device policy [show] Show the local policy
16
22
  capybara-device policy set <key> <value>
17
23
  Replace one field (cpu, memoryMb, allowCredentials)
@@ -23,7 +29,8 @@ export const USAGE = `Usage:
23
29
  Run at login as a user service, or remove it
24
30
  capybara-device service start|stop|restart
25
31
  Start, stop or restart the login service
26
- capybara-device service status Report whether the login service is loaded, what is running,
32
+ capybara-device service status [--json]
33
+ Report whether the login service is loaded, what is running,
27
34
  and whether it is older than the installed program`;
28
35
  /** Thrown for a bad command line; the message is shown with the usage. */
29
36
  export class UsageError extends Error {
@@ -55,6 +62,7 @@ export function parseCommandLine(argv) {
55
62
  "no-browser": { type: "boolean" },
56
63
  dir: { type: "string" },
57
64
  mode: { type: "string" },
65
+ json: { type: "boolean" },
58
66
  });
59
67
  if (positionals.length > 0)
60
68
  throw new UsageError("login takes no positional arguments");
@@ -66,9 +74,10 @@ export function parseCommandLine(argv) {
66
74
  return {
67
75
  command: "login",
68
76
  url: String(values.url),
69
- browser: values["no-browser"] !== true,
77
+ browser: values["no-browser"] !== true && values.json !== true,
70
78
  ...(values.dir !== undefined && { dir: String(values.dir) }),
71
79
  mode,
80
+ ...(values.json === true && { json: true }),
72
81
  };
73
82
  }
74
83
  case "status": {
@@ -122,6 +131,7 @@ export function parseCommandLine(argv) {
122
131
  "full-access": { type: "string" },
123
132
  "project-reach": { type: "string" },
124
133
  yes: { type: "boolean", short: "y" },
134
+ json: { type: "boolean" },
125
135
  });
126
136
  const [action, ...extra] = positionals;
127
137
  const usage = "usage: ceiling show | ceiling set --full-access allow|deny --project-reach workspace|os-user [--yes]";
@@ -130,10 +140,16 @@ export function parseCommandLine(argv) {
130
140
  if (action === "show" || action === undefined) {
131
141
  if (values["full-access"] !== undefined || values["project-reach"] !== undefined)
132
142
  throw new UsageError(usage);
133
- return { command: "ceiling", action: "show" };
143
+ return {
144
+ command: "ceiling",
145
+ action: "show",
146
+ ...(values.json === true && { json: true }),
147
+ };
134
148
  }
135
149
  if (action !== "set")
136
150
  throw new UsageError(usage);
151
+ if (values.json === true)
152
+ throw new UsageError(usage);
137
153
  const full = values["full-access"];
138
154
  const reach = values["project-reach"];
139
155
  // both fields: one explicit atomic target
@@ -149,9 +165,37 @@ export function parseCommandLine(argv) {
149
165
  ...(values.yes === true && { yes: true }),
150
166
  };
151
167
  }
168
+ case "keep-awake": {
169
+ const { values, positionals } = parse(rest, {
170
+ yes: { type: "boolean", short: "y" },
171
+ json: { type: "boolean" },
172
+ });
173
+ const usage = "usage: keep-awake [show | off | while-busy | connected] [--yes] [--json]";
174
+ const [action, ...extra] = positionals;
175
+ if (extra.length > 0)
176
+ throw new UsageError(usage);
177
+ const json = values.json === true && { json: true };
178
+ if (action === undefined || action === "show") {
179
+ if (values.yes === true)
180
+ throw new UsageError(usage);
181
+ return { command: "keep-awake", action: "show", ...json };
182
+ }
183
+ if (!isKeepAwakeMode(action))
184
+ throw new UsageError(usage);
185
+ return {
186
+ command: "keep-awake",
187
+ action: "set",
188
+ mode: action,
189
+ ...(values.yes === true && { yes: true }),
190
+ ...json,
191
+ };
192
+ }
152
193
  case "service": {
153
- const { positionals } = parse(rest, {});
194
+ const { values, positionals } = parse(rest, { json: { type: "boolean" } });
154
195
  const [action, ...extra] = positionals;
196
+ if (values.json === true && action !== "status") {
197
+ throw new UsageError("--json is only for service status");
198
+ }
155
199
  if ((action === "install" ||
156
200
  action === "uninstall" ||
157
201
  action === "start" ||
@@ -159,7 +203,11 @@ export function parseCommandLine(argv) {
159
203
  action === "restart" ||
160
204
  action === "status") &&
161
205
  extra.length === 0) {
162
- return { command: "service", action };
206
+ return {
207
+ command: "service",
208
+ action,
209
+ ...(values.json === true && { json: true }),
210
+ };
163
211
  }
164
212
  throw new UsageError("usage: service install|uninstall|start|stop|restart|status");
165
213
  }
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@ import { homedir } from "node:os";
2
2
  import { parseCommandLine, USAGE, UsageError } from "./args.js";
3
3
  import { ceilingCommand } from "./commands/ceiling.js";
4
4
  import { drain, drainAndWait } from "./commands/drain.js";
5
+ import { keepAwakeCommand } from "./commands/keep-awake.js";
5
6
  import { login } from "./commands/login.js";
6
7
  import { logout } from "./commands/logout.js";
7
8
  import { policyCommand } from "./commands/policy.js";
@@ -86,7 +87,10 @@ export async function runCli(argv, io = {}) {
86
87
  ...(io.ps && { ps: io.ps }),
87
88
  });
88
89
  case "status":
89
- return status(dir, cmd.json, out, err);
90
+ return status(dir, cmd.json, out, err, {
91
+ ...(io.kill && { kill: io.kill }),
92
+ ...(io.ps && { ps: io.ps }),
93
+ });
90
94
  case "start":
91
95
  return start({
92
96
  service: { home, platform },
@@ -129,6 +133,13 @@ export async function runCli(argv, io = {}) {
129
133
  ...((io.stdinIsTTY ?? process.stdin.isTTY === true) && { ask: io.ask ?? askOnTerminal }),
130
134
  ...(io.beforeCeilingWrite && { beforeWrite: io.beforeCeilingWrite }),
131
135
  });
136
+ case "keep-awake":
137
+ return keepAwakeCommand(cmd, {
138
+ stateDir: dir,
139
+ out,
140
+ err,
141
+ ...((io.stdinIsTTY ?? process.stdin.isTTY === true) && { ask: io.ask ?? askOnTerminal }),
142
+ });
132
143
  case "service":
133
144
  return serviceCommand(cmd.action, {
134
145
  stateDir: dir,
@@ -141,6 +152,6 @@ export async function runCli(argv, io = {}) {
141
152
  ...(io.sleep && { sleep: io.sleep }),
142
153
  ...(io.kill && { kill: io.kill }),
143
154
  ...(io.ps && { ps: io.ps }),
144
- });
155
+ }, { json: cmd.json === true });
145
156
  }
146
157
  }
@@ -9,6 +9,19 @@ export const CEILING_WIDENING_TEXT = "Widening this machine's owner ceiling lets
9
9
  "projects outside the device's workspace. Conversations need fresh Full consent either way.";
10
10
  export const CEILING_NEEDS_YES = "Nothing changed. To widen the owner ceiling, add --yes (or answer y at the prompt).";
11
11
  export const CEILING_PROMPT = "Widen this machine's owner ceiling? [y/N] ";
12
+ /** The strict reader's revision for the logged-in device, or null (logged out, unreadable). */
13
+ function strictRevision(stateDir, home) {
14
+ try {
15
+ const cred = readCredential(stateDir);
16
+ if (cred === undefined)
17
+ return null;
18
+ return readStrictOwnerCeilingSync({ stateDir, deviceId: cred.deviceId, dir: cred.dir, home })
19
+ .revision;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
12
25
  /** Thrown inside the locked update when the policy now on disk makes the target a widening. */
13
26
  class WideningNeedsConfirmation extends Error {
14
27
  }
@@ -38,6 +51,15 @@ export async function ceilingCommand(cmd, deps) {
38
51
  return 1;
39
52
  }
40
53
  const cur = store.current();
54
+ if (cmd.action === "show" && cmd.json === true) {
55
+ out(JSON.stringify({
56
+ fullAccess: cur.ownerCeiling.fullAccess,
57
+ projectReach: cur.ownerCeiling.restrictedProjectReach,
58
+ // the strict reader's digest of the policy generation; null while logged out
59
+ revision: strictRevision(stateDir, deps.home),
60
+ }));
61
+ return 0;
62
+ }
41
63
  if (cmd.action === "show") {
42
64
  for (const line of describe(cur.ownerCeiling))
43
65
  out(line);
@@ -0,0 +1,19 @@
1
+ import type { Command } from "../args.js";
2
+ export declare const KEEP_AWAKE_PROMPT = "Keep this computer awake more often? [y/N] ";
3
+ export declare const KEEP_AWAKE_NEEDS_YES = "Nothing changed. To keep this computer awake more often, add --yes (or answer y at the prompt).";
4
+ /** What keep-awake cannot prevent (spec §9.7), printed with the mode. */
5
+ export declare const KEEP_AWAKE_LIMITS: string;
6
+ export interface KeepAwakeDeps {
7
+ stateDir: string;
8
+ out: (line: string) => void;
9
+ err: (line: string) => void;
10
+ ask?: (question: string) => Promise<string>;
11
+ }
12
+ /**
13
+ * `keep-awake show` prints the mode; `keep-awake off|while-busy|connected` writes it under the
14
+ * policy lock. Lowering applies directly; raising needs --yes or a confirmed terminal answer. A
15
+ * running program applies the change without a restart.
16
+ */
17
+ export declare function keepAwakeCommand(cmd: Extract<Command, {
18
+ command: "keep-awake";
19
+ }>, deps: KeepAwakeDeps): Promise<number>;
@@ -0,0 +1,77 @@
1
+ import { noteCliPolicyChange } from "../command-log.js";
2
+ import { PolicyStore } from "../policy-store.js";
3
+ import { KEEP_AWAKE_MODES, policyPath } from "../state.js";
4
+ export const KEEP_AWAKE_PROMPT = "Keep this computer awake more often? [y/N] ";
5
+ export const KEEP_AWAKE_NEEDS_YES = "Nothing changed. To keep this computer awake more often, add --yes (or answer y at the prompt).";
6
+ /** What keep-awake cannot prevent (spec §9.7), printed with the mode. */
7
+ export const KEEP_AWAKE_LIMITS = "Keep-awake cannot prevent sleep when the lid of a Mac on battery is closed without an " +
8
+ "external display, when Sleep is chosen, at a critically low battery or in a thermal " +
9
+ "emergency, nor (on Linux) the lid switch. A sleeping computer is offline for the deployment.";
10
+ const RAISE_TEXT = "While the device is connected or busy, this computer will not go to idle sleep; it uses more " +
11
+ "power and a laptop in a bag can get warm.";
12
+ const rank = (m) => KEEP_AWAKE_MODES.indexOf(m);
13
+ class RaiseNeedsConfirmation extends Error {
14
+ }
15
+ /**
16
+ * `keep-awake show` prints the mode; `keep-awake off|while-busy|connected` writes it under the
17
+ * policy lock. Lowering applies directly; raising needs --yes or a confirmed terminal answer. A
18
+ * running program applies the change without a restart.
19
+ */
20
+ export async function keepAwakeCommand(cmd, deps) {
21
+ const { stateDir, out, err } = deps;
22
+ let store;
23
+ try {
24
+ store = new PolicyStore(stateDir);
25
+ }
26
+ catch (e) {
27
+ err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
28
+ return 1;
29
+ }
30
+ const cur = store.current().keepAwake;
31
+ if (cmd.action === "show") {
32
+ if (cmd.json === true)
33
+ out(JSON.stringify({ keepAwake: cur }));
34
+ else {
35
+ out(`Keep-awake: ${cur}`);
36
+ out(KEEP_AWAKE_LIMITS);
37
+ }
38
+ return 0;
39
+ }
40
+ const next = cmd.mode;
41
+ let confirmed = cmd.yes === true;
42
+ if (rank(next) > rank(cur)) {
43
+ out(RAISE_TEXT);
44
+ if (!confirmed) {
45
+ if (deps.ask === undefined) {
46
+ err(KEEP_AWAKE_NEEDS_YES);
47
+ return 2;
48
+ }
49
+ const answer = (await deps.ask(KEEP_AWAKE_PROMPT)).trim().toLowerCase();
50
+ if (answer !== "y" && answer !== "yes") {
51
+ err("Nothing changed.");
52
+ return 1;
53
+ }
54
+ confirmed = true;
55
+ }
56
+ }
57
+ try {
58
+ // decided again on the policy under the lock: a lowering that landed since the read above
59
+ // makes this a raise, which needs its own confirmation
60
+ store.update((p) => {
61
+ if (!confirmed && rank(next) > rank(p.keepAwake))
62
+ throw new RaiseNeedsConfirmation();
63
+ return { ...p, keepAwake: next };
64
+ });
65
+ }
66
+ catch (e) {
67
+ if (e instanceof RaiseNeedsConfirmation) {
68
+ err(`The keep-awake mode changed meanwhile. ${KEEP_AWAKE_NEEDS_YES}`);
69
+ return 2;
70
+ }
71
+ err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
72
+ return 1;
73
+ }
74
+ noteCliPolicyChange(stateDir, `keep-awake set ${next}`);
75
+ out(cmd.json === true ? JSON.stringify({ keepAwake: next }) : `Keep-awake is now: ${next}`);
76
+ return 0;
77
+ }
@@ -91,8 +91,21 @@ export function normalizeUrl(raw) {
91
91
  }
92
92
  /** `login`: the device authorization flow. Returns the exit code. */
93
93
  export async function login(cmd, deps) {
94
- const out = deps.out ?? ((l) => console.log(l));
94
+ const stdout = deps.out ?? ((l) => console.log(l));
95
95
  const err = deps.err ?? ((l) => console.error(l));
96
+ const json = cmd.json === true;
97
+ // With --json stdout carries only JSON events; the human lines go to stderr.
98
+ const out = json ? err : stdout;
99
+ const emit = (event) => {
100
+ if (json)
101
+ stdout(JSON.stringify(event));
102
+ };
103
+ /** A failed login: the human line, plus the JSON error event. */
104
+ const fail = (code, message, exit) => {
105
+ err(message);
106
+ emit({ event: "error", code, message });
107
+ return exit;
108
+ };
96
109
  const fetchFn = deps.fetch ?? fetch;
97
110
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
98
111
  const platform = deps.platform ?? process.platform;
@@ -102,17 +115,14 @@ export async function login(cmd, deps) {
102
115
  baseUrl = normalizeUrl(cmd.url);
103
116
  }
104
117
  catch (e) {
105
- err(e.message);
106
- return 2;
118
+ return fail("invalid_url", e.message, 2);
107
119
  }
108
120
  if (platform !== "darwin" && platform !== "linux") {
109
- err("capybara-device runs on macOS and Linux. On Windows use WSL or Docker.");
110
- return 1;
121
+ return fail("unsupported_platform", "capybara-device runs on macOS and Linux. On Windows use WSL or Docker.", 1);
111
122
  }
112
123
  try {
113
124
  if (readCredential(deps.stateDir) !== undefined) {
114
- err("This machine is already logged in. Run `capybara-device logout` first.");
115
- return 1;
125
+ return fail("already_logged_in", "This machine is already logged in. Run `capybara-device logout` first.", 1);
116
126
  }
117
127
  }
118
128
  catch (e) {
@@ -126,7 +136,13 @@ export async function login(cmd, deps) {
126
136
  programVersion: programVersion(),
127
137
  });
128
138
  out(`Open ${auth.verificationUriComplete} and confirm the code ${auth.userCode}`);
129
- if (cmd.browser)
139
+ emit({
140
+ event: "verification",
141
+ url: auth.verificationUriComplete,
142
+ userCode: auth.userCode,
143
+ expiresIn: auth.expiresIn,
144
+ });
145
+ if (cmd.browser && !json)
130
146
  (deps.openBrowser ?? defaultOpen(platform))(auth.verificationUriComplete);
131
147
  let interval = Number.isFinite(auth.interval) && auth.interval >= 1 ? auth.interval : 5;
132
148
  const expiresIn = Number.isFinite(auth.expiresIn) && auth.expiresIn > 0 ? auth.expiresIn : 600;
@@ -189,6 +205,7 @@ export async function login(cmd, deps) {
189
205
  reconnectGraceSeconds: granted.reconnectGraceSeconds,
190
206
  maxFrameBytes: granted.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES,
191
207
  });
208
+ emit({ event: "done", deviceId: granted.deviceId, orgId: granted.orgId, dir });
192
209
  out(`Logged in. Device ${granted.deviceId}, working directory ${dir}`);
193
210
  if (ceiling.fullAccess) {
194
211
  out(FULL_CEILING_LOGIN_LINE);
@@ -222,24 +239,20 @@ export async function login(cmd, deps) {
222
239
  // Keep polling at the normal interval: pending, a network blip or a server error.
223
240
  }
224
241
  else if (e.code === "device_sign_in.expired") {
225
- err("The code expired before it was approved. Run `capybara-device login` again.");
226
- return 1;
242
+ return fail("device_sign_in.expired", "The code expired before it was approved. Run `capybara-device login` again.", 1);
227
243
  }
228
244
  else if (e.code === "device_sign_in.denied") {
229
- err("The login was denied in the browser.");
230
- return 1;
245
+ return fail("device_sign_in.denied", "The login was denied in the browser.", 1);
231
246
  }
232
247
  else
233
248
  throw e;
234
249
  if (waited >= expiresIn) {
235
- err("The code expired before it was approved. Run `capybara-device login` again.");
236
- return 1;
250
+ return fail("device_sign_in.expired", "The code expired before it was approved. Run `capybara-device login` again.", 1);
237
251
  }
238
252
  }
239
253
  }
240
254
  }
241
255
  catch (e) {
242
- err(`login failed: ${e.message}`);
243
- return 1;
256
+ return fail(e instanceof ApiError ? e.code : "login_failed", `login failed: ${e.message}`, 1);
244
257
  }
245
258
  }