@capybara-hq/device 0.1.0-rc.17 → 0.1.0-rc.19

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 (107) hide show
  1. package/README.md +143 -32
  2. package/dist/activity.d.ts +31 -0
  3. package/dist/activity.js +62 -0
  4. package/dist/api.d.ts +3 -3
  5. package/dist/args.d.ts +25 -4
  6. package/dist/args.js +82 -21
  7. package/dist/cli.js +14 -3
  8. package/dist/client.js +1 -1
  9. package/dist/commands/ceiling.d.ts +3 -2
  10. package/dist/commands/ceiling.js +60 -20
  11. package/dist/commands/keep-awake.d.ts +19 -0
  12. package/dist/commands/keep-awake.js +77 -0
  13. package/dist/commands/login.d.ts +15 -11
  14. package/dist/commands/login.js +75 -49
  15. package/dist/commands/policy.js +16 -10
  16. package/dist/commands/service.d.ts +3 -1
  17. package/dist/commands/service.js +35 -2
  18. package/dist/commands/start.d.ts +18 -3
  19. package/dist/commands/start.js +144 -9
  20. package/dist/commands/status.d.ts +8 -1
  21. package/dist/commands/status.js +59 -7
  22. package/dist/control/client.d.ts +12 -0
  23. package/dist/control/client.js +63 -0
  24. package/dist/control/protocol.d.ts +58 -0
  25. package/dist/control/protocol.js +16 -0
  26. package/dist/control/server.d.ts +28 -0
  27. package/dist/control/server.js +254 -0
  28. package/dist/exec/docker-operations.d.ts +14 -2
  29. package/dist/exec/docker-operations.js +32 -5
  30. package/dist/exec/linux-agent.d.ts +13 -3
  31. package/dist/exec/linux-agent.js +450 -43
  32. package/dist/exec/linux-operation-backend.d.ts +27 -6
  33. package/dist/exec/linux-operation-backend.js +30 -9
  34. package/dist/exec/linux-operation-worker.d.ts +51 -3
  35. package/dist/exec/linux-operation-worker.js +55 -3
  36. package/dist/exec/linux-runtime.d.ts +3 -2
  37. package/dist/exec/linux-runtime.js +4 -2
  38. package/dist/exec/mac-operation-backend.d.ts +12 -2
  39. package/dist/exec/mac-operation-backend.js +19 -10
  40. package/dist/exec/mac-write-policy.d.ts +2 -0
  41. package/dist/exec/mac-write-policy.js +1 -1
  42. package/dist/exec/operation-supervisor.d.ts +6 -0
  43. package/dist/exec/operation-supervisor.js +10 -0
  44. package/dist/exec/operation-types.d.ts +35 -5
  45. package/dist/exec/operation-types.js +73 -23
  46. package/dist/exec/operation-worker.d.ts +80 -1
  47. package/dist/exec/operation-worker.js +197 -14
  48. package/dist/exec/protected-targets.d.ts +16 -0
  49. package/dist/exec/protected-targets.js +53 -0
  50. package/dist/exec/shared.d.ts +7 -3
  51. package/dist/exec/shared.js +7 -5
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.js +1 -0
  54. package/dist/keep-awake.d.ts +39 -0
  55. package/dist/keep-awake.js +104 -0
  56. package/dist/node_modules/@anthropic-ai/sandbox-runtime/CAPYBARA-MODIFICATIONS.patch +343 -7
  57. package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/resolved-address-guard.js +220 -6
  58. package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js +17 -0
  59. package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js +11 -0
  60. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.d.ts +77 -46
  61. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.js +206 -83
  62. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.d.ts +5 -2
  63. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.js +5 -2
  64. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/network-classes.d.ts +98 -0
  65. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/network-classes.js +291 -0
  66. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/permissions.js +3 -1
  67. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-linux-runtime-source.js +460 -28
  68. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-native-runtime-source.js +143 -3
  69. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.d.ts +36 -4
  70. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.js +21 -4
  71. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-runtime-source.js +2 -2
  72. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-write-denies.d.ts +87 -8
  73. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-write-denies.js +249 -10
  74. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox.d.ts +11 -22
  75. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-capabilities.d.ts +80 -0
  76. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-capabilities.js +13 -0
  77. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-environment.d.ts +57 -0
  78. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/shell-environment.js +16 -0
  79. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-slots.d.ts +12 -0
  80. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-slots.js +23 -0
  81. package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui.d.ts +6 -1
  82. package/dist/node_modules/@capybara-hq/plugin-sdk/package.json +1 -1
  83. package/dist/owner-report.d.ts +1 -1
  84. package/dist/owner-report.js +5 -4
  85. package/dist/policy-store.d.ts +2 -1
  86. package/dist/policy-store.js +2 -1
  87. package/dist/policy.d.ts +23 -14
  88. package/dist/policy.js +28 -21
  89. package/dist/runtime-manifest.json +1 -1
  90. package/dist/server-ops.d.ts +33 -5
  91. package/dist/server-ops.js +138 -85
  92. package/dist/service/launchd.d.ts +2 -0
  93. package/dist/service/launchd.js +10 -4
  94. package/dist/service/manager.d.ts +2 -0
  95. package/dist/service/manager.js +16 -2
  96. package/dist/service/systemd.d.ts +2 -0
  97. package/dist/service/systemd.js +8 -2
  98. package/dist/staged-connect.d.ts +10 -1
  99. package/dist/staged-connect.js +25 -3
  100. package/dist/staged-device.d.ts +1 -1
  101. package/dist/staged-device.js +13 -5
  102. package/dist/staged-session.d.ts +1 -1
  103. package/dist/state.d.ts +50 -21
  104. package/dist/state.js +111 -46
  105. package/dist/wake.d.ts +23 -0
  106. package/dist/wake.js +29 -0
  107. package/package.json +2 -2
@@ -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
- import { type Credential } from "../state.js";
6
+ import { type Credential, type OwnerCeilingPolicy } 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,8 +26,21 @@ 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
- /** Printed once when start converted an old-format policy.json to version 2. */
29
- export declare function legacyPolicyNotice(mode: "auto" | "sandbox"): string;
35
+ /**
36
+ * Printed once when start converted an old-format policy.json to version 3 (never wider). A device
37
+ * that kept the allowlist learns how to open the network.
38
+ */
39
+ export declare function legacyPolicyNotice(ceiling: OwnerCeilingPolicy): string;
40
+ /**
41
+ * Printed once when start found no policy.json (a device set up before rc.58, whose `login` wrote
42
+ * none) and wrote the closed ceiling it already ran with.
43
+ */
44
+ export declare const MISSING_POLICY_NOTICE: string;
30
45
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
31
46
  export declare function start(deps: StartDeps): Promise<number>;
@@ -1,17 +1,35 @@
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, readCredential, readPolicy, } from "../state.js";
9
12
  import { PROGRAM_VERSION } from "../version.js";
10
- /** Printed once when start converted an old-format policy.json to version 2. */
11
- export function legacyPolicyNotice(mode) {
12
- return ("policy.json now uses the version 2 owner ceiling; this machine runs in " +
13
- `${mode} mode; see \`capybara-device ceiling show\`.`);
13
+ import { WakeDetector } from "../wake.js";
14
+ /**
15
+ * Printed once when start converted an old-format policy.json to version 3 (never wider). A device
16
+ * that kept the allowlist learns how to open the network.
17
+ */
18
+ export function legacyPolicyNotice(ceiling) {
19
+ return ("policy.json now uses the version 3 owner ceiling: commands run in the sandbox under every " +
20
+ `profile; outside the sandbox ${ceiling.outsideSandbox ? "on" : "off"}, network ` +
21
+ `${ceiling.network}; see \`capybara-device ceiling show\`.` +
22
+ (ceiling.network === "allowlist"
23
+ ? " To open the sandbox network: capybara-device ceiling set --network open"
24
+ : ""));
14
25
  }
26
+ /**
27
+ * Printed once when start found no policy.json (a device set up before rc.58, whose `login` wrote
28
+ * none) and wrote the closed ceiling it already ran with.
29
+ */
30
+ export const MISSING_POLICY_NOTICE = "policy.json was missing, so this machine keeps the sandbox it had: no network host allowed and " +
31
+ "no running outside the sandbox (written to policy.json). To open the sandbox network: " +
32
+ "capybara-device ceiling set --network open";
15
33
  /** `start`: connect and serve in the foreground until stopped, drained, revoked or replaced. */
16
34
  export async function start(deps) {
17
35
  const { stateDir, out, err } = deps;
@@ -55,29 +73,142 @@ export async function start(deps) {
55
73
  let conn;
56
74
  let stopRequested = false;
57
75
  let drainRequested = false;
76
+ let device;
77
+ // the live status the control socket answers: built from the credential, then followed through
78
+ // the connection's state changes (never the credential itself)
79
+ const keepAwake = new KeepAwake({
80
+ platform: where.platform,
81
+ pid: proc.pid,
82
+ ...(deps.keepAwakeSpawn && { spawn: deps.keepAwakeSpawn }),
83
+ });
84
+ const wake = deps.wake ?? new WakeDetector();
85
+ let mode = (() => {
86
+ try {
87
+ return readPolicy(stateDir).keepAwake;
88
+ }
89
+ catch {
90
+ return DEFAULT_POLICY.keepAwake;
91
+ }
92
+ })();
93
+ let live = {
94
+ pid: proc.pid,
95
+ version: PROGRAM_VERSION,
96
+ url: cred.url,
97
+ orgId: cred.orgId,
98
+ deviceId: cred.deviceId,
99
+ mode: cred.mode,
100
+ connection: "starting",
101
+ since: new Date().toISOString(),
102
+ keepAwake: { mode, held: false },
103
+ };
104
+ let publish = () => { };
105
+ const setState = (s) => {
106
+ if (live.connection === "draining" && s.connection !== "draining")
107
+ return;
108
+ const { offlineReason: _old, ...rest } = live;
109
+ const next = {
110
+ ...rest,
111
+ connection: s.connection,
112
+ ...(s.connection === "offline" && s.reason !== undefined && { offlineReason: s.reason }),
113
+ since: s.connection === live.connection ? live.since : new Date().toISOString(),
114
+ };
115
+ const changed = JSON.stringify(next) !== JSON.stringify(live);
116
+ live = next;
117
+ refresh(changed);
118
+ };
119
+ /**
120
+ * Applies keep-awake for the state now (policy mode, connection, running operations) and follows
121
+ * it in the live status; publishes when the status changed (or `changed` says it did).
122
+ */
123
+ const refresh = (changed = false) => {
124
+ keepAwake.update({
125
+ mode,
126
+ connected: live.connection === "online",
127
+ busy: (device?.owner?.running?.list().length ?? 0) > 0,
128
+ });
129
+ const { unavailable, ...held } = keepAwake.state();
130
+ const next = {
131
+ ...live,
132
+ keepAwake: { ...held, ...(unavailable !== undefined && { unavailable }) },
133
+ };
134
+ const moved = changed || JSON.stringify(next) !== JSON.stringify(live);
135
+ live = next;
136
+ if (moved)
137
+ publish(live);
138
+ };
139
+ const tick = () => {
140
+ try {
141
+ // a change made with `keep-awake` applies here, without a restart; an unreadable file keeps
142
+ // the mode in force
143
+ mode = device?.owner?.store.current().keepAwake ?? readPolicy(stateDir).keepAwake;
144
+ }
145
+ catch {
146
+ // keep the last mode
147
+ }
148
+ const woke = wake.check();
149
+ if (woke !== undefined) {
150
+ live = { ...live, lastWakeAt: woke };
151
+ (device?.owner?.log ?? new CommandLog(stateDir)).append({
152
+ time: woke,
153
+ op: "wake",
154
+ tag: null,
155
+ actor: null,
156
+ exitCode: null,
157
+ });
158
+ refresh(true);
159
+ }
160
+ else
161
+ refresh();
162
+ };
58
163
  const onStop = () => {
59
164
  stopRequested = true;
60
165
  conn?.stop();
61
166
  };
62
167
  const onDrain = () => {
168
+ if (drainRequested)
169
+ return;
63
170
  drainRequested = true;
171
+ setState({ connection: "draining" });
64
172
  out("Draining: no new commands; stopping when the running ones finish.");
65
173
  conn?.drain();
66
174
  };
175
+ const ticker = setInterval(tick, deps.tickMs ?? 2000);
176
+ ticker.unref();
67
177
  proc.on("SIGTERM", onStop);
68
178
  proc.on("SIGINT", onStop);
69
179
  proc.on("SIGUSR2", onDrain);
70
180
  writePid(stateDir, proc.pid, PROGRAM_VERSION);
181
+ // the local control socket (decision 3): a path it cannot use leaves the program serving
182
+ const control = await startControlServer({
183
+ stateDir,
184
+ status: () => live,
185
+ running: () => device?.owner?.running?.list() ?? [],
186
+ drain: onDrain,
187
+ stop: onStop,
188
+ }).catch((e) => ({ unavailable: e.message }));
189
+ if ("unavailable" in control)
190
+ err(`capybara-device: control socket unavailable: ${control.unavailable}`);
191
+ else
192
+ publish = (s) => control.publish(s);
71
193
  try {
72
194
  return await serveStaged(deps, cred, {
73
195
  stopRequested: () => stopRequested,
74
196
  drainRequested: () => drainRequested,
197
+ built: (d) => {
198
+ device = d;
199
+ d.owner?.running?.subscribe(() => refresh());
200
+ },
75
201
  connected: (c) => {
76
202
  conn = c;
77
203
  },
204
+ onState: setState,
78
205
  });
79
206
  }
80
207
  finally {
208
+ clearInterval(ticker);
209
+ keepAwake.dispose();
210
+ if (!("unavailable" in control))
211
+ await control.close();
81
212
  proc.off("SIGTERM", onStop);
82
213
  proc.off("SIGINT", onStop);
83
214
  proc.off("SIGUSR2", onDrain);
@@ -85,7 +216,7 @@ export async function start(deps) {
85
216
  }
86
217
  }
87
218
  /**
88
- * The start proper (device protocol 3): the policy store, the program's parts (binder,
219
+ * The start proper (device protocol 4): the policy store, the program's parts (binder,
89
220
  * per-generation backends, per-credential session state), recovery of a persisted binding, then
90
221
  * {@link connectStaged}.
91
222
  */
@@ -93,16 +224,19 @@ async function serveStaged(deps, cred, signals) {
93
224
  const { stateDir, out, err } = deps;
94
225
  let device;
95
226
  try {
96
- const converted = convertPolicyFile(stateDir) === "converted";
227
+ const conversion = convertPolicyFile(stateDir);
97
228
  const policy = new PolicyStore(stateDir);
98
- if (converted)
99
- out(legacyPolicyNotice(policyMode(policy.current())));
229
+ if (conversion === "converted")
230
+ out(legacyPolicyNotice(policy.current().ownerCeiling));
231
+ if (conversion === "created")
232
+ out(MISSING_POLICY_NOTICE);
100
233
  device = await deps.createStaged(cred, policy);
101
234
  }
102
235
  catch (e) {
103
236
  err(`Cannot start: ${e.message}`);
104
237
  return 1;
105
238
  }
239
+ signals.built(device);
106
240
  try {
107
241
  // a persisted binding of this credential comes back for same-generation journal recovery
108
242
  await device.binder.recover();
@@ -118,6 +252,7 @@ async function serveStaged(deps, cred, signals) {
118
252
  }
119
253
  const conn = (deps.connectStaged ?? connectStaged)(device, {
120
254
  err,
255
+ onState: signals.onState,
121
256
  // read before each reconnect only: a new login while running discards the old credential's
122
257
  // state (B-3)
123
258
  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 { policyMode, readCredential, readPolicy } from "../state.js";
1
+ import { queryControl } from "../control/client.js";
2
+ import { controlUnavailableReason } from "../control/server.js";
3
+ import { readRunningPid } from "../pid.js";
4
+ import { 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);
@@ -14,17 +51,19 @@ export function status(stateDir, json, out, err) {
14
51
  return 1;
15
52
  }
16
53
  // An unreadable policy file is reported by `start` and `policy show`; status still answers.
17
- let sandboxMode;
54
+ let ceiling;
18
55
  try {
19
- sandboxMode = policyMode(readPolicy(stateDir));
56
+ ceiling = readPolicy(stateDir).ownerCeiling;
20
57
  }
21
58
  catch {
22
- sandboxMode = undefined;
59
+ ceiling = undefined;
23
60
  }
61
+ const sandbox = ceiling && { network: ceiling.network, outsideSandbox: ceiling.outsideSandbox };
24
62
  // The credential itself is never printed.
25
63
  const { credential: _secret, ...shown } = cred;
64
+ const control = await controlState(stateDir, opts);
26
65
  if (json) {
27
- out(JSON.stringify({ loggedIn: true, ...shown, ...(sandboxMode && { sandboxMode }) }));
66
+ out(JSON.stringify({ loggedIn: true, ...shown, ...(sandbox && { sandbox }), ...control }));
28
67
  }
29
68
  else {
30
69
  out([
@@ -33,8 +72,21 @@ export function status(stateDir, json, out, err) {
33
72
  ` organization: ${cred.orgId}`,
34
73
  ` device: ${cred.deviceId}`,
35
74
  ` directory: ${cred.dir}`,
36
- ` mode: ${cred.mode} | ${sandboxMode ?? "unknown"}`,
75
+ ` mode: ${cred.mode}`,
76
+ ` sandbox: ${sandbox
77
+ ? `network ${sandbox.network}, outside the sandbox ${sandbox.outsideSandbox ? "allowed" : "off"}`
78
+ : "unknown"}`,
79
+ ` running: ${runningLine(control)}`,
37
80
  ].join("\n"));
38
81
  }
39
82
  return 0;
40
83
  }
84
+ function runningLine(c) {
85
+ if (c.control === "absent")
86
+ return "no";
87
+ if (c.control === "unavailable")
88
+ return `yes (no live status: ${c.controlReason})`;
89
+ const l = c.live;
90
+ const reason = l.offlineReason === undefined ? "" : `: ${l.offlineReason}`;
91
+ return `yes, pid ${l.pid}, ${l.connection}${reason} since ${l.since}`;
92
+ }
@@ -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
+ }>;