@capybara-hq/device 0.1.0-rc.4 → 0.1.0-rc.5

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.
package/dist/client.d.ts CHANGED
@@ -28,6 +28,11 @@ export interface ConnectOptions {
28
28
  livenessMs?: number;
29
29
  /** Terminate a socket still closing this long after we asked it to close (default 2 s). */
30
30
  closeTimeoutMs?: number;
31
+ /**
32
+ * How often a connected program checks its policy summary for a change made on the machine
33
+ * (default 2 s); a change is pushed to the deployment as a `policy` frame.
34
+ */
35
+ policyCheckMs?: number;
31
36
  }
32
37
  /**
33
38
  * A running connection. `done` resolves with the exit code once the program should end: 0 for the
package/dist/client.js CHANGED
@@ -38,6 +38,7 @@ export function connect(cred, executor, opts = {}) {
38
38
  const stableMs = opts.stableMs ?? 10_000;
39
39
  const livenessMs = opts.livenessMs ?? 60_000;
40
40
  const closeTimeoutMs = opts.closeTimeoutMs ?? 2000;
41
+ const policyCheckMs = opts.policyCheckMs ?? 2000;
41
42
  const lifetime = new AbortController();
42
43
  let ws;
43
44
  let draining = false;
@@ -70,6 +71,30 @@ export function connect(cred, executor, opts = {}) {
70
71
  pending.delete(k);
71
72
  };
72
73
  const isOpen = () => ws !== undefined && ws.readyState === WebSocket.OPEN;
74
+ /** The policy summary now: the store's policy (re-read when its file changed) and the facts. */
75
+ const summaryNow = () => opts.policy === undefined
76
+ ? undefined
77
+ : policySummary(opts.policy.current(), summaryFacts(executor, ctx));
78
+ /** The summary the deployment last got on this connection (hello, `policy` op, `policy` frame). */
79
+ let sentPolicy;
80
+ /**
81
+ * Pushes the policy summary when it differs from the one the deployment last got: the owner
82
+ * changed the policy on the machine (`capybara-device policy ...`), the localhost proxy guard
83
+ * flipped, or an exec brought a new tier ceiling. Without it the deployment would learn the
84
+ * change only at the next connect.
85
+ */
86
+ const pushPolicy = () => {
87
+ if (!isOpen())
88
+ return;
89
+ const summary = summaryNow();
90
+ if (summary === undefined)
91
+ return;
92
+ const json = JSON.stringify(summary);
93
+ if (json === sentPolicy)
94
+ return;
95
+ sentPolicy = json;
96
+ ws?.send(JSON.stringify({ type: "policy", policy: summary }));
97
+ };
73
98
  /** `res`, or an error answer when its frame would exceed the deployment's frame limit. */
74
99
  const fit = (res) => Buffer.byteLength(JSON.stringify(res)) <= cred.maxFrameBytes
75
100
  ? res
@@ -168,7 +193,13 @@ export function connect(cred, executor, opts = {}) {
168
193
  return;
169
194
  }
170
195
  else {
196
+ // a policy op's answer carries the summary the deployment stores
197
+ if (req.op === "policy" && res.ok) {
198
+ sentPolicy = JSON.stringify(res.result.policy);
199
+ }
171
200
  deliver(res);
201
+ // an exec may have changed the facts (the proxy guard, the tier ceiling)
202
+ pushPolicy();
172
203
  }
173
204
  maybeFinishDrain();
174
205
  });
@@ -213,6 +244,8 @@ export function connect(cred, executor, opts = {}) {
213
244
  * `devHosts`); the policy summary is the store's policy now, with the latest ceiling seen.
214
245
  */
215
246
  const hello = () => {
247
+ const summary = summaryNow();
248
+ sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
216
249
  const features = [];
217
250
  if (executor.mode === "os")
218
251
  features.push("networkReport");
@@ -229,9 +262,7 @@ export function connect(cred, executor, opts = {}) {
229
262
  roots: executor.roots,
230
263
  sessionIsolation: false,
231
264
  features,
232
- ...(opts.policy !== undefined && {
233
- policy: policySummary(opts.policy.current(), summaryFacts(executor, ctx)),
234
- }),
265
+ ...(summary !== undefined && { policy: summary }),
235
266
  };
236
267
  };
237
268
  let attempt = 0;
@@ -256,6 +287,7 @@ export function connect(cred, executor, opts = {}) {
256
287
  ws = sock;
257
288
  let liveness;
258
289
  let stable;
290
+ let policyCheck;
259
291
  let opened = false;
260
292
  /** The deployment answered the upgrade with an HTTP status (already handled). */
261
293
  let answered = false;
@@ -272,6 +304,8 @@ export function connect(cred, executor, opts = {}) {
272
304
  lastReport = undefined;
273
305
  }, stableMs);
274
306
  sock.send(JSON.stringify(hello()));
307
+ if (opts.policy !== undefined)
308
+ policyCheck = setInterval(pushPolicy, policyCheckMs);
275
309
  prune();
276
310
  for (const [id, p] of pending) {
277
311
  pending.delete(id);
@@ -310,6 +344,7 @@ export function connect(cred, executor, opts = {}) {
310
344
  sock.on("close", (code, reason) => {
311
345
  clearTimeout(liveness);
312
346
  clearTimeout(stable);
347
+ clearInterval(policyCheck);
313
348
  if (ws === sock)
314
349
  ws = undefined;
315
350
  if (exitAfterStop)
package/dist/exec/os.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, realpathSync } from "node:fs";
4
- import { constants as osConstants } from "node:os";
4
+ import { homedir, constants as osConstants } from "node:os";
5
5
  import { resolve } from "node:path";
6
6
  import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
7
7
  import { blockedHosts, denyReason, isPublicName, networkTrailer, } from "../network.js";
@@ -9,7 +9,7 @@ import { ANY_HOST, deviceTier, effectiveEgress, grantedHosts, srtConfig, tierFac
9
9
  import { detectLocalProxy, PROXY_GUARD_TTL_MS } from "../proxy-guard.js";
10
10
  import { FS_HELPER_SCRIPT } from "./fs-helper.js";
11
11
  import { EXEC_MARKER, killMarked } from "./procs.js";
12
- import { cacheEnv, cacheRoot, ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, prepareSocketDir, RootGuard, shellQuote, socketDirPath, } from "./shared.js";
12
+ import { cacheEnv, cacheRoot, ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, prepareSocketDir, RootGuard, shellQuote, socketDirPath, toolHomeEnv, } from "./shared.js";
13
13
  import { DeviceOpError } from "./types.js";
14
14
  export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
15
15
  /** A file operation in the sandboxed helper that takes longer than this is killed. */
@@ -239,6 +239,9 @@ export class OsExecutor {
239
239
  TERM: "dumb",
240
240
  HOME: this.roots.workspace,
241
241
  ...(process.env.USER !== undefined && { USER: process.env.USER }),
242
+ // Version managers (asdf, nvm, pyenv, ...) read their data under the real home, at every
243
+ // tier: HOME is the workspace here. Read only; the request's values win.
244
+ ...toolHomeEnv(this.opts.home ?? homedir()),
242
245
  // dev / open: package caches under <dir>/cache; the command's own values win.
243
246
  ...(dev && cacheEnv(this.cacheDir, { create: true })),
244
247
  ...o.env,
@@ -21,6 +21,22 @@ export declare function cacheRoot(dir: string): string;
21
21
  export declare function cacheEnv(root: string, opts?: {
22
22
  create?: boolean;
23
23
  }): Record<string, string>;
24
+ /**
25
+ * The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
26
+ * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
27
+ * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
28
+ * sets them. CARGO_HOME is a package cache ({@link cacheEnv}).
29
+ */
30
+ export declare const TOOL_HOME_DIRS: readonly (readonly [string, string])[];
31
+ /**
32
+ * The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
33
+ * the device's environment `env` sets to an absolute path is passed on; an unset one points at its
34
+ * default directory under the real `home` when that is a directory. The sandbox only reads them
35
+ * (they are never made writable); the secret paths stay denied. asdf's global `.tool-versions`
36
+ * is still found: asdf walks up from the working directory, and the device directory is under the
37
+ * home.
38
+ */
39
+ export declare function toolHomeEnv(home: string, env?: Record<string, string | undefined>): Record<string, string>;
24
40
  /**
25
41
  * The short socket directory of a device on macOS (spec §5.2.3): `<base>/cap-<first 8 hex of the
26
42
  * device's key>`, short enough for Chromium's singleton socket (unix socket paths stop at 104
@@ -1,4 +1,4 @@
1
- import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
1
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, realpathSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
2
2
  import { lstat, mkdir, open, realpath } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { DeviceOpError } from "./types.js";
@@ -119,6 +119,62 @@ export function cacheEnv(root, opts = {}) {
119
119
  return {};
120
120
  return out;
121
121
  }
122
+ /**
123
+ * The data directories of version managers, relative to the home: the OS sandbox sets HOME to the
124
+ * workspace, so their shims would look there and fail ("unknown command: python3. Perhaps you
125
+ * have to reshim?"). mise's follow XDG_DATA_HOME / XDG_CONFIG_HOME when the device's environment
126
+ * sets them. CARGO_HOME is a package cache ({@link cacheEnv}).
127
+ */
128
+ export const TOOL_HOME_DIRS = [
129
+ ["ASDF_DATA_DIR", ".asdf"],
130
+ ["NVM_DIR", ".nvm"],
131
+ ["PYENV_ROOT", ".pyenv"],
132
+ ["RBENV_ROOT", ".rbenv"],
133
+ ["MISE_DATA_DIR", ".local/share/mise"],
134
+ ["MISE_CONFIG_DIR", ".config/mise"],
135
+ ["VOLTA_HOME", ".volta"],
136
+ ["SDKMAN_DIR", ".sdkman"],
137
+ ["RUSTUP_HOME", ".rustup"],
138
+ ];
139
+ function isDir(path) {
140
+ try {
141
+ return statSync(path).isDirectory();
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ /**
148
+ * The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
149
+ * the device's environment `env` sets to an absolute path is passed on; an unset one points at its
150
+ * default directory under the real `home` when that is a directory. The sandbox only reads them
151
+ * (they are never made writable); the secret paths stay denied. asdf's global `.tool-versions`
152
+ * is still found: asdf walks up from the working directory, and the device directory is under the
153
+ * home.
154
+ */
155
+ export function toolHomeEnv(home, env = process.env) {
156
+ const xdg = (name, rel) => {
157
+ const v = env[name];
158
+ return v !== undefined && isAbsolute(v) ? v : join(home, rel);
159
+ };
160
+ const defaults = {
161
+ MISE_DATA_DIR: join(xdg("XDG_DATA_HOME", ".local/share"), "mise"),
162
+ MISE_CONFIG_DIR: join(xdg("XDG_CONFIG_HOME", ".config"), "mise"),
163
+ };
164
+ const out = {};
165
+ for (const [name, rel] of TOOL_HOME_DIRS) {
166
+ const set = env[name];
167
+ if (set !== undefined && set !== "") {
168
+ if (isAbsolute(set))
169
+ out[name] = set;
170
+ continue;
171
+ }
172
+ const dir = defaults[name] ?? join(home, rel);
173
+ if (isDir(dir))
174
+ out[name] = dir;
175
+ }
176
+ return out;
177
+ }
122
178
  /**
123
179
  * The short socket directory of a device on macOS (spec §5.2.3): `<base>/cap-<first 8 hex of the
124
180
  * device's key>`, short enough for Chromium's singleton socket (unix socket paths stop at 104
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.1.0-rc.4",
3
+ "version": "0.1.0-rc.5",
4
4
  "description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@anthropic-ai/sandbox-runtime": "0.0.81",
36
36
  "ws": "^8.18.0",
37
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.16"
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.17"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/ws": "^8.5.13"