@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
@@ -36,4 +36,6 @@ export declare const BOOTSTRAP_BACKOFF_MS: readonly [500, 1000, 2000];
36
36
  * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
37
37
  * (systemd user), removes it, or reports whether it is loaded and running.
38
38
  */
39
- export declare function serviceCommand(action: ServiceAction, deps: ServiceDeps): Promise<number>;
39
+ export declare function serviceCommand(action: ServiceAction, deps: ServiceDeps, options?: {
40
+ json?: boolean;
41
+ }): Promise<number>;
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { readRunning } from "../pid.js";
5
5
  import { hasLoginService } from "../service/installed.js";
6
6
  import { plistContent, plistPath } from "../service/launchd.js";
7
- import { defaultRunSystem, launchdTarget, managerState, packageVersionAt, serviceBinPath, } from "../service/manager.js";
7
+ import { defaultRunSystem, launchdTarget, managerState, packageVersionAt, serviceBinPath, serviceNodePath, } from "../service/manager.js";
8
8
  import { SYSTEMD_UNIT, unitContent, unitPath } from "../service/systemd.js";
9
9
  /** The bin script next to this package's `dist` (or `src`) directory. */
10
10
  function defaultBinPath() {
@@ -32,7 +32,7 @@ export const BOOTSTRAP_BACKOFF_MS = [500, 1000, 2000];
32
32
  * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
33
33
  * (systemd user), removes it, or reports whether it is loaded and running.
34
34
  */
35
- export async function serviceCommand(action, deps) {
35
+ export async function serviceCommand(action, deps, options = {}) {
36
36
  const run = deps.run ?? defaultRunSystem;
37
37
  const spec = {
38
38
  nodePath: deps.nodePath ?? process.execPath,
@@ -41,6 +41,11 @@ export async function serviceCommand(action, deps) {
41
41
  env: serviceEnv(deps.env),
42
42
  };
43
43
  try {
44
+ const jsonStatus = action === "status" && options.json === true;
45
+ if (deps.platform === "darwin" || deps.platform === "linux") {
46
+ if (jsonStatus)
47
+ return statusJson(deps, run);
48
+ }
44
49
  if (deps.platform === "darwin")
45
50
  return await launchd(action, spec, deps, run);
46
51
  if (deps.platform === "linux")
@@ -114,6 +119,34 @@ function reportStatus(deps, run) {
114
119
  }
115
120
  return 0;
116
121
  }
122
+ /**
123
+ * `service status --json`: one object on stdout, the same facts as the human report. Exit code 0
124
+ * only when running, like the human report. `binExists` is false when the service file's `bin`
125
+ * path is gone (the app that installed it moved).
126
+ */
127
+ function statusJson(deps, run) {
128
+ const at = where(deps);
129
+ const installed = hasLoginService(at.home, at.platform);
130
+ const state = installed ? managerState(at, run) : { loaded: false };
131
+ const pid = "pid" in state ? state.pid : undefined;
132
+ const bin = installed ? serviceBinPath(at) : undefined;
133
+ const program = pid === undefined ? undefined : running(deps);
134
+ const runningVersion = program?.pid === pid ? program?.version : undefined;
135
+ const installedVersion = bin === undefined ? undefined : packageVersionAt(bin);
136
+ const nodePath = installed ? serviceNodePath(at) : undefined;
137
+ deps.out(JSON.stringify({
138
+ installed,
139
+ loaded: state.loaded,
140
+ running: pid !== undefined,
141
+ ...(pid !== undefined && { pid }),
142
+ ...(runningVersion !== undefined && { runningVersion }),
143
+ ...(installedVersion !== undefined && { installedVersion }),
144
+ ...(nodePath !== undefined && { nodePath }),
145
+ ...(bin !== undefined && { binPath: bin }),
146
+ binExists: bin !== undefined && existsSync(bin),
147
+ }));
148
+ return pid !== undefined ? 0 : 1;
149
+ }
117
150
  /**
118
151
  * Refuses to start the service while a program started outside it runs (`capybara-device start`
119
152
  * in a terminal): two programs would fight over the one connection of this device.
@@ -1,8 +1,10 @@
1
+ import type { spawn } from "node:child_process";
1
2
  import { type ProcessLookup } from "../pid.js";
2
3
  import { PolicyStore } from "../policy-store.js";
3
4
  import { connectStaged } from "../staged-connect.js";
4
5
  import type { StagedDevice } from "../staged-device.js";
5
6
  import { type Credential } from "../state.js";
7
+ import { WakeDetector } from "../wake.js";
6
8
  export interface StartDeps {
7
9
  stateDir: string;
8
10
  out: (line: string) => void;
@@ -24,6 +26,11 @@ export interface StartDeps {
24
26
  */
25
27
  createStaged?: (cred: Credential, policy: PolicyStore) => Promise<StagedDevice> | StagedDevice;
26
28
  connectStaged?: typeof connectStaged;
29
+ /** Test seams for keep-awake: the holder's spawn, the wake detector and the check period. */
30
+ keepAwakeSpawn?: typeof spawn;
31
+ wake?: WakeDetector;
32
+ /** How often the policy is re-read and a wake is looked for (default 2 s). */
33
+ tickMs?: number;
27
34
  }
28
35
  /** Printed once when start converted an old-format policy.json to version 2. */
29
36
  export declare function legacyPolicyNotice(mode: "auto" | "sandbox"): string;
@@ -1,12 +1,16 @@
1
1
  import { homedir } from "node:os";
2
+ import { CommandLog } from "../command-log.js";
3
+ import { startControlServer } from "../control/server.js";
4
+ import { KeepAwake } from "../keep-awake.js";
2
5
  import { readRunningPid, removePid, writePid } from "../pid.js";
3
6
  import { PolicyStore } from "../policy-store.js";
4
7
  import { hasLoginService } from "../service/installed.js";
5
8
  import { rotateServiceLog } from "../service/launchd.js";
6
9
  import { startedByServiceManager } from "../service/manager.js";
7
10
  import { connectStaged } from "../staged-connect.js";
8
- import { convertPolicyFile, policyMode, readCredential } from "../state.js";
11
+ import { convertPolicyFile, DEFAULT_POLICY, policyMode, readCredential, readPolicy, } from "../state.js";
9
12
  import { PROGRAM_VERSION } from "../version.js";
13
+ import { WakeDetector } from "../wake.js";
10
14
  /** Printed once when start converted an old-format policy.json to version 2. */
11
15
  export function legacyPolicyNotice(mode) {
12
16
  return ("policy.json now uses the version 2 owner ceiling; this machine runs in " +
@@ -55,29 +59,142 @@ export async function start(deps) {
55
59
  let conn;
56
60
  let stopRequested = false;
57
61
  let drainRequested = false;
62
+ let device;
63
+ // the live status the control socket answers: built from the credential, then followed through
64
+ // the connection's state changes (never the credential itself)
65
+ const keepAwake = new KeepAwake({
66
+ platform: where.platform,
67
+ pid: proc.pid,
68
+ ...(deps.keepAwakeSpawn && { spawn: deps.keepAwakeSpawn }),
69
+ });
70
+ const wake = deps.wake ?? new WakeDetector();
71
+ let mode = (() => {
72
+ try {
73
+ return readPolicy(stateDir).keepAwake;
74
+ }
75
+ catch {
76
+ return DEFAULT_POLICY.keepAwake;
77
+ }
78
+ })();
79
+ let live = {
80
+ pid: proc.pid,
81
+ version: PROGRAM_VERSION,
82
+ url: cred.url,
83
+ orgId: cred.orgId,
84
+ deviceId: cred.deviceId,
85
+ mode: cred.mode,
86
+ connection: "starting",
87
+ since: new Date().toISOString(),
88
+ keepAwake: { mode, held: false },
89
+ };
90
+ let publish = () => { };
91
+ const setState = (s) => {
92
+ if (live.connection === "draining" && s.connection !== "draining")
93
+ return;
94
+ const { offlineReason: _old, ...rest } = live;
95
+ const next = {
96
+ ...rest,
97
+ connection: s.connection,
98
+ ...(s.connection === "offline" && s.reason !== undefined && { offlineReason: s.reason }),
99
+ since: s.connection === live.connection ? live.since : new Date().toISOString(),
100
+ };
101
+ const changed = JSON.stringify(next) !== JSON.stringify(live);
102
+ live = next;
103
+ refresh(changed);
104
+ };
105
+ /**
106
+ * Applies keep-awake for the state now (policy mode, connection, running operations) and follows
107
+ * it in the live status; publishes when the status changed (or `changed` says it did).
108
+ */
109
+ const refresh = (changed = false) => {
110
+ keepAwake.update({
111
+ mode,
112
+ connected: live.connection === "online",
113
+ busy: (device?.owner?.running?.list().length ?? 0) > 0,
114
+ });
115
+ const { unavailable, ...held } = keepAwake.state();
116
+ const next = {
117
+ ...live,
118
+ keepAwake: { ...held, ...(unavailable !== undefined && { unavailable }) },
119
+ };
120
+ const moved = changed || JSON.stringify(next) !== JSON.stringify(live);
121
+ live = next;
122
+ if (moved)
123
+ publish(live);
124
+ };
125
+ const tick = () => {
126
+ try {
127
+ // a change made with `keep-awake` applies here, without a restart; an unreadable file keeps
128
+ // the mode in force
129
+ mode = device?.owner?.store.current().keepAwake ?? readPolicy(stateDir).keepAwake;
130
+ }
131
+ catch {
132
+ // keep the last mode
133
+ }
134
+ const woke = wake.check();
135
+ if (woke !== undefined) {
136
+ live = { ...live, lastWakeAt: woke };
137
+ (device?.owner?.log ?? new CommandLog(stateDir)).append({
138
+ time: woke,
139
+ op: "wake",
140
+ tag: null,
141
+ actor: null,
142
+ exitCode: null,
143
+ });
144
+ refresh(true);
145
+ }
146
+ else
147
+ refresh();
148
+ };
58
149
  const onStop = () => {
59
150
  stopRequested = true;
60
151
  conn?.stop();
61
152
  };
62
153
  const onDrain = () => {
154
+ if (drainRequested)
155
+ return;
63
156
  drainRequested = true;
157
+ setState({ connection: "draining" });
64
158
  out("Draining: no new commands; stopping when the running ones finish.");
65
159
  conn?.drain();
66
160
  };
161
+ const ticker = setInterval(tick, deps.tickMs ?? 2000);
162
+ ticker.unref();
67
163
  proc.on("SIGTERM", onStop);
68
164
  proc.on("SIGINT", onStop);
69
165
  proc.on("SIGUSR2", onDrain);
70
166
  writePid(stateDir, proc.pid, PROGRAM_VERSION);
167
+ // the local control socket (decision 3): a path it cannot use leaves the program serving
168
+ const control = await startControlServer({
169
+ stateDir,
170
+ status: () => live,
171
+ running: () => device?.owner?.running?.list() ?? [],
172
+ drain: onDrain,
173
+ stop: onStop,
174
+ }).catch((e) => ({ unavailable: e.message }));
175
+ if ("unavailable" in control)
176
+ err(`capybara-device: control socket unavailable: ${control.unavailable}`);
177
+ else
178
+ publish = (s) => control.publish(s);
71
179
  try {
72
180
  return await serveStaged(deps, cred, {
73
181
  stopRequested: () => stopRequested,
74
182
  drainRequested: () => drainRequested,
183
+ built: (d) => {
184
+ device = d;
185
+ d.owner?.running?.subscribe(() => refresh());
186
+ },
75
187
  connected: (c) => {
76
188
  conn = c;
77
189
  },
190
+ onState: setState,
78
191
  });
79
192
  }
80
193
  finally {
194
+ clearInterval(ticker);
195
+ keepAwake.dispose();
196
+ if (!("unavailable" in control))
197
+ await control.close();
81
198
  proc.off("SIGTERM", onStop);
82
199
  proc.off("SIGINT", onStop);
83
200
  proc.off("SIGUSR2", onDrain);
@@ -103,6 +220,7 @@ async function serveStaged(deps, cred, signals) {
103
220
  err(`Cannot start: ${e.message}`);
104
221
  return 1;
105
222
  }
223
+ signals.built(device);
106
224
  try {
107
225
  // a persisted binding of this credential comes back for same-generation journal recovery
108
226
  await device.binder.recover();
@@ -118,6 +236,7 @@ async function serveStaged(deps, cred, signals) {
118
236
  }
119
237
  const conn = (deps.connectStaged ?? connectStaged)(device, {
120
238
  err,
239
+ onState: signals.onState,
121
240
  // read before each reconnect only: a new login while running discards the old credential's
122
241
  // state (B-3)
123
242
  credential: () => {
@@ -1,2 +1,9 @@
1
+ import { type ProcessChecks } from "../pid.js";
2
+ /** How long `status` waits for the running program to answer on its control socket. */
3
+ export declare const STATUS_CONTROL_TIMEOUT_MS = 500;
4
+ export interface StatusOptions extends ProcessChecks {
5
+ /** The running program's pid, if any (default: the pid file, checked against the process). */
6
+ running?: () => number | undefined;
7
+ }
1
8
  /** `status`: exit 0 when logged in, 1 when not (or the credential file is unusable). */
2
- export declare function status(stateDir: string, json: boolean, out: (line: string) => void, err: (line: string) => void): number;
9
+ export declare function status(stateDir: string, json: boolean, out: (line: string) => void, err: (line: string) => void, opts?: StatusOptions): Promise<number>;
@@ -1,6 +1,43 @@
1
+ import { queryControl } from "../control/client.js";
2
+ import { controlUnavailableReason } from "../control/server.js";
3
+ import { readRunningPid } from "../pid.js";
1
4
  import { policyMode, readCredential, readPolicy } from "../state.js";
5
+ /** How long `status` waits for the running program to answer on its control socket. */
6
+ export const STATUS_CONTROL_TIMEOUT_MS = 500;
7
+ /** A light shape check of the runner's answer before it is printed. */
8
+ function isLiveStatus(v) {
9
+ if (v === null || typeof v !== "object")
10
+ return false;
11
+ const s = v;
12
+ return (typeof s.pid === "number" &&
13
+ typeof s.connection === "string" &&
14
+ typeof s.deviceId === "string" &&
15
+ typeof s.since === "string");
16
+ }
17
+ async function controlState(stateDir, opts) {
18
+ let answer;
19
+ try {
20
+ answer = await queryControl(stateDir, "status", STATUS_CONTROL_TIMEOUT_MS);
21
+ }
22
+ catch (e) {
23
+ return { control: "unavailable", controlReason: e.message, live: null };
24
+ }
25
+ if (isLiveStatus(answer))
26
+ return { control: "ok", live: answer };
27
+ // an answer of another shape is treated as no answer
28
+ const pid = (opts.running ?? (() => readRunningPid(stateDir, opts)))();
29
+ if (pid === undefined)
30
+ return { control: "absent", live: null };
31
+ // a program runs but does not answer: say why when it is visible from here (decision 3)
32
+ return {
33
+ control: "unavailable",
34
+ controlReason: controlUnavailableReason(stateDir) ??
35
+ `the running program (pid ${pid}) does not answer on its control socket`,
36
+ live: null,
37
+ };
38
+ }
2
39
  /** `status`: exit 0 when logged in, 1 when not (or the credential file is unusable). */
3
- export function status(stateDir, json, out, err) {
40
+ export async function status(stateDir, json, out, err, opts = {}) {
4
41
  let cred;
5
42
  try {
6
43
  cred = readCredential(stateDir);
@@ -23,8 +60,9 @@ export function status(stateDir, json, out, err) {
23
60
  }
24
61
  // The credential itself is never printed.
25
62
  const { credential: _secret, ...shown } = cred;
63
+ const control = await controlState(stateDir, opts);
26
64
  if (json) {
27
- out(JSON.stringify({ loggedIn: true, ...shown, ...(sandboxMode && { sandboxMode }) }));
65
+ out(JSON.stringify({ loggedIn: true, ...shown, ...(sandboxMode && { sandboxMode }), ...control }));
28
66
  }
29
67
  else {
30
68
  out([
@@ -34,7 +72,17 @@ export function status(stateDir, json, out, err) {
34
72
  ` device: ${cred.deviceId}`,
35
73
  ` directory: ${cred.dir}`,
36
74
  ` mode: ${cred.mode} | ${sandboxMode ?? "unknown"}`,
75
+ ` running: ${runningLine(control)}`,
37
76
  ].join("\n"));
38
77
  }
39
78
  return 0;
40
79
  }
80
+ function runningLine(c) {
81
+ if (c.control === "absent")
82
+ return "no";
83
+ if (c.control === "unavailable")
84
+ return `yes (no live status: ${c.controlReason})`;
85
+ const l = c.live;
86
+ const reason = l.offlineReason === undefined ? "" : `: ${l.offlineReason}`;
87
+ return `yes, pid ${l.pid}, ${l.connection}${reason} since ${l.since}`;
88
+ }
@@ -0,0 +1,12 @@
1
+ import { type ControlRequest } from "./protocol.js";
2
+ /** The answer of one control error: the runner answered, but refused the op. */
3
+ export declare class ControlError extends Error {
4
+ readonly code: string;
5
+ constructor(code: string, message: string);
6
+ }
7
+ /**
8
+ * Asks the running program one op over its control socket and answers the result; `undefined`
9
+ * when no runner answers (no socket, nothing listening, or no answer within `timeoutMs`). Throws
10
+ * {@link ControlError} when the runner answered `ok: false`. Only a socket of this user is asked.
11
+ */
12
+ export declare function queryControl(stateDir: string, op: ControlRequest["op"], timeoutMs?: number): Promise<unknown | undefined>;
@@ -0,0 +1,63 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { createConnection } from "node:net";
3
+ import { controlSocketPath } from "./protocol.js";
4
+ /** The answer of one control error: the runner answered, but refused the op. */
5
+ export class ControlError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ }
11
+ }
12
+ /**
13
+ * Asks the running program one op over its control socket and answers the result; `undefined`
14
+ * when no runner answers (no socket, nothing listening, or no answer within `timeoutMs`). Throws
15
+ * {@link ControlError} when the runner answered `ok: false`. Only a socket of this user is asked.
16
+ */
17
+ export async function queryControl(stateDir, op, timeoutMs = 500) {
18
+ const path = controlSocketPath(stateDir);
19
+ try {
20
+ const st = lstatSync(path);
21
+ const uid = process.getuid?.();
22
+ if (!st.isSocket() || (uid !== undefined && st.uid !== uid))
23
+ return undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ return new Promise((resolve, reject) => {
29
+ const sock = createConnection(path);
30
+ let buf = "";
31
+ const finish = (settle) => {
32
+ clearTimeout(timer);
33
+ sock.destroy();
34
+ settle();
35
+ };
36
+ const timer = setTimeout(() => finish(() => resolve(undefined)), timeoutMs);
37
+ sock.setEncoding("utf8");
38
+ sock.once("error", () => finish(() => resolve(undefined)));
39
+ sock.once("close", () => finish(() => resolve(undefined)));
40
+ sock.once("connect", () => sock.write(`${JSON.stringify({ id: 1, op })}\n`));
41
+ sock.on("data", (chunk) => {
42
+ buf += chunk;
43
+ for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
44
+ const line = buf.slice(0, i);
45
+ buf = buf.slice(i + 1);
46
+ let msg;
47
+ try {
48
+ msg = JSON.parse(line);
49
+ }
50
+ catch {
51
+ continue;
52
+ }
53
+ // events and answers to other ids are not ours
54
+ if (msg.id !== 1)
55
+ continue;
56
+ if (msg.ok === true)
57
+ return finish(() => resolve(msg.result));
58
+ const error = msg.error;
59
+ return finish(() => reject(new ControlError(String(error?.code ?? "failed"), String(error?.message ?? ""))));
60
+ }
61
+ });
62
+ });
63
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The local control socket of a running `capybara-device` (JSON lines over a unix socket, mode
3
+ * 0600, in the owner-only state directory): what the desktop app and `status` ask the runner.
4
+ */
5
+ /** The longest socket path this program binds: macOS `sun_path` holds 104 bytes with its NUL. */
6
+ export declare const CONTROL_PATH_MAX_BYTES = 103;
7
+ /** The longest line a peer may send; a longer one ends that connection. */
8
+ export declare const CONTROL_LINE_MAX_BYTES: number;
9
+ /** The most unread answer bytes a connection may queue; past it the connection is closed. */
10
+ export declare const CONTROL_WRITE_MAX_BYTES: number;
11
+ /** `<stateDir>/control.sock`. */
12
+ export declare function controlSocketPath(stateDir: string): string;
13
+ export declare const CONTROL_OPS: readonly ["status", "running", "subscribe", "drain", "stop"];
14
+ /** One request line. `id` is the peer's own (a positive integer); the answer carries it back. */
15
+ export type ControlRequest = {
16
+ id: number;
17
+ op: "status" | "running" | "subscribe" | "drain" | "stop";
18
+ };
19
+ /** One answer line. A line without a usable id is answered with id 0. */
20
+ export type ControlResponse = {
21
+ id: number;
22
+ ok: true;
23
+ result: unknown;
24
+ } | {
25
+ id: number;
26
+ ok: false;
27
+ error: {
28
+ code: string;
29
+ message: string;
30
+ };
31
+ };
32
+ /** A line pushed to a connection that subscribed, after each status change. */
33
+ export type ControlEvent = {
34
+ event: "status";
35
+ status: LiveStatus;
36
+ };
37
+ /** The runner's state now. Never the credential. */
38
+ export interface LiveStatus {
39
+ pid: number;
40
+ version: string;
41
+ url: string;
42
+ orgId: string;
43
+ deviceId: string;
44
+ mode: "os" | "docker";
45
+ connection: "starting" | "online" | "offline" | "draining";
46
+ /** Why it is offline (the last connection failure), only while offline. */
47
+ offlineReason?: string;
48
+ /** When `connection` last changed (ISO 8601). */
49
+ since: string;
50
+ /** Keep-awake now: the policy mode, whether the assertion is held, why it cannot be. */
51
+ keepAwake: {
52
+ mode: "off" | "while-busy" | "connected";
53
+ held: boolean;
54
+ unavailable?: string;
55
+ };
56
+ /** When this program last noticed the computer woke from sleep (ISO 8601), once it did. */
57
+ lastWakeAt?: string;
58
+ }
@@ -0,0 +1,16 @@
1
+ import { join } from "node:path";
2
+ /**
3
+ * The local control socket of a running `capybara-device` (JSON lines over a unix socket, mode
4
+ * 0600, in the owner-only state directory): what the desktop app and `status` ask the runner.
5
+ */
6
+ /** The longest socket path this program binds: macOS `sun_path` holds 104 bytes with its NUL. */
7
+ export const CONTROL_PATH_MAX_BYTES = 103;
8
+ /** The longest line a peer may send; a longer one ends that connection. */
9
+ export const CONTROL_LINE_MAX_BYTES = 64 * 1024;
10
+ /** The most unread answer bytes a connection may queue; past it the connection is closed. */
11
+ export const CONTROL_WRITE_MAX_BYTES = 1024 * 1024;
12
+ /** `<stateDir>/control.sock`. */
13
+ export function controlSocketPath(stateDir) {
14
+ return join(stateDir, "control.sock");
15
+ }
16
+ export const CONTROL_OPS = ["status", "running", "subscribe", "drain", "stop"];
@@ -0,0 +1,28 @@
1
+ import type { RunningOperation } from "../activity.js";
2
+ import { type LiveStatus } from "./protocol.js";
3
+ export interface ControlServerOptions {
4
+ stateDir: string;
5
+ status(): LiveStatus;
6
+ running(): RunningOperation[];
7
+ drain(): void;
8
+ stop(): void;
9
+ }
10
+ export interface ControlServer {
11
+ close(): Promise<void>;
12
+ /** Pushes a status event to every connection that subscribed. */
13
+ publish(s: LiveStatus): void;
14
+ }
15
+ /**
16
+ * Why no control socket can be made for this state directory, from what is visible without
17
+ * binding: a path over {@link CONTROL_PATH_MAX_BYTES}, or a state directory that is missing, not
18
+ * the user's or open to other users (the same owner and mode rule the credential file follows).
19
+ * Undefined when nothing is in the way. `status` uses it to explain a runner that does not answer.
20
+ */
21
+ export declare function controlUnavailableReason(stateDir: string): string | undefined;
22
+ /**
23
+ * Starts the control socket at `<stateDir>/control.sock` (mode 0600). Answers `{ unavailable }`
24
+ * with the reason instead when the socket cannot be made safely; the runner keeps serving then.
25
+ */
26
+ export declare function startControlServer(opts: ControlServerOptions): Promise<ControlServer | {
27
+ unavailable: string;
28
+ }>;