@capybara-hq/plugin-device-local 0.1.0-rc.1 → 0.1.0-rc.10

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "name": "device-local",
4
- "version": "0.1.0-rc.1",
4
+ "version": "0.1.0-rc.10",
5
5
  "publisher": "Capybara",
6
6
  "description": {
7
7
  "en": "Devices on people's own computers: a machine connected with capybara-device serves the device over the dial-in channel, and its owner limits it there",
@@ -23,7 +23,7 @@
23
23
  "entry": "./dist/index.mjs",
24
24
  "manifest": {
25
25
  "name": "device-local",
26
- "version": "0.1.0-rc.1",
26
+ "version": "0.1.0-rc.10",
27
27
  "sdk": "^0.1.0-rc.56",
28
28
  "provides": [
29
29
  "device-provider@1"
@@ -32,12 +32,11 @@
32
32
  "optional": [],
33
33
  "permissions": {
34
34
  "dialIn": {
35
- "protocol": "capybara-device/5"
35
+ "protocol": "capybara-device/6"
36
36
  }
37
37
  },
38
38
  "config": {
39
- "deployment": [],
40
- "org": []
39
+ "deployment": []
41
40
  }
42
41
  },
43
42
  "migrations": "./migrations"
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Devices on people's own computers (`device-provider@1` over the kernel's dial-in channel). A machine
4
4
  signs in with [`capybara-device`](https://www.npmjs.com/package/@capybara-hq/device) (protocol
5
- `capybara-device/5`, declared as `permissions.dialIn`) and serves one device; every operation of the
5
+ `capybara-device/6`, declared as `permissions.dialIn`) and serves one device; every operation of the
6
6
  device is relayed to it through `ctx.dialIn`. The kernel holds the machine's socket and relays the
7
7
  frames without reading them; this plugin checks every request before it is sent and parses every
8
8
  answer strictly (the machine is not trusted).
@@ -14,9 +14,22 @@ answer strictly (the machine is not trusted).
14
14
  | `createFileSystem` / `destroyFileSystem` | Nothing on the machine: the device directory (`~/capybara-device/<device id>`) belongs to the machine's owner and stays when the device is deleted; `destroyFileSystem` forgets the device's rows |
15
15
  | `create` | `create` (ends the previous generation's background work, answers the directory's roots), then `bindInstance` of a new instance generation; the handle is handed out only once the machine attested the binding |
16
16
  | `resume` | Needs the machine online. `create` again (ends any background work a suspension could not reach), then the identical `bindInstance`; `gone` when the roots changed (a new login into another directory or mode) or the machine can no longer hold the generation (its runtime changed) |
17
+ | `update` | Nothing on the machine: a widening of the network (every host still allowed) is stored with the generation's binding, new resources included (commands carry them from then on), and answers `updated`; the next `ensureService` sends the network, and the machine restarts a running service started with another. A narrowing or a call without a fence answers `recreate` |
17
18
  | `suspend` / `destroy` | `create` when the machine is online: the generation's tracked background work ends, files are kept. Never fails while the machine is offline |
18
- | `operation` / `prepare` / `browse` / `background` / `revokeOperation` | The scoped protocol 5 operations, each with its admitted scope |
19
- | raw `exec` / `readFile` / … , `killAll` / `killTagged` | Refused or nothing: a protocol 5 machine runs work only under an admitted operation scope |
19
+ | `operation` / `prepare` / `browse` / `background` / `revokeOperation` | The scoped protocol 6 operations, each with its admitted scope |
20
+ | raw `exec` / `readFile` / … , `killAll` / `killTagged` | Refused or nothing: a protocol 6 machine runs work only under an admitted operation scope |
21
+
22
+ **Limits and fencing.** The limits in force are stored with the generation's binding (`create`
23
+ stores the kernel's, `update` replaces them on a widening); the kernel keeps the handle as `create`
24
+ returned it. `limitsApplyAt` is `instance` (a recreate applies new limits). Fence tokens (device
25
+ update fencing): `update` compares the token with the stored one and stores it in one locked PG
26
+ transaction, refusing a lower one with `StaleFenceError` and writing nothing; a `recreate` answer
27
+ still raises the stored token. `create` and `destroy` read the stored token first and refuse a
28
+ lower one before they ask the machine; that read and the machine call are not one atomic step, so
29
+ a newer holder's token stored in between is not seen by them (a narrow window: the kernel's own
30
+ fenced write for the holder precedes each call). `create` compares once more, atomically, when it
31
+ commits the new binding, so a stale holder never installs a generation. A `create` without a fence
32
+ (an older kernel) compares nothing and stores 0.
20
33
 
21
34
  A command carries the instance's resources and, as its outer network, the network the kernel
22
35
  admitted for the operation (its scope); the machine intersects it with its owner's ceiling. The
@@ -55,19 +68,40 @@ generation under another runtime identity is refused (`local.invalid_hello`,
55
68
  - **Attestation.** An unbound hello (the program restarted, typically under a new runtime after an
56
69
  upgrade) marks the installed binding unattested: the instance is gone and the kernel recreates
57
70
  it, which binds a new generation.
58
- - **`report()`** answers from the rows only: a description of the owner's ceiling (reach, outside
59
- the sandbox, network) in English and Chinese, the owner's home (OS mode), the machine's own
60
- narrowing as read-only limits and `reset: false`. Its revision is a hash of everything it is made
71
+ - **`report()`** answers from the rows only: a description of the owner's ceiling (project reach
72
+ `machine` / `paths` / `workspace`, always `workspace` in Docker mode; outside the sandbox;
73
+ network) in English and Chinese, the owner's home (OS mode), the machine's own
74
+ narrowing as read-only limits, `reset: false` and `changeHint`: only the computer's owner changes
75
+ the limits, on that computer, with `capybara-device ceiling set -c <device id> …` (the
76
+ connection's real id). Its revision is a hash of everything it is made
61
77
  of plus the machine epoch (moved when the machine is revoked or replaced), the instance
62
78
  generation, its runtime identity and its stored support; times and connection ids are left out,
63
79
  so a reconnect with the same facts keeps it. After a hello or event moved the revision the
64
80
  provider calls `ctx.devices.reportChanged`; after a create or resume the kernel reads the report
65
81
  again itself.
82
+ - **Shared project directories.** The machine's policy summary (hello and `policy` event) may carry
83
+ `sharedProjectRoots`: this connection's project directories another connection on the same
84
+ computer also uses, only those the owner listed in this connection's `projectPaths`, never naming
85
+ the other connection. The report lists them as "Also used by another connection on this
86
+ computer" (no line when none, or from an older device). They are left out of the revision: the
87
+ kernel moves the device authority epoch on every new revision and they change nothing the device
88
+ may do, so a change calls `ctx.devices.reportChanged` once with the revision kept and the kernel
89
+ stores the new text without invalidating approvals. A stale or conflicting `policy` event never
90
+ changes them; an unreadable summary, or an unreadable list in a readable one, keeps them. The
91
+ line fits as many whole directories as it can, skipping one too long, then `+N more` (Chinese:
92
+ `;另有 N 个`) for the rest, within the 60-character limit in each language. Every limit value is
93
+ English and Chinese text (`DeviceReportLimit.value` is `DeviceText`); pure numbers carry English
94
+ only.
95
+ - **Refused project paths.** A machine's `project_refused` outcome becomes
96
+ `ProjectPathRefusedError` with the fixed English and Chinese text of its refusal code
97
+ (`other-connection`, `outside-reach`, `denied`; `PROJECT_REFUSAL_TEXT`): the machine is not
98
+ trusted, so its message text never reaches the person.
66
99
  - **`permissionSupport()`** answers from the rows only, never a machine round trip: the support the
67
100
  machine attested for the installed binding, with outside-the-sandbox and the open public
68
101
  internet narrowed to what the owner allows now (no open public internet while the owner's
69
- network is an allowlist or the owner facts are blocked or missing); closed when no binding is
70
- installed or no hello is stored.
102
+ network is an allowlist or the owner facts are blocked or missing), and `limitedBy` naming the
103
+ owner for each crossing the machine attested but the owner keeps closed (so the kernel names the
104
+ owner's limit, not the provider's); closed when no binding is installed or no hello is stored.
71
105
 
72
106
  A handle the machine will never serve again (the device's binding is a newer generation, or the
73
107
  machine's last hello did not attest it) still reads its installed support, because the kernel
@@ -83,10 +117,9 @@ on it.
83
117
 
84
118
  ## Connecting a computer
85
119
 
86
- The member guide `guides/connect.md` (place `device-connection`, with the desktop app's
87
- `connect-this-machine` action): `npm install -g @capybara-hq/device@next`,
88
- `capybara-device login --url <deployment>`, then `capybara-device service install` and
89
- `service start` (or `capybara-device start` in the foreground). Dial-in limits are the kernel's
120
+ The member guide `guides/connect.md` (place `device-connection`): `npm install -g @capybara-hq/device@next`,
121
+ `capybara-device login --url <deployment>`, then `capybara-device service install -c <device id>`
122
+ (it also starts the service; or `capybara-device start -c <device id>` in the foreground). Dial-in limits are the kernel's
90
123
  `CAPYBARA_DEVICES__DIAL_IN__*` settings.
91
124
 
92
125
  ## Existing local devices
package/dist/index.mjs CHANGED
@@ -49,7 +49,7 @@ var canonicalReport = (r) => ({
49
49
  outsideSandbox: r.outsideSandbox,
50
50
  network: r.network,
51
51
  allowedDomains: [...r.allowedDomains],
52
- restrictedProjectReach: r.restrictedProjectReach
52
+ projectReach: r.projectReach
53
53
  });
54
54
  var sameOwnerReport = (a, b) => JSON.stringify(canonicalReport(a)) === JSON.stringify(canonicalReport(b));
55
55
  function decideOwnerReport(stored, incoming) {
@@ -61,7 +61,7 @@ function decideOwnerReport(stored, incoming) {
61
61
  }
62
62
  var FAIL_CLOSED = {
63
63
  outsideSandbox: false,
64
- restrictedProjectReach: "workspace",
64
+ projectReach: "workspace",
65
65
  allowedDomains: [],
66
66
  network: "allowlist"
67
67
  };
@@ -77,7 +77,7 @@ function ownerFactsOf(stored) {
77
77
  return {
78
78
  state: "report",
79
79
  outsideSandbox: stored.report.outsideSandbox,
80
- restrictedProjectReach: stored.report.restrictedProjectReach,
80
+ projectReach: stored.report.projectReach,
81
81
  allowedDomains: [...stored.report.allowedDomains],
82
82
  network: stored.report.network,
83
83
  revision: stored.report.revision,
@@ -101,7 +101,12 @@ function applyOwnerReport(stored, incoming, via, now) {
101
101
 
102
102
  // src/report.ts
103
103
  import { createHash } from "node:crypto";
104
- import { parseSandboxPermissionSupport } from "@capybara-hq/plugin-sdk/device-protocol";
104
+ import {
105
+ DEVICE_REPORT_LIMITS
106
+ } from "@capybara-hq/plugin-sdk";
107
+ import {
108
+ parseSandboxPermissionSupport
109
+ } from "@capybara-hq/plugin-sdk/device-protocol";
105
110
  function closedSupport(unavailableReason) {
106
111
  return parseSandboxPermissionSupport({
107
112
  version: 2,
@@ -148,7 +153,7 @@ function revisionFacts(c, b) {
148
153
  sequence: owner.sequence,
149
154
  revision: owner.revision,
150
155
  outsideSandbox: owner.outsideSandbox,
151
- reach: owner.restrictedProjectReach,
156
+ projectReach: owner.projectReach,
152
157
  network: owner.network,
153
158
  allowedDomains: [...owner.allowedDomains].sort()
154
159
  }
@@ -167,7 +172,72 @@ function revisionFacts(c, b) {
167
172
  };
168
173
  }
169
174
  var revisionOf = (c, b) => createHash("sha256").update(JSON.stringify(revisionFacts(c, b))).digest("hex");
175
+ function sharedRootsOf(policy, prev) {
176
+ if (policy?.sharedProjectRoots === void 0) return [...prev];
177
+ return [...new Set(policy.sharedProjectRoots)].sort();
178
+ }
179
+ var sameRoots = (a, b) => a.length === b.length && a.every((r, i) => r === b[i]);
180
+ var reportMoved = (before, after) => revisionOf(before.connection, before.binding) !== revisionOf(after.connection, after.binding) || !sameRoots(
181
+ before.connection?.sharedProjectRoots ?? [],
182
+ after.connection?.sharedProjectRoots ?? []
183
+ );
184
+ var SHARED_LABEL = {
185
+ en: "Also used by another connection on this computer",
186
+ zh: "本机的另一个连接也在使用"
187
+ };
188
+ function sharedRootsValue(roots) {
189
+ return {
190
+ en: fitRoots(roots, (n) => ` +${n} more`),
191
+ zh: fitRoots(roots, (n) => `;另有 ${n} 个`)
192
+ };
193
+ }
194
+ function fitRoots(roots, more) {
195
+ const max = DEVICE_REPORT_LIMITS.limitValueChars;
196
+ const rest = (n) => n > 0 ? more(n) : "";
197
+ const kept = [];
198
+ for (const root of roots) {
199
+ const value = `${[...kept, root].join(", ")}${rest(roots.length - kept.length - 1)}`;
200
+ if (value.length <= max) kept.push(root);
201
+ }
202
+ if (kept.length > 0) return `${kept.join(", ")}${rest(roots.length - kept.length)}`;
203
+ const shortest = roots.reduce(
204
+ (best, r) => best === void 0 || r.length < best.length ? r : best,
205
+ void 0
206
+ );
207
+ const left = rest(roots.length - 1);
208
+ const chars = Array.from(shortest ?? "");
209
+ let tail = "";
210
+ for (let i = chars.length - 1; i >= 0; i--) {
211
+ const next = `${chars[i]}${tail}`;
212
+ if (`…${next}${left}`.length > max) break;
213
+ tail = next;
214
+ }
215
+ return `…${tail}${left}`;
216
+ }
170
217
  var hosts = (n) => n === 1 ? { en: "1 allowed host", zh: "允许 1 个主机" } : { en: `${n} allowed hosts`, zh: `允许 ${n} 个主机` };
218
+ var effectiveReach = (mode, reach) => mode === "docker" ? "workspace" : reach;
219
+ var READS = {
220
+ machine: {
221
+ en: "Reads the whole machine except secrets and other connections; writes only in the project and workspace",
222
+ zh: "读取本机全部文件(密钥和其他连接除外);只在项目和工作区写入"
223
+ },
224
+ paths: {
225
+ en: "Reads only the project directories the machine's owner listed; writes only in the project and workspace",
226
+ zh: "只读取本机所有者列出的项目目录;只在项目和工作区写入"
227
+ },
228
+ workspace: { en: "Reads and writes only the device's workspace", zh: "只读写设备的工作区" }
229
+ };
230
+ function describeLocalDevice(c) {
231
+ const reads = READS[effectiveReach(c.mode, c.projectReach)];
232
+ const outside = c.outsideSandbox ? {
233
+ en: "runs outside the sandbox only per approved call",
234
+ zh: "仅在获批的单次调用中在沙箱外运行"
235
+ } : {
236
+ en: "the machine's owner keeps every call in the sandbox",
237
+ zh: "本机所有者让每个调用都留在沙箱内"
238
+ };
239
+ return { en: `${reads.en}; ${outside.en}`, zh: `${reads.zh};${outside.zh}` };
240
+ }
171
241
  function describe(c, owner) {
172
242
  const docker = c.mode === "docker";
173
243
  if (owner.state !== "report")
@@ -175,40 +245,59 @@ function describe(c, owner) {
175
245
  en: "The computer's owner settings are unreadable or arrived out of order, so it runs as narrowly as possible (workspace only, never outside the sandbox) until it reports them again.",
176
246
  zh: "电脑所有者的设置无法读取或报告顺序异常,在重新报告前按最窄的方式运行(只用工作区,从不在沙箱外运行)。"
177
247
  };
178
- const reach = owner.restrictedProjectReach === "os-user" ? {
179
- en: "Reads the whole computer except secrets; writes only in the project",
180
- zh: "读取整台电脑(密钥除外),只在项目中写入"
181
- } : { en: "Reads and writes only in its workspace", zh: "只在工作区内读写" };
182
- const outside = owner.outsideSandbox ? {
183
- en: "runs outside the sandbox only per approved call",
184
- zh: "仅对批准的单次调用在沙箱外运行"
185
- } : { en: "never runs outside the sandbox", zh: "从不在沙箱外运行" };
248
+ const what = describeLocalDevice({
249
+ projectReach: owner.projectReach,
250
+ outsideSandbox: owner.outsideSandbox,
251
+ mode: c.mode
252
+ });
186
253
  const net = owner.network === "open" ? { en: "the open internet", zh: "开放的互联网" } : hosts(owner.allowedDomains.length);
187
254
  return {
188
- en: `${docker ? "In a Docker container: " : ""}${reach.en}; ${outside.en}; network: ${net.en}.`,
189
- zh: `${docker ? "在 Docker 容器中:" : ""}${reach.zh};${outside.zh};网络:${net.zh}。`
255
+ en: `${docker ? "In a Docker container: " : ""}${what.en}; network: ${net.en}.`,
256
+ zh: `${docker ? "在 Docker 容器中:" : ""}${what.zh};网络:${net.zh}。`
190
257
  };
191
258
  }
259
+ var REACH_VALUE = {
260
+ machine: { en: "machine", zh: "整台机器" },
261
+ paths: { en: "listed directories", zh: "列出的目录" },
262
+ workspace: { en: "workspace", zh: "工作区" }
263
+ };
264
+ var MODE_VALUE = {
265
+ os: { en: "os", zh: "本机系统" },
266
+ docker: { en: "docker", zh: "Docker 容器" }
267
+ };
268
+ var NETWORK_VALUE = {
269
+ open: { en: "open", zh: "开放互联网" },
270
+ allowlist: { en: "allowlist", zh: "白名单" }
271
+ };
192
272
  function limitsOf(c, owner) {
193
273
  const lines = [
194
- { label: { en: "Mode", zh: "模式" }, value: c.mode },
274
+ { label: { en: "Mode", zh: "模式" }, value: MODE_VALUE[c.mode] },
195
275
  {
196
276
  label: { en: "Outside the sandbox", zh: "沙箱外运行" },
197
- value: owner.outsideSandbox ? "per approved call" : "off"
277
+ value: owner.outsideSandbox ? { en: "per approved call", zh: "仅限获批的单次调用" } : { en: "off", zh: "关闭" }
198
278
  },
199
279
  {
200
280
  label: { en: "Project reach", zh: "项目范围" },
201
- value: owner.restrictedProjectReach === "os-user" ? "machine" : "workspace"
281
+ value: REACH_VALUE[effectiveReach(c.mode, owner.projectReach)]
202
282
  },
203
- { label: { en: "Network", zh: "网络" }, value: owner.network }
283
+ { label: { en: "Network", zh: "网络" }, value: NETWORK_VALUE[owner.network] }
204
284
  ];
205
285
  if (owner.network === "allowlist")
206
286
  lines.push({
207
287
  label: { en: "Allowed hosts", zh: "允许的主机" },
208
- value: String(owner.allowedDomains.length)
288
+ value: { en: String(owner.allowedDomains.length) }
209
289
  });
290
+ if (c.sharedProjectRoots.length > 0)
291
+ lines.push({ label: SHARED_LABEL, value: sharedRootsValue(c.sharedProjectRoots) });
210
292
  return lines;
211
293
  }
294
+ function localChangeHint(deviceId) {
295
+ const command = `capybara-device ceiling set -c ${deviceId} --outside-sandbox on|off --network open|allowlist --project-reach machine|paths|workspace`;
296
+ return {
297
+ en: `Only the owner of the computer changes these limits, on that computer: ${command}`,
298
+ zh: `只有这台电脑的所有者能在电脑上更改这些限制:${command}`
299
+ };
300
+ }
212
301
  function deviceReportOf(c, b) {
213
302
  const revision = revisionOf(c, b);
214
303
  if (!c)
@@ -230,7 +319,8 @@ function deviceReportOf(c, b) {
230
319
  home: c.mode === "os" ? c.home : null,
231
320
  limits: limitsOf(c, owner),
232
321
  // the files are the machine owner's directory: the provider never resets them
233
- reset: false
322
+ reset: false,
323
+ changeHint: localChangeHint(c.deviceId)
234
324
  };
235
325
  }
236
326
  function supportOf(h, c, b) {
@@ -242,17 +332,20 @@ function supportOf(h, c, b) {
242
332
  if (!c)
243
333
  return closedSupport("The machine has not said hello yet; connect it with capybara-device");
244
334
  const owner = ownerFactsOf(c.ownerReport);
245
- const attested = b.installed.permissionSupport;
335
+ const { limitedBy: _attested, ...attested } = b.installed.permissionSupport;
336
+ const ownerOpen = owner.state === "report" && owner.network === "open";
337
+ const limitedBy = {
338
+ ...attested.outsideSandbox && !owner.outsideSandbox && { outsideSandbox: "owner" },
339
+ ...attested.network.openPublic && !ownerOpen && { openPublic: "owner" }
340
+ };
246
341
  return parseSandboxPermissionSupport({
247
342
  ...attested,
248
343
  // never wider than the owner allows now (a ceiling change since the binding narrows it)
249
344
  outsideSandbox: attested.outsideSandbox && owner.outsideSandbox,
250
345
  // the open public internet only while the owner's sandbox network is open (an allowlist, or
251
346
  // blocked or missing facts, narrow every command's egress on the machine)
252
- network: {
253
- ...attested.network,
254
- openPublic: attested.network.openPublic && owner.state === "report" && owner.network === "open"
255
- }
347
+ network: { ...attested.network, openPublic: attested.network.openPublic && ownerOpen },
348
+ ...Object.keys(limitedBy).length > 0 && { limitedBy }
256
349
  });
257
350
  }
258
351
  async function reportFor(store, device) {
@@ -337,6 +430,8 @@ function decideHello(s, deviceId, hello, conn, now) {
337
430
  features: [...hello.features ?? []],
338
431
  permissionSupport: hello.permissionSupport,
339
432
  ownerReport: applied.next ?? stored?.ownerReport ?? null,
433
+ // a hello restarts what the machine said: an unreadable summary shows none
434
+ sharedProjectRoots: sharedRootsOf(hello.policy, []),
340
435
  instanceGeneration: gen,
341
436
  runtimeIdentity: hello.runtimeIdentity ?? null
342
437
  };
@@ -375,8 +470,10 @@ function createDialInHandler(ctx, store, now = () => (/* @__PURE__ */ new Date()
375
470
  const out = await store.change(deviceId, (s) => {
376
471
  const c = fn(s);
377
472
  if ("ok" in c) return { result: c };
378
- const before = revisionOf(s.connection, s.binding);
379
- moved = before !== revisionOf(c.connection ?? s.connection, c.binding ?? s.binding);
473
+ moved = reportMoved(s, {
474
+ connection: c.connection ?? s.connection,
475
+ binding: c.binding ?? s.binding
476
+ });
380
477
  return c;
381
478
  });
382
479
  if (moved) await tell(deviceId);
@@ -403,10 +500,13 @@ function createDialInHandler(ctx, store, now = () => (/* @__PURE__ */ new Date()
403
500
  return { ok: true };
404
501
  },
405
502
  /**
406
- * A `policy` event: the owner changed the machine's ceiling while connected. Recorded through
407
- * the owner-report rule (stale ignored, conflicting blocks); an invalid body is logged and
408
- * dropped (the kernel keeps the connection; the machine's own enforcement stands), and so is a
409
- * frame of any connection other than the one whose hello was recorded last.
503
+ * A `policy` event: the owner changed the machine's ceiling or policy while connected. The
504
+ * ceiling is recorded through the owner-report rule (stale ignored, conflicting blocks); the
505
+ * summary's shared project directories are taken only with a current ceiling (recorded or the
506
+ * same again; an unreadable summary keeps them), never from a stale or conflicting event. An
507
+ * invalid body is logged and dropped (the kernel keeps the connection; the machine's own
508
+ * enforcement stands), and so is a frame of any connection other than the one whose hello was
509
+ * recorded last.
410
510
  */
411
511
  async onFrame(deviceId, frame, conn) {
412
512
  let event;
@@ -426,7 +526,12 @@ function createDialInHandler(ctx, store, now = () => (/* @__PURE__ */ new Date()
426
526
  );
427
527
  if (applied.outcome === "conflict")
428
528
  ctx.log.warn("a machine's owner report conflicts with the recorded one", { deviceId });
429
- return applied.next ? { result: applied.outcome, connection: { ...s.connection, ownerReport: applied.next } } : { result: applied.outcome };
529
+ const current = applied.outcome === "recorded" || applied.outcome === "same";
530
+ const sharedProjectRoots = current ? sharedRootsOf(event.policy, s.connection.sharedProjectRoots) : s.connection.sharedProjectRoots;
531
+ return applied.next ? {
532
+ result: applied.outcome,
533
+ connection: { ...s.connection, ownerReport: applied.next, sharedProjectRoots }
534
+ } : { result: applied.outcome };
430
535
  });
431
536
  },
432
537
  /**
@@ -455,6 +560,7 @@ function createDialInHandler(ctx, store, now = () => (/* @__PURE__ */ new Date()
455
560
  }
456
561
 
457
562
  // src/pg-rows.ts
563
+ import { validateAllowHost } from "@capybara-hq/plugin-sdk";
458
564
  import {
459
565
  parseOwnerCeilingReport as parseOwnerCeilingReport2,
460
566
  parseSandboxPermissionSupport as parseSandboxPermissionSupport2
@@ -4190,9 +4296,30 @@ function installedOf(r) {
4190
4296
  return void 0;
4191
4297
  }
4192
4298
  }
4299
+ var isCount = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
4300
+ function limitsOf2(v) {
4301
+ const o = json(v);
4302
+ if (!o || typeof o !== "object") return void 0;
4303
+ const n = o.network;
4304
+ if (!isCount(o.cpu) || !isCount(o.memoryMb) || !isCount(o.diskMb) || !n || typeof n !== "object" || n.kind !== "open-public" && n.kind !== "allowlist" || !Array.isArray(n.hosts) || !n.hosts.every((h) => typeof h === "string" && validateAllowHost(h).length === 0))
4305
+ return void 0;
4306
+ return {
4307
+ cpu: o.cpu,
4308
+ memoryMb: o.memoryMb,
4309
+ diskMb: o.diskMb,
4310
+ network: { kind: n.kind, hosts: [...n.hosts] }
4311
+ };
4312
+ }
4313
+ function tokenOf(v) {
4314
+ if (v === null || v === void 0) return void 0;
4315
+ const t = Number(v);
4316
+ return Number.isSafeInteger(t) && t >= 0 ? t : void 0;
4317
+ }
4193
4318
  function bindingOf(r) {
4194
4319
  if (!r) return null;
4195
4320
  const installed = r.status === "installed" ? installedOf(r) : void 0;
4321
+ const limits = limitsOf2(r.limits);
4322
+ const fenceToken = tokenOf(r.fence_token);
4196
4323
  return {
4197
4324
  deviceId: String(r.device_id),
4198
4325
  instanceId: String(r.instance_id),
@@ -4202,7 +4329,9 @@ function bindingOf(r) {
4202
4329
  // an installed row whose facts are unreadable admits nothing until a binding answer again
4203
4330
  status: installed ? "installed" : "awaiting-device",
4204
4331
  ...installed && { installed },
4205
- ...installed && r.unattested === true && { unattested: true }
4332
+ ...installed && r.unattested === true && { unattested: true },
4333
+ ...limits && { limits },
4334
+ ...fenceToken !== void 0 && { fenceToken }
4206
4335
  };
4207
4336
  }
4208
4337
  var UNREADABLE_SUPPORT = parseSandboxPermissionSupport2({
@@ -4238,6 +4367,7 @@ function connectionOf(r) {
4238
4367
  features: FEATURES.filter((f) => features.includes(f)),
4239
4368
  permissionSupport,
4240
4369
  ownerReport: storedOwnerReportOf(json(r.owner_report)),
4370
+ sharedProjectRoots: Array.isArray(r.shared_project_roots) ? r.shared_project_roots.filter((p) => typeof p === "string") : [],
4241
4371
  instanceGeneration: typeof r.instance_generation === "string" ? r.instance_generation : null,
4242
4372
  runtimeIdentity: identityOf(r.runtime_identity)
4243
4373
  };
@@ -4263,6 +4393,7 @@ async function writeConnection(db, c) {
4263
4393
  features: c.features,
4264
4394
  permission_support: JSON.stringify(c.permissionSupport),
4265
4395
  owner_report: c.ownerReport === null ? null : JSON.stringify(c.ownerReport),
4396
+ shared_project_roots: c.sharedProjectRoots,
4266
4397
  instance_generation: c.instanceGeneration,
4267
4398
  runtime_identity: c.runtimeIdentity === null ? null : JSON.stringify(c.runtimeIdentity),
4268
4399
  updated_at: sql`now()`
@@ -4288,6 +4419,8 @@ async function writeBinding(db, b) {
4288
4419
  permission_support: b.installed ? JSON.stringify(b.installed.permissionSupport) : null,
4289
4420
  owner_ceiling: b.installed ? JSON.stringify(b.installed.ownerCeiling) : null,
4290
4421
  unattested: b.unattested === true,
4422
+ limits: b.limits === void 0 ? null : JSON.stringify(b.limits),
4423
+ fence_token: b.fenceToken ?? null,
4291
4424
  updated_at: sql`now()`
4292
4425
  };
4293
4426
  const { device_id: _key, ...update } = values;
@@ -4328,8 +4461,9 @@ import {
4328
4461
  parseSandboxPreparationScope,
4329
4462
  SandboxGoneError as SandboxGoneError2,
4330
4463
  SandboxPermissionUnsupportedError as SandboxPermissionUnsupportedError2,
4464
+ StaleFenceError as StaleFenceError2,
4331
4465
  ToolError as ToolError2,
4332
- validateAllowHost
4466
+ validateAllowHost as validateAllowHost2
4333
4467
  } from "@capybara-hq/plugin-sdk";
4334
4468
 
4335
4469
  // src/bindings.ts
@@ -4342,9 +4476,9 @@ import {
4342
4476
  } from "@capybara-hq/plugin-sdk";
4343
4477
 
4344
4478
  // src/frames.ts
4479
+ import { createHash as createHash2 } from "node:crypto";
4345
4480
  import {
4346
4481
  FileSystemGoneError,
4347
- ProjectPathRefusedError,
4348
4482
  SandboxGoneError,
4349
4483
  SandboxOperationOutcomeUnknownError,
4350
4484
  SandboxPermissionUnsupportedError,
@@ -4357,6 +4491,29 @@ import {
4357
4491
  parseDeviceFrame as parseDeviceFrame2,
4358
4492
  parseOperationResult
4359
4493
  } from "@capybara-hq/plugin-sdk/device-protocol";
4494
+
4495
+ // src/project-refusal.ts
4496
+ import { ProjectPathRefusedError } from "@capybara-hq/plugin-sdk";
4497
+ var PROJECT_REFUSAL_TEXT = Object.freeze({
4498
+ "other-connection": Object.freeze({
4499
+ en: "This directory belongs to another connection on this machine.",
4500
+ zh: "这个目录属于本机上的另一个连接。"
4501
+ }),
4502
+ "outside-reach": Object.freeze({
4503
+ en: "This directory is outside the project reach the machine's owner set for this device.",
4504
+ zh: "这个目录不在本机所有者为此设备设定的项目范围内。"
4505
+ }),
4506
+ denied: Object.freeze({
4507
+ en: "This directory holds secrets or the device program's own state.",
4508
+ zh: "这个目录存放密钥或设备程序自身的状态。"
4509
+ })
4510
+ });
4511
+ function projectRefusalError(refusal) {
4512
+ const text = PROJECT_REFUSAL_TEXT[refusal];
4513
+ return new ProjectPathRefusedError({ en: text.en, zh: text.zh });
4514
+ }
4515
+
4516
+ // src/frames.ts
4360
4517
  var POLICY_REFUSAL_PREFIX = "Refused by the machine's local policy: ";
4361
4518
  var ON_MACHINE_PREFIX = "On the connected machine: ";
4362
4519
  var EXEC_DEADLINE_MARGIN_MS = 5e3;
@@ -4391,9 +4548,12 @@ function requestOf(op, args) {
4391
4548
  if (op === "bindInstance") return args;
4392
4549
  return void 0;
4393
4550
  }
4394
- var isProjectListing = (op) => op === "list" || op === "scan" || op === "browseList" || op === "browseScan";
4395
4551
  function failureOf(error, op) {
4396
4552
  const { kind, message } = error;
4553
+ if (kind === "project_refused") {
4554
+ if (error.refusal === void 0) return invalidAnswer(op, "a project refusal without a code");
4555
+ return projectRefusalError(error.refusal);
4556
+ }
4397
4557
  switch (kind) {
4398
4558
  case "denied":
4399
4559
  return new SandboxScopeDeniedError(message);
@@ -4410,8 +4570,6 @@ function failureOf(error, op) {
4410
4570
  case "fs_gone":
4411
4571
  return new FileSystemGoneError(message);
4412
4572
  case "policy":
4413
- if (isProjectListing(op))
4414
- return new ProjectPathRefusedError({ en: `${POLICY_REFUSAL_PREFIX}${message}` });
4415
4573
  return new ToolError(
4416
4574
  `${POLICY_REFUSAL_PREFIX}${message} (ask the machine's owner to allow it, or use another way)`
4417
4575
  );
@@ -4419,17 +4577,106 @@ function failureOf(error, op) {
4419
4577
  return new ToolError(`${ON_MACHINE_PREFIX}${message} (check the path or command and retry)`);
4420
4578
  }
4421
4579
  }
4580
+ var SERVICE_OP_DEADLINE_MS = 6e4;
4581
+ var ServiceOpRefusedError = class extends ToolError {
4582
+ constructor(message, refusal) {
4583
+ super(message);
4584
+ this.refusal = refusal;
4585
+ }
4586
+ refusal;
4587
+ };
4588
+ function filesDigestOf(files) {
4589
+ const h = createHash2("sha256");
4590
+ for (const path of Object.keys(files).sort()) {
4591
+ const data = files[path];
4592
+ h.update(`${path}\0${data.byteLength}\0`);
4593
+ h.update(data);
4594
+ }
4595
+ return `sha256:${h.digest("hex")}`;
4596
+ }
4597
+ function serviceFailure(error, op) {
4598
+ const message = typeof error.message === "string" ? error.message : "no message";
4599
+ switch (error.kind) {
4600
+ case "unsupported":
4601
+ return new SandboxPermissionUnsupportedError(
4602
+ `${message} (update capybara-device on that machine to use device services)`
4603
+ );
4604
+ case "denied":
4605
+ return new SandboxScopeDeniedError(message);
4606
+ case "files_needed":
4607
+ return new ServiceOpRefusedError(
4608
+ `The connected machine needs the service files for ${op} (retry with the files)`,
4609
+ "files_needed"
4610
+ );
4611
+ case "invalid":
4612
+ return new ServiceOpRefusedError(
4613
+ `The connected machine refused the ${op} request: ${message} (check the request and retry)`,
4614
+ "invalid"
4615
+ );
4616
+ default:
4617
+ return new ToolError(`${ON_MACHINE_PREFIX}${message} (check the service and retry)`);
4618
+ }
4619
+ }
4620
+ async function serviceCall(dialIn, deviceId, body, opts) {
4621
+ const raw = await dialIn.request(deviceId, body, {
4622
+ timeoutMs: opts.deadlineMs,
4623
+ signal: opts.signal
4624
+ });
4625
+ const res = raw;
4626
+ if (typeof res !== "object" || res === null || typeof res.ok !== "boolean")
4627
+ throw invalidAnswer(body.op, "not a response body");
4628
+ if (!res.ok) {
4629
+ const e = res.error;
4630
+ if (typeof e !== "object" || e === null) throw invalidAnswer(body.op, "no error body");
4631
+ throw serviceFailure(e, body.op);
4632
+ }
4633
+ return res.result;
4634
+ }
4422
4635
 
4423
4636
  // src/store.ts
4637
+ import {
4638
+ StaleFenceError
4639
+ } from "@capybara-hq/plugin-sdk";
4424
4640
  var viaOf = (c) => c ? { machineId: c.machineId, connectionId: c.connectionId } : null;
4425
4641
  var sameVia = (c, via) => c === null || via === null ? c === null && via === null : c.machineId === via.machineId && c.connectionId === via.connectionId;
4642
+ function assertFresh(deviceId, held, token, op) {
4643
+ if (held !== void 0 && held > token)
4644
+ throw new StaleFenceError(
4645
+ `device-local: the device ${deviceId} holds fence ${held}; ${op} carries ${token}`,
4646
+ { current: held }
4647
+ );
4648
+ }
4649
+ var hostKey = (h) => {
4650
+ const l = h.toLowerCase();
4651
+ return l.endsWith(".") ? l.slice(0, -1) : l;
4652
+ };
4653
+ function networkCovers(next, prev) {
4654
+ if (next.kind === "open-public") return true;
4655
+ if (prev.kind === "open-public") return false;
4656
+ const allowed = new Set(next.hosts.map(hostKey));
4657
+ return prev.hosts.every((h) => allowed.has(hostKey(h)));
4658
+ }
4426
4659
  function storeOver(rows, now = () => (/* @__PURE__ */ new Date()).toISOString()) {
4427
4660
  return {
4428
4661
  binding: async (deviceId) => (await rows.read(deviceId)).binding,
4429
- commitBinding: (binding, expectedGeneration) => rows.change(
4430
- binding.deviceId,
4431
- (s) => (s.binding?.generation ?? null) === expectedGeneration ? { result: true, binding } : { result: false }
4432
- ),
4662
+ commitBinding: (binding, expectedGeneration, fence) => rows.change(binding.deviceId, (s) => {
4663
+ if (fence !== void 0)
4664
+ assertFresh(binding.deviceId, s.binding?.fenceToken, fence, "create");
4665
+ return (s.binding?.generation ?? null) === expectedGeneration ? { result: true, binding } : { result: false };
4666
+ }),
4667
+ updateLimits: (deviceId, generation, limits, token, current) => rows.change(deviceId, (s) => {
4668
+ const b = s.binding;
4669
+ assertFresh(deviceId, b?.fenceToken, token, "update");
4670
+ if (b?.generation !== generation) return { result: "gone" };
4671
+ const enforced = b.limits ?? current;
4672
+ const widens = networkCovers(limits.network, enforced.network);
4673
+ const binding = {
4674
+ ...b,
4675
+ fenceToken: token,
4676
+ ...widens && { limits: structuredClone(limits) }
4677
+ };
4678
+ return { result: widens ? "updated" : "recreate", binding };
4679
+ }),
4433
4680
  installBinding: (deviceId, generation, bindingId, installed, via) => rows.change(deviceId, (s) => {
4434
4681
  const b = s.binding;
4435
4682
  if (b?.generation !== generation || b.bindingId !== bindingId) return { result: false };
@@ -4495,7 +4742,7 @@ function createInstanceBindings(call, store, now = Date.now) {
4495
4742
  return { ...kept, status: "installed", installed };
4496
4743
  };
4497
4744
  return {
4498
- async bindNew(deviceId, signal) {
4745
+ async bindNew(deviceId, signal, seed) {
4499
4746
  signal.throwIfAborted();
4500
4747
  const current = await store.binding(deviceId);
4501
4748
  const previous = current?.generation ?? null;
@@ -4505,9 +4752,10 @@ function createInstanceBindings(call, store, now = Date.now) {
4505
4752
  generation: nextGeneration(previous, now()),
4506
4753
  bindingId: randomUUID(),
4507
4754
  previousGeneration: previous,
4508
- status: "awaiting-device"
4755
+ status: "awaiting-device",
4756
+ ...seed && { limits: seed.limits, fenceToken: seed.fence ?? 0 }
4509
4757
  };
4510
- if (!await store.commitBinding(binding, previous))
4758
+ if (!await store.commitBinding(binding, previous, seed?.fence))
4511
4759
  throw new InstanceBindingError(
4512
4760
  "Another instance of this device was created at the same time; retry"
4513
4761
  );
@@ -4552,7 +4800,7 @@ function localHandle(h) {
4552
4800
  const l = h;
4553
4801
  return l.roots && l.limits && typeof l.generation === "string" ? h : void 0;
4554
4802
  }
4555
- var sameRoots = (a, b) => a.workspace === b.workspace && a.skills === b.skills && a.tmp === b.tmp;
4803
+ var sameRoots2 = (a, b) => a.workspace === b.workspace && a.skills === b.skills && a.tmp === b.tmp;
4556
4804
  var bytesOf = (b64) => new Uint8Array(Buffer.from(b64, "base64"));
4557
4805
  var b64Of = (data) => Buffer.from(data).toString("base64");
4558
4806
  var refuseRaw = (method) => async (..._args) => {
@@ -4568,7 +4816,7 @@ function relayer(blocked) {
4568
4816
  return blocked.map((b) => {
4569
4817
  if (b.layer !== "device") return b;
4570
4818
  const h = normalizeHost(b.host);
4571
- return validateAllowHost(h).length > 0 || h.startsWith("*.") ? { ...b, layer: "address" } : b;
4819
+ return validateAllowHost2(h).length > 0 || h.startsWith("*.") ? { ...b, layer: "address" } : b;
4572
4820
  });
4573
4821
  }
4574
4822
  function commandLimits(h, scope) {
@@ -4576,6 +4824,21 @@ function commandLimits(h, scope) {
4576
4824
  const network = scope.network.kind === "open-public" ? { kind: "open-public", hosts: [] } : scope.network.kind === "allowlist" ? { kind: "allowlist", hosts: [...scope.network.hosts] } : scope.network.kind === "none" ? { kind: "allowlist", hosts: [] } : { kind: h.limits.network.kind, hosts: [...h.limits.network.hosts] };
4577
4825
  return { cpu, memoryMb, diskMb, network };
4578
4826
  }
4827
+ var isAbsolutePath = (v) => typeof v === "string" && v.startsWith("/") && !v.includes("\0");
4828
+ function statusOf(v) {
4829
+ const s = v;
4830
+ if (typeof s !== "object" || s === null || typeof s.name !== "string" || s.state !== "running" && s.state !== "stopped" || s.startedAt !== null && typeof s.startedAt !== "string" || typeof s.stateDir !== "string" || s.codeDir !== void 0 && !isAbsolutePath(s.codeDir))
4831
+ throw new ToolError2(
4832
+ "The connected machine sent an invalid service status; update capybara-device on that machine and retry"
4833
+ );
4834
+ return {
4835
+ name: s.name,
4836
+ state: s.state,
4837
+ startedAt: s.startedAt,
4838
+ stateDir: s.stateDir,
4839
+ ...s.codeDir !== void 0 && { codeDir: s.codeDir }
4840
+ };
4841
+ }
4579
4842
  function requireLocal(h) {
4580
4843
  const l = localHandle(h);
4581
4844
  if (!l) throw new SandboxGoneError2("The instance handle is not a connected machine's instance");
@@ -4590,9 +4853,10 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4590
4853
  const l = localHandle(h);
4591
4854
  if (!l) return;
4592
4855
  try {
4593
- if ((await store.binding(l.id))?.generation !== l.generation) return;
4856
+ const b = await store.binding(l.id);
4857
+ if (b?.generation !== l.generation) return;
4594
4858
  if (!await ctx.dialIn.online(l.id)) return;
4595
- await machineCreate(l.id, l.limits, signal);
4859
+ await machineCreate(l.id, b.limits ?? l.limits, signal);
4596
4860
  } catch (e) {
4597
4861
  if (signal.aborted) throw e;
4598
4862
  if (!isDeviceOfflineError(e))
@@ -4611,7 +4875,20 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4611
4875
  throw new SandboxGoneError2(
4612
4876
  "The machine restarted without this instance's binding (for example after an upgrade)"
4613
4877
  );
4614
- return l;
4878
+ return b.limits ? { ...l, limits: b.limits } : l;
4879
+ };
4880
+ const limitsInForce = async (l) => {
4881
+ const b = await store.binding(l.id);
4882
+ return b?.generation === l.generation && b.limits ? b.limits : l.limits;
4883
+ };
4884
+ const assertFence = async (deviceId, fence, op) => {
4885
+ if (fence === null || fence === void 0) return;
4886
+ const held = (await store.binding(deviceId))?.fenceToken;
4887
+ if (held !== void 0 && held > fence.token)
4888
+ throw new StaleFenceError2(
4889
+ `device-local: the device ${deviceId} holds fence ${held}; ${op} carries ${fence.token}`,
4890
+ { current: held }
4891
+ );
4615
4892
  };
4616
4893
  const native = (h, scope, prefix, factorySignal) => {
4617
4894
  const send = (op, args, signal) => call(
@@ -4700,12 +4977,11 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4700
4977
  sessionIsolation: false,
4701
4978
  operation: async (h, input, signal) => {
4702
4979
  const scope = parseSandboxOperationScope(input);
4703
- await assertLive(h);
4980
+ const l = await assertLive(h);
4704
4981
  const methods = native(h, scope, "", signal);
4705
4982
  return {
4706
4983
  ...methods,
4707
4984
  exec: async (args) => {
4708
- const l = requireLocal(h);
4709
4985
  const { signal: callSignal, ...rest } = args;
4710
4986
  const limits = commandLimits(l, scope);
4711
4987
  const combined = AbortSignal.any([signal, callSignal]);
@@ -4766,10 +5042,31 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4766
5042
  const id = args.fileSystem.id;
4767
5043
  if (deviceIdOfName(args.name) !== id)
4768
5044
  throw new Error(`instance ${args.name} does not belong to file system ${id}`);
5045
+ const fence = args.fence?.token;
5046
+ await assertFence(id, args.fence, "create");
4769
5047
  const roots = await machineCreate(id, args.limits, args.signal);
4770
- const binding = await bindings.bindNew(id, args.signal);
5048
+ const binding = await bindings.bindNew(id, args.signal, { limits: args.limits, fence });
4771
5049
  return { id, roots, limits: args.limits, generation: binding.generation };
4772
5050
  },
5051
+ /**
5052
+ * Applies new limits to the running generation without recreating it, a store write only:
5053
+ * every command already carries its operation's network, and the next `ensureService` sends
5054
+ * the stored network, on which the machine restarts a running service started with another.
5055
+ * A network widening (every enforced host still allowed) is stored with the new resources
5056
+ * (sent with the commands from then on) and `updated`; a narrowing or a call without a fence
5057
+ * (an older kernel) answers `recreate`, since a running service or escalated command could
5058
+ * still reach a removed host. A token lower
5059
+ * than the stored one is refused with `StaleFenceError`, checked and stored in one step.
5060
+ */
5061
+ async update(h, limits, signal, fence) {
5062
+ signal.throwIfAborted();
5063
+ const l = requireLocal(h);
5064
+ if (fence === void 0) return "recreate";
5065
+ const answer = await store.updateLimits(l.id, l.generation, limits, fence.token, l.limits);
5066
+ if (answer === "gone")
5067
+ throw new SandboxGoneError2("The device's machine no longer holds this instance generation");
5068
+ return answer;
5069
+ },
4773
5070
  /**
4774
5071
  * Needs the machine online. Ends any background work a suspension could not reach (the machine
4775
5072
  * was offline then), then re-verifies the generation's binding. `gone` (the kernel recreates the
@@ -4783,14 +5080,18 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4783
5080
  if (!await ctx.dialIn.online(l.id)) throw new DeviceOfflineError(l.id);
4784
5081
  const current = await store.binding(l.id);
4785
5082
  if (current?.generation !== l.generation) return "gone";
4786
- const roots = await machineCreate(l.id, l.limits, signal);
4787
- if (!sameRoots(roots, l.roots)) return "gone";
5083
+ const roots = await machineCreate(l.id, current.limits ?? l.limits, signal);
5084
+ if (!sameRoots2(roots, l.roots)) return "gone";
4788
5085
  return await bindings.rebind(l.id, l.generation, signal) === "bound" ? "resumed" : "gone";
4789
5086
  },
4790
5087
  async suspend(h, signal) {
4791
5088
  await endGenerationWork(h, signal, "suspend");
4792
5089
  },
4793
- async destroy(h, signal) {
5090
+ async destroy(h, signal, fence) {
5091
+ signal.throwIfAborted();
5092
+ const l = localHandle(h);
5093
+ if (l && (await store.binding(l.id))?.generation === l.generation)
5094
+ await assertFence(l.id, fence, "destroy");
4794
5095
  await endGenerationWork(h, signal, "destroy");
4795
5096
  },
4796
5097
  /**
@@ -4800,13 +5101,109 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4800
5101
  async destroyByName(_name, signal) {
4801
5102
  signal.throwIfAborted();
4802
5103
  },
4803
- /** A protocol 5 machine has no broad kill: the kernel revokes exact operations instead. */
5104
+ /** A protocol 6 machine has no broad kill: the kernel revokes exact operations instead. */
4804
5105
  async killAll(_h, signal) {
4805
5106
  signal.throwIfAborted();
4806
5107
  },
4807
5108
  async killTagged(_h, _tags, signal) {
4808
5109
  signal.throwIfAborted();
4809
5110
  },
5111
+ /**
5112
+ * Starts the service on the machine (or finds it running) with the network the generation
5113
+ * enforces now (the binding's limits, which `update` replaces), which the machine compares
5114
+ * with the running service's and restarts it on a change (from the spec it launched).
5115
+ * `ifRunning` starts nothing: a stopped service answers `stopped`.
5116
+ */
5117
+ async ensureService(h, spec, signal, o) {
5118
+ const l = requireLocal(h);
5119
+ const inForce = (await limitsInForce(l)).network;
5120
+ const network = { kind: inForce.kind, hosts: [...inForce.hosts] };
5121
+ const opts2 = { deadlineMs: SERVICE_OP_DEADLINE_MS, signal };
5122
+ if (o?.ifRunning)
5123
+ return statusOf(
5124
+ await serviceCall(
5125
+ ctx.dialIn,
5126
+ l.id,
5127
+ { op: "service.ensure", spec: { name: spec.name }, network, ifRunning: true },
5128
+ opts2
5129
+ )
5130
+ );
5131
+ const filesDigest = filesDigestOf(spec.files);
5132
+ const send = async (files2) => statusOf(
5133
+ await serviceCall(
5134
+ ctx.dialIn,
5135
+ l.id,
5136
+ {
5137
+ op: "service.ensure",
5138
+ network,
5139
+ spec: {
5140
+ name: spec.name,
5141
+ entry: spec.entry,
5142
+ args: spec.args,
5143
+ ...files2 && { files: files2 },
5144
+ ...spec.env && { env: spec.env }
5145
+ },
5146
+ filesDigest
5147
+ },
5148
+ opts2
5149
+ )
5150
+ );
5151
+ try {
5152
+ return await send();
5153
+ } catch (e) {
5154
+ if (!(e instanceof ServiceOpRefusedError)) throw e;
5155
+ }
5156
+ const files = {};
5157
+ let size = 0;
5158
+ for (const [path, data] of Object.entries(spec.files)) {
5159
+ files[path] = b64Of(data);
5160
+ size += files[path].length + path.length;
5161
+ }
5162
+ const cap = await frameCapacity(ctx.dialIn, l.id);
5163
+ if (size + FRAME_ENVELOPE_BYTES > cap)
5164
+ throw new ToolError2(
5165
+ `The service files for ${spec.name} (${size} bytes encoded) do not fit in one frame of the connected machine (${cap} bytes); raise CAPYBARA_DEVICES__DIAL_IN__MAX_FRAME_BYTES on the deployment and the machine, or use a smaller service`
5166
+ );
5167
+ return await send(files);
5168
+ },
5169
+ async stopService(h, name, signal) {
5170
+ const l = requireLocal(h);
5171
+ await serviceCall(
5172
+ ctx.dialIn,
5173
+ l.id,
5174
+ { op: "service.stop", name },
5175
+ { deadlineMs: SERVICE_OP_DEADLINE_MS, signal }
5176
+ );
5177
+ },
5178
+ async serviceStatus(h, name, signal) {
5179
+ const l = requireLocal(h);
5180
+ return statusOf(
5181
+ await serviceCall(
5182
+ ctx.dialIn,
5183
+ l.id,
5184
+ { op: "service.status", name },
5185
+ { deadlineMs: OP_DEADLINE_MS, signal }
5186
+ )
5187
+ );
5188
+ },
5189
+ async serviceRequest(h, name, body, o) {
5190
+ const l = requireLocal(h);
5191
+ const result = await serviceCall(
5192
+ ctx.dialIn,
5193
+ l.id,
5194
+ { op: "service.request", name, body: b64Of(body), timeoutMs: o.timeoutMs },
5195
+ { deadlineMs: o.timeoutMs + EXEC_DEADLINE_MARGIN_MS, signal: o.signal }
5196
+ );
5197
+ if (typeof result?.body !== "string")
5198
+ throw new ToolError2(
5199
+ "The connected machine sent an invalid answer to service.request; update capybara-device on that machine and retry"
5200
+ );
5201
+ return bytesOf(result.body);
5202
+ },
5203
+ async openStream(h, target, signal) {
5204
+ const l = requireLocal(h);
5205
+ return await ctx.dialIn.openStream(l.id, { service: target.service }, { signal });
5206
+ },
4810
5207
  exec: refuseRaw("exec"),
4811
5208
  readFile: refuseRaw("readFile"),
4812
5209
  writeFile: refuseRaw("writeFile"),
@@ -4819,7 +5216,7 @@ function createDeviceLocalProvider(ctx, store, opts = {}) {
4819
5216
  // src/index.ts
4820
5217
  var plugin = defineExtension({
4821
5218
  name: "device-local",
4822
- version: "0.1.0-rc.1",
5219
+ version: "0.1.0-rc.10",
4823
5220
  // ctx.dialIn.capacity and the handlers' connection argument are the rc.56 SDK's
4824
5221
  sdk: "^0.1.0-rc.56",
4825
5222
  provides: [DEVICE_PROVIDER_EXTENSION_POINT],
@@ -4852,6 +5249,7 @@ export {
4852
5249
  ON_MACHINE_PREFIX,
4853
5250
  OP_DEADLINE_MS,
4854
5251
  POLICY_REFUSAL_PREFIX,
5252
+ PROJECT_REFUSAL_TEXT,
4855
5253
  applyOwnerReport,
4856
5254
  closedSupport,
4857
5255
  commandLimits,
@@ -4861,18 +5259,23 @@ export {
4861
5259
  decideHello,
4862
5260
  decideOwnerReport,
4863
5261
  index_default as default,
5262
+ describeLocalDevice,
4864
5263
  deviceIdOfName,
4865
5264
  deviceReportOf,
4866
5265
  failureOf,
5266
+ filesDigestOf,
4867
5267
  frameCapacity,
4868
5268
  machineCall,
4869
5269
  maxReadBytes,
4870
5270
  nextGeneration,
4871
5271
  ownerFactsOf,
4872
5272
  pgRows,
5273
+ projectRefusalError,
4873
5274
  relayer,
4874
5275
  reportFor,
5276
+ reportMoved,
4875
5277
  revisionOf,
5278
+ sharedRootsValue,
4876
5279
  storeOver,
4877
5280
  storedOwnerReportOf,
4878
5281
  supportFor,
package/guides/connect.md CHANGED
@@ -1,10 +1,7 @@
1
1
  # Connect this machine
2
2
 
3
- ::shell-action connect-this-machine Connect this machine
4
-
5
3
  A device on your own computer: the computer connects to the platform with the `capybara-device`
6
- program and serves the device, and you limit what it may do there. In the desktop app, the button
7
- above connects the computer it runs on. Anywhere else, run these steps in a terminal on the
4
+ program and serves the device, and you limit what it may do there. Run these steps in a terminal on the
8
5
  computer you want to connect (macOS or Linux, Node 22.12 or newer; on Windows use WSL).
9
6
 
10
7
  ## 1. Install the program
@@ -27,19 +24,32 @@ another computer into the same device replaces the first one.
27
24
  ## 3. Keep it online
28
25
 
29
26
  ```bash title="Connect at login (recommended)"
30
- capybara-device service install
31
- capybara-device service start
27
+ capybara-device service install -c <device id>
32
28
  ```
33
29
 
34
- Or run `capybara-device start` to connect in the foreground until you stop it. The device shows as
35
- online once the program is connected; while it is offline, agents cannot use it.
30
+ This is the command `login` printed at its end, with your device id: it installs the service,
31
+ starts it right away and connects again at every login. Or run
32
+ `capybara-device start -c <device id>` to connect in the foreground until you stop it. The device
33
+ shows as online once the program is connected; while it is offline, agents cannot use it.
34
+
35
+ **If this computer is already connected elsewhere.** Each device this computer serves is one
36
+ connection, kept under its device id, with its own service. Choosing a new device in the browser, or
37
+ moving a device here from another computer, adds a connection; signing in again to a device this
38
+ computer already serves keeps its connection (only the sign-in is renewed; then run
39
+ `capybara-device service restart -c <device id>` if its service is installed). With more than one
40
+ connection every command needs `-c <device id>` (or the device name or host, when it is unique);
41
+ with only one, `-c` may be left out. `capybara-device status` lists the connections with their ids,
42
+ and `login` prints the exact next command, id included, at its end.
36
43
 
37
44
  ## What it may do
38
45
 
39
46
  Commands run in a sandbox on your computer, inside the device's directory
40
47
  (`~/capybara-device/<device id>`). You set the owner ceiling on the computer:
41
- `capybara-device ceiling show` shows it, `capybara-device ceiling set` changes it (running outside
42
- the sandbox, the network, project reach). The organization's and the platform's settings apply as
48
+ `capybara-device ceiling show -c <device id>` shows it, `capybara-device ceiling set -c <device id>`
49
+ changes it (running outside the sandbox, the network, project reach); each connection has its own.
50
+ A new connection allows running outside the sandbox: a call that asks to is approved as the
51
+ conversation's permission profile decides; `--outside-sandbox off` keeps every call in the sandbox.
52
+ The organization's and the platform's settings apply as
43
53
  well; the narrowest wins. In OS mode commands run as your user with no CPU or memory limits.
44
54
 
45
55
  Deleting the device revokes the computer's sign-in and stops the program; the files stay on your
@@ -1,8 +1,6 @@
1
1
  # 连接本机
2
2
 
3
- ::shell-action connect-this-machine 连接本机
4
-
5
- 在你自己的电脑上使用的设备:电脑用 `capybara-device` 程序连接到平台并为这台设备服务,由你在本机限制它能做什么。在桌面应用里,点上面的按钮即可连接正在运行它的这台电脑;在其他地方,请在要连接的电脑的终端里依次执行下面的步骤(macOS 或 Linux,Node 22.12 或更高版本;Windows 请使用 WSL)。
3
+ 在你自己的电脑上使用的设备:电脑用 `capybara-device` 程序连接到平台并为这台设备服务,由你在本机限制它能做什么。请在要连接的电脑的终端里依次执行下面的步骤(macOS 或 Linux,Node 22.12 或更高版本;Windows 请使用 WSL)。
6
4
 
7
5
  ## 1. 安装连接程序
8
6
 
@@ -21,15 +19,16 @@ capybara-device login --url {{publicUrl}}
21
19
  ## 3. 保持在线
22
20
 
23
21
  ```bash title="开机自动连接(推荐)"
24
- capybara-device service install
25
- capybara-device service start
22
+ capybara-device service install -c <device id>
26
23
  ```
27
24
 
28
- 也可以运行 `capybara-device start` 在前台连接,直到你停止它。程序连接后设备显示为在线;离线时智能体无法使用它。
25
+ 这就是 `login` 在结尾打印的命令(带着你的设备 id):它会安装服务并立即启动,之后每次登录都会自动连接。也可以运行 `capybara-device start -c <设备 id>` 在前台连接,直到你停止它。程序连接后设备显示为在线;离线时智能体无法使用它。
26
+
27
+ **如果这台电脑已经连接了其他平台或组织。** 这台电脑服务的每台设备对应一个连接,以设备 id 保存,各有自己的服务。在浏览器里选择新建设备,或把另一台电脑上的设备移到这里,都会新增一个连接;重新登录这台电脑已在服务的设备,则沿用原来的连接(只更新登录凭据;若已安装它的服务,接着运行 `capybara-device service restart -c <设备 id>`)。有多个连接时,每条命令都需要加 `-c <设备 id>`(设备名称或主机名唯一时也可以用它们);只有一个连接时可以省略 `-c`。`capybara-device status` 会列出所有连接及其 id,`login` 的结尾会打印带有 id 的下一步命令。
29
28
 
30
29
  ## 它能做什么
31
30
 
32
- 命令在你电脑上的沙箱里运行,位于设备目录(`~/capybara-device/<设备 id>`)内。你在本机设置所有者上限:`capybara-device ceiling show` 查看,`capybara-device ceiling set` 修改(是否允许在沙箱外运行、网络、项目范围)。组织和平台的设置同样生效,以最严格的为准。OS 模式下命令以你的用户身份运行,没有 CPU 和内存限制。
31
+ 命令在你电脑上的沙箱里运行,位于设备目录(`~/capybara-device/<设备 id>`)内。你在本机设置所有者上限:`capybara-device ceiling show -c <设备 id>` 查看,`capybara-device ceiling set -c <设备 id>` 修改(是否允许在沙箱外运行、网络、项目范围),每个连接各有一份。新连接默认允许在沙箱外运行:请求在沙箱外运行的调用按会话的权限模式审批;`--outside-sandbox off` 让每个调用都留在沙箱内。组织和平台的设置同样生效,以最严格的为准。OS 模式下命令以你的用户身份运行,没有 CPU 和内存限制。
33
32
 
34
33
  删除设备会撤销这台电脑的登录并停止程序,文件仍保留在你的电脑上。
35
34
 
@@ -0,0 +1,4 @@
1
+ -- The project directories of the connection that another connection on the same machine also
2
+ -- uses, from the machine's last policy summary (only directories the owner listed for this
3
+ -- connection; never naming the other connection). Shown in the device report only.
4
+ ALTER TABLE connections ADD COLUMN IF NOT EXISTS shared_project_roots text[] NOT NULL DEFAULT '{}';
@@ -0,0 +1,5 @@
1
+ -- The limits the device's instance generation enforces now (those of its create, replaced by
2
+ -- every update that answered "updated"), and the highest fence token a lifecycle call of the
3
+ -- device carried (create seeds it, update raises it; a lower token is a stale holder's).
4
+ ALTER TABLE bindings ADD COLUMN IF NOT EXISTS limits jsonb;
5
+ ALTER TABLE bindings ADD COLUMN IF NOT EXISTS fence_token bigint;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-device-local",
3
- "version": "0.1.0-rc.1",
3
+ "version": "0.1.0-rc.10",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Devices on people's own computers: a machine connected with capybara-device serves the device over the dial-in channel, and its owner limits it there",