@capybara-hq/device 0.1.0-rc.1 → 0.1.0-rc.11

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 (73) hide show
  1. package/README.md +205 -44
  2. package/dist/api.d.ts +6 -1
  3. package/dist/args.d.ts +14 -3
  4. package/dist/args.js +74 -10
  5. package/dist/cli.d.ts +27 -4
  6. package/dist/cli.js +81 -11
  7. package/dist/client.d.ts +19 -6
  8. package/dist/client.js +93 -19
  9. package/dist/command-log.d.ts +8 -0
  10. package/dist/commands/drain.d.ts +14 -1
  11. package/dist/commands/drain.js +31 -2
  12. package/dist/commands/login.d.ts +3 -0
  13. package/dist/commands/login.js +96 -11
  14. package/dist/commands/logout.d.ts +2 -0
  15. package/dist/commands/logout.js +1 -1
  16. package/dist/commands/mode.d.ts +69 -0
  17. package/dist/commands/mode.js +129 -0
  18. package/dist/commands/policy.d.ts +13 -4
  19. package/dist/commands/policy.js +162 -33
  20. package/dist/commands/service.d.ts +26 -4
  21. package/dist/commands/service.js +242 -19
  22. package/dist/commands/signal.d.ts +6 -2
  23. package/dist/commands/signal.js +7 -4
  24. package/dist/commands/start.d.ts +18 -3
  25. package/dist/commands/start.js +46 -7
  26. package/dist/commands/status.js +12 -4
  27. package/dist/commands/stop.d.ts +20 -2
  28. package/dist/commands/stop.js +26 -3
  29. package/dist/exec/docker.d.ts +41 -13
  30. package/dist/exec/docker.js +123 -57
  31. package/dist/exec/fs-helper.d.ts +13 -8
  32. package/dist/exec/fs-helper.js +31 -13
  33. package/dist/exec/groups.d.ts +42 -0
  34. package/dist/exec/groups.js +100 -0
  35. package/dist/exec/host.d.ts +53 -0
  36. package/dist/exec/host.js +183 -0
  37. package/dist/exec/os.d.ts +85 -15
  38. package/dist/exec/os.js +208 -36
  39. package/dist/exec/reap.d.ts +41 -0
  40. package/dist/exec/reap.js +89 -0
  41. package/dist/exec/sandbox-messages.d.ts +14 -0
  42. package/dist/exec/sandbox-messages.js +21 -0
  43. package/dist/exec/shared.d.ts +42 -13
  44. package/dist/exec/shared.js +94 -16
  45. package/dist/exec/switch.d.ts +98 -0
  46. package/dist/exec/switch.js +175 -0
  47. package/dist/exec/types.d.ts +28 -4
  48. package/dist/index.d.ts +1 -1
  49. package/dist/network.d.ts +45 -0
  50. package/dist/network.js +154 -0
  51. package/dist/pid.d.ts +44 -3
  52. package/dist/pid.js +110 -7
  53. package/dist/policy-ops.d.ts +47 -0
  54. package/dist/policy-ops.js +90 -0
  55. package/dist/policy-store.d.ts +43 -0
  56. package/dist/policy-store.js +94 -0
  57. package/dist/policy.d.ts +36 -16
  58. package/dist/policy.js +77 -19
  59. package/dist/public-suffix.d.ts +6 -0
  60. package/dist/public-suffix.js +79 -0
  61. package/dist/server-ops.d.ts +48 -7
  62. package/dist/server-ops.js +287 -29
  63. package/dist/service/installed.d.ts +5 -0
  64. package/dist/service/installed.js +14 -0
  65. package/dist/service/launchd.d.ts +14 -1
  66. package/dist/service/launchd.js +25 -1
  67. package/dist/service/manager.d.ts +41 -0
  68. package/dist/service/manager.js +91 -0
  69. package/dist/service/systemd.d.ts +2 -0
  70. package/dist/service/systemd.js +8 -0
  71. package/dist/state.d.ts +50 -6
  72. package/dist/state.js +195 -16
  73. package/package.json +3 -3
@@ -0,0 +1,69 @@
1
+ import type { Command } from "../args.js";
2
+ /**
3
+ * Shown once before auto mode is turned on, and once at login in an organization that allows it
4
+ * (spec §8): the trust model is command review, not the OS sandbox.
5
+ */
6
+ export declare const AUTO_MODE_RISK_TEXT: string;
7
+ /** The refusal of `capybara-device mode auto` without `--yes` or a `y` at the prompt. */
8
+ export declare const MODE_AUTO_NEEDS_YES = "Nothing changed. To run commands in auto mode, run: capybara-device mode auto --yes";
9
+ /** Printed before the question `capybara-device mode auto` asks on a terminal. */
10
+ export declare const MODE_AUTO_PROMPT = "Run agent commands on this computer as you, in auto mode? [y/N] ";
11
+ /**
12
+ * The line `login` prints when the organization allows auto mode and this machine's policy is
13
+ * auto (the default).
14
+ */
15
+ export declare const AUTO_MODE_LOGIN_LINE: string;
16
+ /**
17
+ * The line `login` prints when the organization allows auto mode but this machine's persisted
18
+ * policy is sandbox mode (an earlier login in an auto-forbidden organization, or the owner's
19
+ * switch): the line follows the machine, not the allowance.
20
+ */
21
+ export declare const SANDBOX_POLICY_LOGIN_LINE: string;
22
+ /** The line `login` prints when the organization forbids auto mode and the policy now says so. */
23
+ export declare const SANDBOX_MODE_LOGIN_LINE: string;
24
+ /**
25
+ * The line `login` prints when the organization forbids auto mode but the machine keeps its own
26
+ * auto policy: the kernel refuses every command until the owner switches the machine.
27
+ */
28
+ export declare const AUTO_POLICY_REFUSED_LOGIN_LINE: string;
29
+ /** The line `login --mode docker` prints when the device runs in auto mode. */
30
+ export declare const DOCKER_AUTO_MODE_LOGIN_LINE: string;
31
+ /** The line `login --mode docker` prints when the local policy is sandbox mode. */
32
+ export declare const DOCKER_SANDBOX_MODE_LOGIN_LINE: string;
33
+ /**
34
+ * The line `login` prints when the organization forbids auto mode and the OS sandbox cannot run
35
+ * here: no sandbox policy is written (it could not run a command either).
36
+ */
37
+ export declare function sandboxUnavailableLoginLine(reason: string): string;
38
+ /** The OS sandbox check `login` and `mode` use (default: the runtime's, loaded on demand). */
39
+ export type SandboxCheck = () => {
40
+ ok: true;
41
+ } | {
42
+ ok: false;
43
+ reason: string;
44
+ };
45
+ export declare function checkSandbox(check: SandboxCheck | undefined): Promise<{
46
+ ok: true;
47
+ } | {
48
+ ok: false;
49
+ reason: string;
50
+ }>;
51
+ export interface ModeDeps {
52
+ stateDir: string;
53
+ out: (line: string) => void;
54
+ err: (line: string) => void;
55
+ /**
56
+ * Asks the question on a terminal (only when standard input is one). Without it and without
57
+ * `--yes`, `mode auto` changes nothing.
58
+ */
59
+ ask?: (question: string) => Promise<string>;
60
+ /**
61
+ * Whether the OS sandbox can run here (default: the runtime's check). `mode sandbox` is refused
62
+ * when it cannot; injectable for tests.
63
+ */
64
+ sandboxAvailable?: SandboxCheck;
65
+ }
66
+ /** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
67
+ export declare function modeCommand(cmd: Extract<Command, {
68
+ command: "mode";
69
+ }>, deps: ModeDeps): Promise<number>;
@@ -0,0 +1,129 @@
1
+ import { SANDBOX_INSTALL_HINT, sandboxUnavailableSwitchRefusal } from "../exec/sandbox-messages.js";
2
+ import { PolicyStore } from "../policy-store.js";
3
+ import { policyPath, readCredential } from "../state.js";
4
+ /**
5
+ * Shown once before auto mode is turned on, and once at login in an organization that allows it
6
+ * (spec §8): the trust model is command review, not the OS sandbox.
7
+ */
8
+ export const AUTO_MODE_RISK_TEXT = "In auto mode, agent commands run on this computer as you: they can read and write all your " +
9
+ "files, use your credentials (SSH keys, cloud accounts, keychain), Docker and any network, and " +
10
+ "the deployment reviews every command before it runs. Prompt injection can make an agent try " +
11
+ "to delete files or send your credentials away; the review blocks or asks about the dangerous " +
12
+ "ones. Such commands can also read this program's own credential: if you suspect misuse, run " +
13
+ "capybara-device logout and log in again.";
14
+ /** The refusal of `capybara-device mode auto` without `--yes` or a `y` at the prompt. */
15
+ export const MODE_AUTO_NEEDS_YES = "Nothing changed. To run commands in auto mode, run: capybara-device mode auto --yes";
16
+ /** Printed before the question `capybara-device mode auto` asks on a terminal. */
17
+ export const MODE_AUTO_PROMPT = "Run agent commands on this computer as you, in auto mode? [y/N] ";
18
+ /**
19
+ * The line `login` prints when the organization allows auto mode and this machine's policy is
20
+ * auto (the default).
21
+ */
22
+ export const AUTO_MODE_LOGIN_LINE = "New logins start in auto mode: agent commands run as you on this machine, and the deployment " +
23
+ "reviews every command. Switch with `capybara-device mode sandbox`.";
24
+ /**
25
+ * The line `login` prints when the organization allows auto mode but this machine's persisted
26
+ * policy is sandbox mode (an earlier login in an auto-forbidden organization, or the owner's
27
+ * switch): the line follows the machine, not the allowance.
28
+ */
29
+ export const SANDBOX_POLICY_LOGIN_LINE = "This organization allows auto mode, but this machine's local policy is sandbox mode: agent " +
30
+ "commands run inside the OS sandbox here. Switch with `capybara-device mode auto`.";
31
+ /** The line `login` prints when the organization forbids auto mode and the policy now says so. */
32
+ export const SANDBOX_MODE_LOGIN_LINE = "This organization does not allow auto mode, so this device runs in sandbox mode: agent " +
33
+ "commands run inside the OS sandbox on this machine.";
34
+ /**
35
+ * The line `login` prints when the organization forbids auto mode but the machine keeps its own
36
+ * auto policy: the kernel refuses every command until the owner switches the machine.
37
+ */
38
+ export const AUTO_POLICY_REFUSED_LOGIN_LINE = "This organization does not allow auto mode, but this machine's local policy is auto mode: the " +
39
+ "deployment refuses every command until you run `capybara-device mode sandbox`.";
40
+ /** The line `login --mode docker` prints when the device runs in auto mode. */
41
+ export const DOCKER_AUTO_MODE_LOGIN_LINE = "New logins start in auto mode: agent commands run in this device's Docker container with its " +
42
+ "network, file operations reach any path in the container, and the deployment reviews every " +
43
+ "command. Switch with `capybara-device mode sandbox`.";
44
+ /** The line `login --mode docker` prints when the local policy is sandbox mode. */
45
+ export const DOCKER_SANDBOX_MODE_LOGIN_LINE = "This device runs in sandbox mode: agent commands run in this device's Docker container " +
46
+ "without a network, and file operations stay in the device's directories.";
47
+ /**
48
+ * The line `login` prints when the organization forbids auto mode and the OS sandbox cannot run
49
+ * here: no sandbox policy is written (it could not run a command either).
50
+ */
51
+ export function sandboxUnavailableLoginLine(reason) {
52
+ return ("This organization does not allow auto mode, and the OS sandbox is unavailable on this " +
53
+ `machine (${reason}), so no command can run here yet: ${SANDBOX_INSTALL_HINT}, then run ` +
54
+ "`capybara-device mode sandbox`; or log in again with --mode docker.");
55
+ }
56
+ export async function checkSandbox(check) {
57
+ if (check !== undefined)
58
+ return check();
59
+ const os = await import("../exec/os.js");
60
+ return os.sandboxAvailability();
61
+ }
62
+ /** Whether this machine is logged in in Docker mode (false when unknown). */
63
+ function dockerRunMode(stateDir) {
64
+ try {
65
+ return readCredential(stateDir)?.mode === "docker";
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
71
+ /** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
72
+ export async function modeCommand(cmd, deps) {
73
+ const { stateDir, out, err } = deps;
74
+ let store;
75
+ try {
76
+ store = new PolicyStore(stateDir);
77
+ }
78
+ catch (e) {
79
+ err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
80
+ return 1;
81
+ }
82
+ const mode = cmd.mode;
83
+ if (mode === undefined) {
84
+ const now = store.current().mode;
85
+ out(`Mode: ${now}.`);
86
+ out(now === "auto"
87
+ ? "Commands run as you on this machine; the deployment reviews every command."
88
+ : "Commands run in the OS sandbox; only the workspace, skills and temporary files are " +
89
+ "writable and the network reaches the allowed hosts.");
90
+ return 0;
91
+ }
92
+ if (mode === "auto") {
93
+ // The risk text is printed once, whether --yes was given or the question is asked.
94
+ out(AUTO_MODE_RISK_TEXT);
95
+ if (cmd.yes !== true) {
96
+ if (deps.ask === undefined) {
97
+ err(MODE_AUTO_NEEDS_YES);
98
+ return 2;
99
+ }
100
+ const answer = (await deps.ask(MODE_AUTO_PROMPT)).trim().toLowerCase();
101
+ if (answer !== "y" && answer !== "yes") {
102
+ err("Nothing changed.");
103
+ return 1;
104
+ }
105
+ }
106
+ }
107
+ let next;
108
+ if (mode === "sandbox" && !dockerRunMode(stateDir)) {
109
+ // Sandbox mode cannot run a command without the OS sandbox; refuse the switch on such a
110
+ // machine and leave the policy as it is (auto mode keeps working).
111
+ const available = await checkSandbox(deps.sandboxAvailable);
112
+ if (!available.ok) {
113
+ err(sandboxUnavailableSwitchRefusal(available.reason));
114
+ return 1;
115
+ }
116
+ }
117
+ try {
118
+ next = store.update((p) => ({ ...p, mode })).mode;
119
+ }
120
+ catch (e) {
121
+ err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
122
+ return 1;
123
+ }
124
+ out(next === "auto"
125
+ ? "This machine's local policy is now auto mode (from the next command); the deployment's " +
126
+ "ceiling still applies."
127
+ : "This machine's local policy is now sandbox mode (from the next command).");
128
+ return 0;
129
+ }
@@ -1,15 +1,24 @@
1
1
  import type { Command } from "../args.js";
2
+ import { type Policy } from "../state.js";
2
3
  export interface PolicyDeps {
3
4
  stateDir: string;
4
5
  out: (line: string) => void;
5
6
  err: (line: string) => void;
6
7
  }
7
- /** What the OS mode does not enforce yet, shown with every `show` and `set`. */
8
+ /** What OS mode does not enforce yet, shown with `show` and with a limits change. */
8
9
  export declare const NOT_ENFORCED_NOTE: string;
10
+ /** Shown when a Docker-mode device's policy is shown or given allowed domains. */
11
+ export declare const DOCKER_DOMAIN_NOTE: string;
12
+ /** What `policy show` says the mode gives on this machine (English, one line each). */
13
+ export declare function describeMode(policy: Policy, runMode?: "os" | "docker"): string[];
9
14
  /**
10
- * `policy show` prints the local policy; `policy set <key> <value>` changes one field. Only the
11
- * machine's user edits this file: the cloud never writes it. Changes apply at the next start.
15
+ * `policy show` prints the local policy and what its mode gives on this machine;
16
+ * `policy set <key> <value>` replaces one field; `policy add|remove <key> <value>` adds or removes
17
+ * entries of a list field. The mode is set with `capybara-device mode`. The machine's user edits
18
+ * this file; the deployment changes it only through the `policy` op (narrowing only: hosts and
19
+ * `mode: "sandbox"`, never auto). Writes take policy.json.lock, and a running program applies the
20
+ * change at its next command.
12
21
  */
13
22
  export declare function policyCommand(cmd: Extract<Command, {
14
23
  command: "policy";
15
- }>, deps: PolicyDeps): number;
24
+ }>, deps: PolicyDeps): Promise<number>;
@@ -1,9 +1,15 @@
1
1
  import { validateAllowHost } from "@capybara-hq/plugin-sdk";
2
- import { policyPath, readPolicy, writePolicy } from "../state.js";
3
- const KEYS = ["allowedDomains", "allowCredentials", "cpu", "memoryMb"];
4
- /** What the OS mode does not enforce yet, shown with every `show` and `set`. */
5
- export const NOT_ENFORCED_NOTE = "Note: in OS mode cpu and memoryMb are not enforced yet, and allowCredentials is not used: " +
6
- "commands get no local credentials.";
2
+ import { PolicyStore } from "../policy-store.js";
3
+ import { policyPath, readCredential } from "../state.js";
4
+ /** The fields `show` prints and `set` may replace. */
5
+ const KEYS = ["allowedDomains", "allowCredentials", "cpu", "memoryMb", "mode"];
6
+ /** What OS mode does not enforce yet, shown with `show` and with a limits change. */
7
+ export const NOT_ENFORCED_NOTE = "Note: in OS mode cpu and memoryMb are not enforced yet; allowCredentials is ignored (auto " +
8
+ "mode already has the owner's credentials, sandbox mode gets none).";
9
+ /** Shown when a Docker-mode device's policy is shown or given allowed domains. */
10
+ export const DOCKER_DOMAIN_NOTE = "Note: this device runs commands in Docker mode, where the mode alone decides network " +
11
+ "access (auto: the default bridge; sandbox: no network). Allowed domains apply in OS mode's " +
12
+ "sandbox only.";
7
13
  function list(value) {
8
14
  return value
9
15
  .split(",")
@@ -19,56 +25,179 @@ function ceiling(key, value) {
19
25
  }
20
26
  return n;
21
27
  }
28
+ /** Whether this machine is logged in in Docker mode (false when unknown). */
29
+ function dockerMode(stateDir) {
30
+ try {
31
+ return readCredential(stateDir)?.mode === "docker";
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ /** The keys `add` and `remove` work on: the list fields. */
38
+ const LIST_KEYS = ["allowedDomains", "allowCredentials"];
39
+ /** Lowercased, validated hosts; throws naming the first bad one. */
40
+ function domains(value) {
41
+ const out = list(value).map((d) => d.toLowerCase());
42
+ for (const d of out) {
43
+ const errors = validateAllowHost(d);
44
+ if (errors.length > 0)
45
+ throw new Error(`"${d}": ${errors.join("; ")}`);
46
+ }
47
+ return out;
48
+ }
49
+ /** The new value of a list field after `add` / `remove`; unchanged entries are reported. */
50
+ function edit(current, action, key, values, out) {
51
+ // Domains compare ignoring case (a hand-edited file may hold any spelling).
52
+ const norm = key === "allowedDomains" ? (v) => v.toLowerCase() : (v) => v;
53
+ const has = (list, v) => list.some((x) => norm(x) === norm(v));
54
+ if (action === "add") {
55
+ const next = [...current];
56
+ for (const v of values) {
57
+ if (has(next, v))
58
+ out(`${v} is already in ${key}.`);
59
+ else {
60
+ next.push(v);
61
+ out(`Added ${v} to ${key}.`);
62
+ }
63
+ }
64
+ return next;
65
+ }
66
+ for (const v of values)
67
+ out(has(current, v) ? `Removed ${v} from ${key}.` : `${v} is not in ${key}.`);
68
+ return current.filter((x) => !has(values, x));
69
+ }
70
+ /** What `policy show` says the mode gives on this machine (English, one line each). */
71
+ export function describeMode(policy, runMode = "os") {
72
+ if (policy.mode === "auto") {
73
+ if (runMode === "docker") {
74
+ return [
75
+ "Mode: auto. Commands run in the device's container on its default bridge, and the " +
76
+ "platform's file tools reach any path in the container; the deployment reviews every " +
77
+ "command and blocks or asks about dangerous ones.",
78
+ ];
79
+ }
80
+ return [
81
+ "Mode: auto. Commands run as you on this machine, with their files, credentials and " +
82
+ "network; the deployment reviews every command and blocks or asks about dangerous ones.",
83
+ "Allowed domains apply in sandbox mode only (capybara-device mode sandbox).",
84
+ ];
85
+ }
86
+ if (runMode === "docker") {
87
+ return [
88
+ "Mode: sandbox. Commands run in the device's container with no network; only the " +
89
+ "workspace, skills and temporary files are writable.",
90
+ ];
91
+ }
92
+ return [
93
+ "Mode: sandbox. Only the workspace, skills and temporary files are writable; the network " +
94
+ "reaches the allowed hosts.",
95
+ ];
96
+ }
22
97
  /**
23
- * `policy show` prints the local policy; `policy set <key> <value>` changes one field. Only the
24
- * machine's user edits this file: the cloud never writes it. Changes apply at the next start.
98
+ * `policy show` prints the local policy and what its mode gives on this machine;
99
+ * `policy set <key> <value>` replaces one field; `policy add|remove <key> <value>` adds or removes
100
+ * entries of a list field. The mode is set with `capybara-device mode`. The machine's user edits
101
+ * this file; the deployment changes it only through the `policy` op (narrowing only: hosts and
102
+ * `mode: "sandbox"`, never auto). Writes take policy.json.lock, and a running program applies the
103
+ * change at its next command.
25
104
  */
26
- export function policyCommand(cmd, deps) {
105
+ export async function policyCommand(cmd, deps) {
27
106
  const { stateDir, out, err } = deps;
28
- let policy;
107
+ let store;
29
108
  try {
30
- policy = readPolicy(stateDir);
109
+ store = new PolicyStore(stateDir);
31
110
  }
32
111
  catch (e) {
33
112
  err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
34
113
  return 1;
35
114
  }
115
+ const docker = dockerMode(stateDir);
36
116
  if (cmd.action === "show") {
117
+ const policy = store.current();
37
118
  out(JSON.stringify(policy, null, 2));
119
+ for (const l of describeMode(policy, docker ? "docker" : "os"))
120
+ out(l);
121
+ if (docker)
122
+ out(DOCKER_DOMAIN_NOTE);
38
123
  out(NOT_ENFORCED_NOTE);
39
124
  return 0;
40
125
  }
41
- const { key, value } = cmd;
42
- const next = { ...policy };
126
+ const { action, key, value } = cmd;
127
+ // Parse and validate before taking the lock; apply inside it, against the file as it is then.
128
+ let change;
43
129
  try {
44
- switch (key) {
45
- case "allowedDomains": {
46
- const domains = list(value).map((d) => d.toLowerCase());
47
- for (const d of domains) {
48
- const errors = validateAllowHost(d);
49
- if (errors.length > 0)
50
- throw new Error(`"${d}": ${errors.join("; ")}`);
130
+ if (action === "set") {
131
+ switch (key) {
132
+ case "allowedDomains": {
133
+ const next = [...new Set(domains(value))];
134
+ change = (p) => ({ ...p, allowedDomains: next });
135
+ break;
136
+ }
137
+ case "allowCredentials": {
138
+ const next = [...new Set(list(value))];
139
+ change = (p) => ({ ...p, allowCredentials: next });
140
+ break;
141
+ }
142
+ case "cpu":
143
+ case "memoryMb": {
144
+ const next = ceiling(key, value);
145
+ change = (p) => ({ ...p, [key]: next });
146
+ break;
51
147
  }
52
- next.allowedDomains = [...new Set(domains)];
53
- break;
148
+ case "mode":
149
+ throw new Error("the mode is set with: capybara-device mode auto|sandbox");
150
+ case "network":
151
+ case "tier":
152
+ case "isolation":
153
+ case "localhost":
154
+ case "remoteGrants":
155
+ throw new Error(`"${key}" is gone: the mode is set with capybara-device mode auto|sandbox; ` +
156
+ `allowedDomains with capybara-device policy add allowedDomains <host>`);
157
+ default:
158
+ throw new Error(`unknown policy key "${key}"; one of ${KEYS.join(", ")}`);
54
159
  }
55
- case "allowCredentials":
56
- next.allowCredentials = [...new Set(list(value))];
57
- break;
58
- case "cpu":
59
- case "memoryMb":
60
- next[key] = ceiling(key, value);
61
- break;
62
- default:
63
- throw new Error(`unknown policy key "${key}"; one of ${KEYS.join(", ")}`);
160
+ }
161
+ else {
162
+ if (!LIST_KEYS.includes(key)) {
163
+ throw new Error(`${action} works on ${LIST_KEYS.join(" and ")} only; use set for ${key}`);
164
+ }
165
+ const listKey = key;
166
+ // Only additions are validated: any entry already in the file can be removed.
167
+ const values = listKey !== "allowedDomains"
168
+ ? list(value)
169
+ : action === "add"
170
+ ? domains(value)
171
+ : list(value).map((d) => d.toLowerCase());
172
+ if (values.length === 0)
173
+ throw new Error(`${action} needs at least one value`);
174
+ change = (p, say) => ({ ...p, [listKey]: edit(p[listKey], action, listKey, values, say) });
64
175
  }
65
176
  }
66
177
  catch (e) {
67
178
  err(e.message);
68
179
  return 2;
69
180
  }
70
- writePolicy(stateDir, next);
71
- out(`Saved ${policyPath(stateDir)}. Restart capybara-device for it to take effect.`);
72
- out(NOT_ENFORCED_NOTE);
181
+ const lines = [];
182
+ let next;
183
+ try {
184
+ next = store.update((p) => change(p, (l) => lines.push(l)));
185
+ }
186
+ catch (e) {
187
+ err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
188
+ return 1;
189
+ }
190
+ for (const l of lines)
191
+ out(l);
192
+ out(`Saved ${policyPath(stateDir)}. A running capybara-device applies it at the next command.`);
193
+ if (key === "allowedDomains") {
194
+ out(docker
195
+ ? DOCKER_DOMAIN_NOTE
196
+ : next.mode === "auto"
197
+ ? "Allowed domains apply in sandbox mode only; switch with: capybara-device mode sandbox"
198
+ : "Sandboxed commands may reach these domains when the organization allows them too.");
199
+ }
200
+ if (key === "cpu" || key === "memoryMb" || key === "allowCredentials")
201
+ out(NOT_ENFORCED_NOTE);
73
202
  return 0;
74
203
  }
@@ -1,3 +1,6 @@
1
+ import { type ProcessChecks } from "../pid.js";
2
+ import { type RunSystem } from "../service/manager.js";
3
+ export type ServiceAction = "install" | "uninstall" | "start" | "stop" | "restart" | "status";
1
4
  export interface ServiceDeps {
2
5
  stateDir: string;
3
6
  home: string;
@@ -5,13 +8,32 @@ export interface ServiceDeps {
5
8
  env: Record<string, string | undefined>;
6
9
  out: (line: string) => void;
7
10
  err: (line: string) => void;
8
- /** Runs a system command; throws when it fails (default: execFileSync). */
9
- run?: (cmd: string, args: string[]) => void;
11
+ /**
12
+ * Runs a system command and returns its output; throws when it fails (default: execFileSync,
13
+ * whose error carries the exit `status` and `stderr`).
14
+ */
15
+ run?: RunSystem;
16
+ /** Waits between service manager checks (default: setTimeout). */
17
+ sleep?: (ms: number) => Promise<void>;
18
+ /** How the pid file's program is checked (default: `kill(pid, 0)` and `ps`). */
19
+ kill?: typeof process.kill;
20
+ ps?: ProcessChecks["ps"];
10
21
  uid?: number;
11
22
  nodePath?: string;
12
23
  binPath?: string;
13
24
  }
14
25
  /** What the service needs from the installing shell: PATH (docker lives there) and the state dir. */
15
26
  export declare function serviceEnv(env: Record<string, string | undefined>): Record<string, string>;
16
- /** `service install|uninstall`: runs `capybara-device start` at login (launchd) or boot (systemd user). */
17
- export declare function serviceCommand(action: "install" | "uninstall", deps: ServiceDeps): number;
27
+ /** How often launchctl is asked whether the old service is gone. */
28
+ export declare const SERVICE_POLL_MS = 200;
29
+ /** How long install / uninstall wait for `launchctl bootout` to finish (it is asynchronous). */
30
+ export declare const SERVICE_GONE_TIMEOUT_MS = 10000;
31
+ /** How long `service start|restart` wait for the program to be running. */
32
+ export declare const SERVICE_UP_TIMEOUT_MS = 10000;
33
+ /** The waits before each retry of a `launchctl bootstrap` that failed with error 5. */
34
+ export declare const BOOTSTRAP_BACKOFF_MS: readonly [500, 1000, 2000];
35
+ /**
36
+ * `service install|uninstall|status`: runs `capybara-device start` at login (launchd) or boot
37
+ * (systemd user), removes it, or reports whether it is loaded and running.
38
+ */
39
+ export declare function serviceCommand(action: ServiceAction, deps: ServiceDeps): Promise<number>;