@capybara-hq/kernel 0.1.0-rc.49 → 0.1.0-rc.50

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 (128) hide show
  1. package/dist/admin/admin.schemas.d.ts +0 -6
  2. package/dist/background/launch.d.ts +7 -61
  3. package/dist/background/launch.js +8 -133
  4. package/dist/background/poll.job.d.ts +19 -23
  5. package/dist/background/poll.job.js +30 -66
  6. package/dist/background/render.d.ts +9 -0
  7. package/dist/background/render.js +19 -0
  8. package/dist/background/session.d.ts +3 -66
  9. package/dist/background/session.js +3 -114
  10. package/dist/background/stop.d.ts +26 -33
  11. package/dist/background/stop.js +59 -90
  12. package/dist/background/store.d.ts +26 -60
  13. package/dist/background/store.js +23 -108
  14. package/dist/background/tasks.service.d.ts +9 -29
  15. package/dist/background/tasks.service.js +18 -115
  16. package/dist/catalog/marketplaces.service.d.ts +1 -1
  17. package/dist/channels/cards.d.ts +3 -0
  18. package/dist/channels/cards.js +29 -2
  19. package/dist/channels/phrases.d.ts +35 -0
  20. package/dist/channels/phrases.js +32 -0
  21. package/dist/config/load.d.ts +3 -10
  22. package/dist/config/load.js +26 -21
  23. package/dist/config/schema.js +3 -3
  24. package/dist/conversations/events.d.ts +45 -2
  25. package/dist/conversations/events.js +44 -4
  26. package/dist/db/kernel-schema.d.ts +9 -4
  27. package/dist/devices/devices.service.js +1 -1
  28. package/dist/devices/errors.d.ts +5 -0
  29. package/dist/devices/errors.js +5 -0
  30. package/dist/devices/project-rules.d.ts +2 -2
  31. package/dist/errors.d.ts +9 -11
  32. package/dist/errors.js +9 -11
  33. package/dist/identity/settings.d.ts +4 -17
  34. package/dist/identity/settings.js +9 -32
  35. package/dist/infra/config/kernel-config.service.js +2 -9
  36. package/dist/infra/outbox/registry.d.ts +13 -0
  37. package/dist/infra/outbox/registry.js +8 -0
  38. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  39. package/dist/local-devices/device-auth.controller.js +1 -1
  40. package/dist/local-devices/device-auth.d.ts +4 -3
  41. package/dist/local-devices/device-auth.js +1 -1
  42. package/dist/local-devices/device-policy.service.d.ts +6 -6
  43. package/dist/local-devices/device-routes.d.ts +4 -2
  44. package/dist/local-devices/device-routes.js +7 -6
  45. package/dist/local-devices/instance-bindings.d.ts +4 -4
  46. package/dist/local-devices/instance-bindings.js +2 -2
  47. package/dist/local-devices/local-device-gateway.d.ts +12 -12
  48. package/dist/local-devices/local-device-gateway.js +94 -129
  49. package/dist/local-devices/local-device-provider.d.ts +19 -87
  50. package/dist/local-devices/local-device-provider.js +43 -158
  51. package/dist/local-devices/local-devices.module.d.ts +4 -5
  52. package/dist/local-devices/local-devices.module.js +6 -9
  53. package/dist/local-devices/machines.d.ts +6 -6
  54. package/dist/local-devices/machines.js +4 -4
  55. package/dist/local-devices/owner-report.d.ts +3 -3
  56. package/dist/local-devices/owner-report.js +4 -4
  57. package/dist/local-devices/owner-reports.js +2 -2
  58. package/dist/local-devices/policy-summary.js +2 -2
  59. package/dist/local-devices/relay.d.ts +12 -25
  60. package/dist/local-devices/relay.js +17 -31
  61. package/dist/orgs/settings.controller.d.ts +1 -4
  62. package/dist/orgs/settings.controller.js +3 -3
  63. package/dist/orgs/settings.service.d.ts +7 -21
  64. package/dist/orgs/settings.service.js +16 -40
  65. package/dist/overrides.d.ts +3 -3
  66. package/dist/platform/ops/admin.ops.js +6 -8
  67. package/dist/platform/ops/org-settings.ops.js +4 -4
  68. package/dist/platform/ops/orgs.ops.js +0 -1
  69. package/dist/runtime/maintenance.d.ts +1 -1
  70. package/dist/runtime/maintenance.js +7 -1
  71. package/dist/runtime/run-steps.js +2 -2
  72. package/dist/sandbox/held-operations.d.ts +7 -0
  73. package/dist/sandbox/held-operations.js +25 -1
  74. package/dist/sandbox/leases.d.ts +6 -3
  75. package/dist/sandbox/leases.js +16 -10
  76. package/dist/sandbox/legacy-retirement.d.ts +0 -19
  77. package/dist/sandbox/legacy-retirement.js +6 -37
  78. package/dist/sandbox/managed-device-context.d.ts +12 -0
  79. package/dist/sandbox/managed-device-context.js +49 -1
  80. package/dist/sandbox/modes.d.ts +9 -8
  81. package/dist/sandbox/modes.js +4 -15
  82. package/dist/sandbox/operation-authority-types.d.ts +18 -1
  83. package/dist/sandbox/operation-authority-types.js +20 -1
  84. package/dist/sandbox/operation-authority.d.ts +14 -0
  85. package/dist/sandbox/operation-authority.js +120 -18
  86. package/dist/sandbox/operation-intents.d.ts +43 -0
  87. package/dist/sandbox/operation-intents.js +107 -4
  88. package/dist/sandbox/operation-reconcile.job.d.ts +12 -1
  89. package/dist/sandbox/operation-reconcile.job.js +53 -6
  90. package/dist/sandbox/permission-call-grants.d.ts +4 -0
  91. package/dist/sandbox/permission-call-grants.js +32 -3
  92. package/dist/sandbox/permission-call-types.d.ts +27 -2
  93. package/dist/sandbox/permission-ceiling-writes.js +2 -1
  94. package/dist/sandbox/permission-context-types.d.ts +2 -2
  95. package/dist/sandbox/permission-context-types.js +2 -2
  96. package/dist/sandbox/permission-facts.js +10 -2
  97. package/dist/sandbox/platform-full-access.d.ts +8 -26
  98. package/dist/sandbox/platform-full-access.js +8 -20
  99. package/dist/sandbox/review/classifier.d.ts +2 -2
  100. package/dist/sandbox/review/classifier.js +18 -5
  101. package/dist/sandbox/review/permission-candidate.d.ts +59 -3
  102. package/dist/sandbox/review/permission-candidate.js +192 -25
  103. package/dist/sandbox/review/review.service.d.ts +18 -0
  104. package/dist/sandbox/review/review.service.js +158 -12
  105. package/dist/sandbox/sandbox.service.d.ts +71 -47
  106. package/dist/sandbox/sandbox.service.js +234 -133
  107. package/dist/tools/approvals.service.d.ts +6 -1
  108. package/dist/tools/approvals.service.js +10 -0
  109. package/dist/tools/builtins/builtin-tools.d.ts +1 -4
  110. package/dist/tools/builtins/builtin-tools.js +13 -18
  111. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  112. package/dist/tools/builtins/sandbox/bash.js +92 -270
  113. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  114. package/dist/tools/builtins/sandbox/common.js +55 -19
  115. package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
  116. package/dist/tools/builtins/sandbox/device-owner.js +14 -0
  117. package/dist/tools/builtins/sandbox/task-list.js +2 -2
  118. package/dist/tools/builtins/sandbox/task-output.d.ts +14 -57
  119. package/dist/tools/builtins/sandbox/task-output.js +88 -210
  120. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
  121. package/dist/tools/builtins/sandbox/task-stop.js +15 -26
  122. package/dist/tools/pipeline.d.ts +31 -2
  123. package/dist/tools/pipeline.js +273 -43
  124. package/dist/tools/registry.d.ts +7 -0
  125. package/package.json +4 -4
  126. package/src/migrations/0162_permission_call_escalation.sql +9 -0
  127. package/dist/background/status.d.ts +0 -35
  128. package/dist/background/status.js +0 -57
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, parseDeviceFrameV3, } from "@capybara-hq/plugin-sdk";
11
+ import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
14
  import { LockService } from "../infra/lock/lock.service.js";
@@ -46,7 +46,7 @@ export const CLAIM_RETRY_MS = 250;
46
46
  /** Traffic marks the machine seen at most this often per connection (the row has its own gate). */
47
47
  const TOUCH_EVERY_MS = 30_000;
48
48
  /**
49
- * Consecutive failed capacity publications on ping after which a staged connection closes (its
49
+ * Consecutive failed capacity publications on ping after which a connection closes (its
50
50
  * transport key lives three pings, so two misses still leave it readable).
51
51
  */
52
52
  const MAX_PUBLISH_FAILURES = 3;
@@ -106,7 +106,6 @@ class DeviceConnection {
106
106
  socket;
107
107
  identity;
108
108
  credential;
109
- staged;
110
109
  token = randomUUID();
111
110
  state = "hello";
112
111
  lease;
@@ -122,15 +121,14 @@ class DeviceConnection {
122
121
  released;
123
122
  /** The hello's record, then each policy frame's, one after another (never rejects). */
124
123
  recorded = Promise.resolve();
125
- constructor(gw, socket, identity, credential, staged = false) {
124
+ constructor(gw, socket, identity, credential) {
126
125
  this.gw = gw;
127
126
  this.socket = socket;
128
127
  this.identity = identity;
129
128
  this.credential = credential;
130
- this.staged = staged;
131
129
  }
132
130
  /**
133
- * The id a staged connection fences requests and results with (sent to the machine in `ready`).
131
+ * The id a connection fences requests and results with (sent to the machine in `ready`).
134
132
  * Random and separate from the lease token, which stays internal to the kernel.
135
133
  */
136
134
  connectionId = randomUUID();
@@ -139,7 +137,7 @@ class DeviceConnection {
139
137
  /** Consecutive failed capacity publications on ping (this socket's own state). */
140
138
  publishFailures = 0;
141
139
  async publishCapacity() {
142
- if (!this.staged || this.effectiveCap === undefined || this.state !== "holding")
140
+ if (this.effectiveCap === undefined || this.state !== "holding")
143
141
  return;
144
142
  if (this.gw.maxFrameBytes() < this.effectiveCap) {
145
143
  await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
@@ -180,12 +178,10 @@ class DeviceConnection {
180
178
  async onFrame(text) {
181
179
  let frame;
182
180
  try {
183
- frame = this.staged
184
- ? parseDeviceFrameV3(text, "device", this.effectiveCap ?? this.gw.maxFrameBytes())
185
- : parseDeviceFrame(text, "device");
186
- if (this.staged &&
187
- this.effectiveCap !== undefined &&
188
- this.gw.maxFrameBytes() < this.effectiveCap)
181
+ // protocol 3 only: a protocol 2 hello (or any frame that is not protocol 3, such as a hello
182
+ // whose protocol differs from the upgrade header's) fails the strict parse and closes 4400
183
+ frame = parseDeviceFrame(text, "device", this.effectiveCap ?? this.gw.maxFrameBytes());
184
+ if (this.effectiveCap !== undefined && this.gw.maxFrameBytes() < this.effectiveCap)
189
185
  throw new Error("Frame capacity changed; reconnect");
190
186
  }
191
187
  catch (e) {
@@ -201,37 +197,25 @@ class DeviceConnection {
201
197
  this.close(DEVICE_CLOSE.protocol, "hello sent twice");
202
198
  return;
203
199
  }
204
- if (frame.protocol !== (this.staged ? 3 : DEVICE_PROTOCOL_VERSION)) {
200
+ if (frame.protocol !== DEVICE_PROTOCOL_VERSION) {
205
201
  this.close(DEVICE_CLOSE.protocol, "unsupported protocol");
206
202
  return;
207
203
  }
208
- if (this.staged) {
209
- if (!("transport" in frame)) {
210
- this.close(DEVICE_CLOSE.protocol, "Expected staged hello");
211
- return;
212
- }
213
- this.effectiveCap = Math.min(frame.transport.maxFrameBytes, this.gw.maxFrameBytes());
214
- if (this.effectiveCap < 1024 || Buffer.byteLength(text) > this.effectiveCap) {
215
- this.close(DEVICE_CLOSE.protocol, "Check frame limits: hello cannot fit");
216
- return;
217
- }
204
+ this.effectiveCap = Math.min(frame.transport.maxFrameBytes, this.gw.maxFrameBytes());
205
+ if (this.effectiveCap < 1024 || Buffer.byteLength(text) > this.effectiveCap) {
206
+ this.close(DEVICE_CLOSE.protocol, "Check frame limits: hello cannot fit");
207
+ return;
218
208
  }
219
209
  clearTimeout(this.helloTimer);
220
210
  this.state = "claiming";
221
- // the raw summary too: the frame parser drops one it cannot read whole, and its
222
- // isolation must still reach the kernel
223
- const rawPolicy = JSON.parse(text).policy;
224
211
  // set before the first await: a policy frame that follows is recorded after the hello
225
212
  this.recorded = (async () => {
226
213
  if (!(await this.claim()))
227
214
  return;
228
215
  try {
229
- // a staged hello carries the authenticated owner report and runtime facts: recorded
230
- // with the connection it opened (the id the machine gets in `ready`)
231
- if (this.staged)
232
- await this.gw.machines.recordHelloV3(this.identity.machineId, frame, this.connectionId);
233
- else
234
- await this.gw.machines.recordHello(this.identity.machineId, frame, rawPolicy);
216
+ // the hello carries the authenticated owner report and runtime facts: recorded with
217
+ // the connection it opened (the id the machine gets in `ready`)
218
+ await this.gw.machines.recordHelloV3(this.identity.machineId, frame, this.connectionId);
235
219
  }
236
220
  catch (e) {
237
221
  this.gw.log.warn("could not record a device hello", {
@@ -245,15 +229,11 @@ class DeviceConnection {
245
229
  }
246
230
  if (frame.type === "policy" && this.state !== "hello") {
247
231
  // after the hello's record and the earlier policy frames, in the order they came
248
- const rawPolicy = JSON.parse(text).policy;
249
232
  this.recorded = this.recorded.then(async () => {
250
233
  if (this.state === "closed")
251
234
  return;
252
235
  try {
253
- if (this.staged)
254
- await this.gw.machines.recordPolicyV3(this.identity.machineId, frame, this.connectionId);
255
- else
256
- await this.gw.machines.recordPolicy(this.identity.machineId, frame.policy, rawPolicy);
236
+ await this.gw.machines.recordPolicyV3(this.identity.machineId, frame, this.connectionId);
257
237
  }
258
238
  catch (e) {
259
239
  this.gw.log.warn("could not record a device policy change", {
@@ -265,7 +245,7 @@ class DeviceConnection {
265
245
  await this.recorded;
266
246
  return;
267
247
  }
268
- if (frame.type !== "res" || this.state === "hello" || (this.staged && !this.ready)) {
248
+ if (frame.type !== "res" || this.state === "hello" || !this.ready) {
269
249
  this.close(DEVICE_CLOSE.protocol, "hello expected");
270
250
  return;
271
251
  }
@@ -285,14 +265,12 @@ class DeviceConnection {
285
265
  // its strict parse. The device's frame was rebuilt by the strict parser; the marker is
286
266
  // dropped from it all the same, so only this gateway's own refusal can carry it
287
267
  const { [GATEWAY_NOT_SENT]: _never, ...frame } = res;
288
- const tagged = this.staged
289
- ? {
290
- ...frame,
291
- connectionId: this.connectionId,
292
- maxFrameBytes: this.effectiveCap,
293
- ...(notSent && { [GATEWAY_NOT_SENT]: true }),
294
- }
295
- : res;
268
+ const tagged = {
269
+ ...frame,
270
+ connectionId: this.connectionId,
271
+ maxFrameBytes: this.effectiveCap,
272
+ ...(notSent && { [GATEWAY_NOT_SENT]: true }),
273
+ };
296
274
  const stored = await this.gw.redis.eval(ACCEPT, 2, deviceTakenKey(res.id), deviceResKey(res.id), this.deviceId, JSON.stringify(tagged));
297
275
  if (Number(stored) !== 1) {
298
276
  this.gw.log.warn("dropping a device result for a request not taken for its device", {
@@ -371,22 +349,20 @@ class DeviceConnection {
371
349
  deviceId: env,
372
350
  machineId: this.identity.machineId,
373
351
  });
374
- if (this.staged) {
375
- const raw = JSON.stringify({
376
- type: "ready",
377
- connectionId: this.connectionId,
378
- maxFrameBytes: this.effectiveCap,
379
- });
380
- if (this.effectiveCap === undefined || Buffer.byteLength(raw) > this.effectiveCap)
381
- throw new Error("Check frame limits: ready cannot fit");
382
- parseDeviceFrameV3(raw, "kernel", this.effectiveCap);
383
- // published before ready: a reader that sees the machine ready also finds its capacity
384
- await this.publishCapacity();
385
- if (this.state !== "holding")
386
- return false;
387
- this.socket.send(raw);
388
- this.ready = true;
389
- }
352
+ const raw = JSON.stringify({
353
+ type: "ready",
354
+ connectionId: this.connectionId,
355
+ maxFrameBytes: this.effectiveCap,
356
+ });
357
+ if (this.effectiveCap === undefined || Buffer.byteLength(raw) > this.effectiveCap)
358
+ throw new Error("Check frame limits: ready cannot fit");
359
+ parseDeviceFrame(raw, "kernel", this.effectiveCap);
360
+ // published before ready: a reader that sees the machine ready also finds its capacity
361
+ await this.publishCapacity();
362
+ if (this.state !== "holding")
363
+ return false;
364
+ this.socket.send(raw);
365
+ this.ready = true;
390
366
  // what was queued while nobody held the machine
391
367
  this.drain();
392
368
  return true;
@@ -421,10 +397,8 @@ class DeviceConnection {
421
397
  }
422
398
  async drainOnce() {
423
399
  const key = deviceReqKey(this.deviceId);
424
- while (this.state === "holding" && (!this.staged || this.ready)) {
425
- if (this.staged &&
426
- this.effectiveCap !== undefined &&
427
- this.gw.maxFrameBytes() < this.effectiveCap) {
400
+ while (this.state === "holding" && this.ready) {
401
+ if (this.effectiveCap !== undefined && this.gw.maxFrameBytes() < this.effectiveCap) {
428
402
  await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
429
403
  return;
430
404
  }
@@ -445,34 +419,26 @@ class DeviceConnection {
445
419
  });
446
420
  continue;
447
421
  }
448
- if (this.staged) {
449
- // a cancel carries no capacity-sized payload and must reach the machine after a
450
- // reconnect too (an operation keeps running across a socket blip, as in protocol 2);
451
- // so does a machine's `stop`, fenced to the machine above instead of the socket
452
- const unfenced = request.type === "cancel" || (request.op === "stop" && stopFor !== undefined);
453
- if (!unfenced &&
454
- (connectionId !== this.connectionId || maxFrameBytes !== this.effectiveCap)) {
455
- if (request.type === "req" && typeof request.id === "string")
456
- await this.store({
457
- type: "res",
458
- id: request.id,
459
- ok: false,
460
- error: {
461
- kind: "error",
462
- message: connectionChangedMessage(String(request.op)),
463
- },
464
- }, true);
465
- continue;
466
- }
467
- wire = JSON.stringify(request);
468
- frame = parseDeviceFrameV3(wire, "kernel", this.effectiveCap);
469
- }
470
- else {
471
- // protocol 2's wire stays byte for byte what the relay queued, minus the stop's fence
472
- if (stopFor !== undefined)
473
- wire = JSON.stringify(request);
474
- frame = parseDeviceFrame(wire, "kernel");
422
+ // a cancel carries no capacity-sized payload and must reach the machine after a
423
+ // reconnect too (an operation keeps running across a socket blip, as in protocol 2);
424
+ // so does a machine's `stop`, fenced to the machine above instead of the socket
425
+ const unfenced = request.type === "cancel" || (request.op === "stop" && stopFor !== undefined);
426
+ if (!unfenced &&
427
+ (connectionId !== this.connectionId || maxFrameBytes !== this.effectiveCap)) {
428
+ if (request.type === "req" && typeof request.id === "string")
429
+ await this.store({
430
+ type: "res",
431
+ id: request.id,
432
+ ok: false,
433
+ error: {
434
+ kind: "error",
435
+ message: connectionChangedMessage(String(request.op)),
436
+ },
437
+ }, true);
438
+ continue;
475
439
  }
440
+ wire = JSON.stringify(request);
441
+ frame = parseDeviceFrame(wire, "kernel", this.effectiveCap);
476
442
  }
477
443
  catch (e) {
478
444
  this.gw.log.warn("dropping an invalid device request", {
@@ -524,21 +490,20 @@ class DeviceConnection {
524
490
  this.socket.ping();
525
491
  // a backstop for a lost nudge (the bus delivers at most once)
526
492
  if (this.state === "holding") {
527
- if (this.staged)
528
- void this.publishCapacity().then(() => {
529
- this.publishFailures = 0;
530
- }, (e) => {
531
- // the key lives three pings: a transient failure is retried on the next ping, and
532
- // only failures that would let the key expire close the connection
533
- this.publishFailures++;
534
- this.gw.log.warn("could not publish a device connection's capacity", {
535
- deviceId: this.deviceId,
536
- failures: this.publishFailures,
537
- error: errMsg(e),
538
- });
539
- if (this.publishFailures >= MAX_PUBLISH_FAILURES)
540
- void this.close(DEVICE_CLOSE.internal, "Capacity publication failed; reconnect");
493
+ void this.publishCapacity().then(() => {
494
+ this.publishFailures = 0;
495
+ }, (e) => {
496
+ // the key lives three pings: a transient failure is retried on the next ping, and
497
+ // only failures that would let the key expire close the connection
498
+ this.publishFailures++;
499
+ this.gw.log.warn("could not publish a device connection's capacity", {
500
+ deviceId: this.deviceId,
501
+ failures: this.publishFailures,
502
+ error: errMsg(e),
541
503
  });
504
+ if (this.publishFailures >= MAX_PUBLISH_FAILURES)
505
+ void this.close(DEVICE_CLOSE.internal, "Capacity publication failed; reconnect");
506
+ });
542
507
  this.drain();
543
508
  }
544
509
  if (this.state === "holding" && Date.now() - this.lastAuth >= REAUTH_EVERY_MS) {
@@ -596,8 +561,7 @@ class DeviceConnection {
596
561
  const lease = this.lease;
597
562
  this.released = (async () => {
598
563
  try {
599
- if (this.staged)
600
- await this.gw.redis.del(deviceTransportKey(this.deviceId, this.token));
564
+ await this.gw.redis.del(deviceTransportKey(this.deviceId, this.token));
601
565
  if (lease) {
602
566
  if (lease.lost.aborted)
603
567
  lease.abandon();
@@ -669,31 +633,36 @@ let LocalDeviceGateway = class LocalDeviceGateway {
669
633
  authenticate(credential) {
670
634
  return this.machines.authenticate(credential);
671
635
  }
672
- /** Serves one upgraded socket of an authenticated machine until it closes. */
673
- accept(socket, identity, credential) {
674
- if (this.stopping) {
675
- socket.close(DEVICE_CLOSE.shutdown, "shutting down");
676
- return;
677
- }
678
- const conn = new DeviceConnection(this, socket, identity, credential);
679
- this.connections.add(conn);
680
- conn.start();
681
- }
682
- /** Dormant authenticated seam; the production HTTP route never calls this until full cutover. */
683
- async acceptStaged(socket, credential) {
636
+ /**
637
+ * Serves one upgraded socket of a machine until it closes (protocol 3 only: the route refused any
638
+ * other header with 426, and a hello that is not protocol 3 closes 4400). The credential is
639
+ * checked again here, with the socket paused, so a credential revoked since the upgrade check
640
+ * never gets a connection.
641
+ */
642
+ async accept(socket, credential) {
684
643
  socket.pause();
685
644
  try {
645
+ if (this.stopping) {
646
+ socket.close(DEVICE_CLOSE.shutdown, "shutting down");
647
+ return;
648
+ }
686
649
  const identity = await this.authenticate(credential);
687
- if (!identity || this.stopping || socket.readyState !== socket.OPEN) {
650
+ if (socket.readyState !== socket.OPEN)
651
+ return;
652
+ if (this.stopping) {
653
+ socket.close(DEVICE_CLOSE.shutdown, "shutting down");
654
+ return;
655
+ }
656
+ if (!identity) {
688
657
  socket.close(DEVICE_CLOSE.revoked, "Reconnect with a current credential");
689
658
  return;
690
659
  }
691
- const conn = new DeviceConnection(this, socket, identity, credential, true);
660
+ const conn = new DeviceConnection(this, socket, identity, credential);
692
661
  this.connections.add(conn);
693
662
  conn.start();
694
663
  }
695
664
  catch (error) {
696
- this.log.warn("could not authenticate staged device connection", { error: errMsg(error) });
665
+ this.log.warn("could not authenticate a device connection", { error: errMsg(error) });
697
666
  socket.close(DEVICE_CLOSE.internal, "Authentication unavailable; reconnect");
698
667
  }
699
668
  finally {
@@ -732,7 +701,3 @@ LocalDeviceGateway = __decorate([
732
701
  __param(5, Inject(KERNEL_LOGGER))
733
702
  ], LocalDeviceGateway);
734
703
  export { LocalDeviceGateway };
735
- /** Staged validation only; active connection acceptance above remains protocol 2. */
736
- export function validateDeviceOperationFrameV3(raw, from) {
737
- return parseDeviceFrameV3(raw, from);
738
- }
@@ -1,10 +1,8 @@
1
- import type { ExecResult, FileSystemHandle, SandboxHandle, SandboxLimits, SandboxProvider, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import { type DeviceOperationV3, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
1
+ import type { FileSystemHandle, SandboxHandle, SandboxLimits, SandboxProvider, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import { type DeviceOperation, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
3
3
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
- import type { KernelLogger } from "../log.js";
5
4
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
6
5
  import { SandboxService } from "../sandbox/sandbox.service.js";
7
- import { NetworkGrants } from "./network-grants.js";
8
6
  import { LocalDeviceRelay } from "./relay.js";
9
7
  import { DeviceTargets } from "./targets.js";
10
8
  /** Extra time the machine gets beyond a command's own timeout (spawn, output, the trip back). */
@@ -20,15 +18,9 @@ export declare const FRAME_ENVELOPE_BYTES: number;
20
18
  export { projectsUnsupported } from "../devices/errors.js";
21
19
  /** The most raw bytes whose base64 plus {@link FRAME_ENVELOPE_BYTES} fit in `maxFrameBytes`. */
22
20
  export declare const maxReadBytes: (maxFrameBytes: number) => number;
23
- /**
24
- * The refusal of a command on a machine whose local policy is auto mode while the organization (or
25
- * the platform) allows only sandbox mode (auto mode spec §4.3): re-checked at every exec, so a
26
- * machine switched locally is refused at the next command.
27
- */
28
- export declare const AUTO_MODE_NOT_ALLOWED_TEXT = "This device's machine runs in auto mode, which your organization does not allow. Run `capybara-device mode sandbox` on that machine to switch it to sandbox mode.";
29
21
  /** What the staged provider sends through: the relay's protocol 3 call and the attested support. */
30
22
  export interface StagedDeviceTransport {
31
- call(deviceId: string, op: DeviceOperationV3, args: Record<string, unknown>, opts: {
23
+ call(deviceId: string, op: DeviceOperation, args: Record<string, unknown>, opts: {
32
24
  deadlineMs: number;
33
25
  signal: AbortSignal;
34
26
  connection?: {
@@ -65,12 +57,10 @@ export declare class LocalDeviceProvider implements SandboxProvider {
65
57
  private readonly targets;
66
58
  private readonly sandbox;
67
59
  private readonly config;
68
- private readonly grants;
69
- private readonly log;
70
60
  private readonly callGrants?;
71
61
  readonly concurrentExec: true;
72
62
  readonly sessionIsolation = false;
73
- constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots" | "machineFeatures">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, grants: Pick<NetworkGrants, "forExec" | "reportedMode">, log: Pick<KernelLogger, "warn">, callGrants?: PermissionCallGrants | undefined);
63
+ constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, callGrants?: PermissionCallGrants | undefined);
74
64
  /**
75
65
  * The `@local` provider as the staged (protocol 3) registration hands it out
76
66
  * (`LocalDevicesModule`): the protocol 2 lifecycle methods that send no frame (file system,
@@ -83,15 +73,12 @@ export declare class LocalDeviceProvider implements SandboxProvider {
83
73
  * missing operation support never falls back to them.
84
74
  *
85
75
  * A v3 machine has no `killAll` / `killTagged` (permission runtime cutover B-1), so both are
86
- * no-ops that queue nothing. What reaches the machine instead is only what the kernel revokes
87
- * exactly (`revokeOperation` per intent): `SandboxService` calls `OperationIntents.revokeHolders`
88
- * with the crashed holders' tokens before `killTagged` and before `killLeftovers`' `killAll`, and
89
- * that revokes those holders' admitted, dispatching and started-or-unknown intents only. Not
90
- * covered today: the `killAll` after a failed limits change on a resumed instance and the one
91
- * in `quarantine` (unreachable for `@local`) revoke nothing first; `killLeftovers` revokes only
92
- * the dead tokens, not the started-or-unknown intents of live holders of the instance; and
93
- * tokens `claimDeadHolders` already deleted are lost when `revokeHolders` then throws. Revoking
94
- * every started-or-unknown intent of the generation on a v3 resume is W5-P3a's kernel change.
76
+ * no-ops that queue nothing; the kernel never calls them anyway. What reaches the machine is
77
+ * only what the kernel revokes exactly (`revokeOperation` per intent): `SandboxService` owes a
78
+ * crashed holder's revocation in an outbox row before it forgets the holder record, revokes that
79
+ * holder's admitted, dispatching and started-or-unknown intents, and, under the exclusive lease
80
+ * on an incarnation nobody else holds (a resume, a failed limits change, a quarantine), every
81
+ * started-or-unknown intent of that generation; the owed revokes are delivered by operation id.
95
82
  */
96
83
  staged(transport: StagedDeviceTransport): SandboxProvider;
97
84
  /** Dormant v3 adapter. It is not installed on the active v2 registered provider. */
@@ -120,68 +107,13 @@ export declare class LocalDeviceProvider implements SandboxProvider {
120
107
  suspend(_h: SandboxHandle, signal: AbortSignal): Promise<void>;
121
108
  destroy(_h: SandboxHandle, signal: AbortSignal): Promise<void>;
122
109
  destroyByName(_name: string, signal: AbortSignal): Promise<void>;
123
- killAll(h: SandboxHandle, signal: AbortSignal): Promise<void>;
124
- killTagged(h: SandboxHandle, tags: string[], signal: AbortSignal): Promise<void>;
125
- /**
126
- * Runs the command on the machine with the org's limits now (ruling R27) and, for a command of a
127
- * run, the hosts the kernel allows that run on this device beyond the local policy (network
128
- * ask-to-allow spec §6.3; only those the org's limits admit, sent only when there are some). The
129
- * device's report of refused hosts is re-layered against the limits this exec carried: the
130
- * kernel never takes the device's word that the org allows a host (auto mode spec §4.2).
131
- *
132
- * The exec args carry `mode: allowedMode` (the machine cuts its own choice to it), the
133
- * sandbox-mode allowlist and the run's grants. A machine whose local policy is auto mode while
134
- * the organization allows only sandbox mode is refused at every exec
135
- * (`device.auto_mode_not_allowed`), before anything is relayed to it.
136
- */
137
- exec(h: SandboxHandle, args: Parameters<SandboxProvider["exec"]>[1]): Promise<ExecResult>;
138
- readFile(h: SandboxHandle, path: string, opts: {
139
- maxBytes: number;
140
- signal: AbortSignal;
141
- }): Promise<{
142
- data: Uint8Array;
143
- truncated: boolean;
144
- } | null>;
145
- writeFile(h: SandboxHandle, path: string, data: Uint8Array, signal: AbortSignal): Promise<void>;
146
- stat(h: SandboxHandle, path: string, signal: AbortSignal): Promise<{
147
- size: number;
148
- isDir: boolean;
149
- } | null>;
150
- /**
151
- * Lists one directory on the machine (the `list` op, project root §4.1), read in the mode the
152
- * kernel's current ceiling gives. A machine that did not announce `projects` throws
153
- * `device.projects_unsupported` (never null, which would read as "does not exist").
154
- */
155
- list(h: SandboxHandle, path: string, opts: {
156
- limit: number;
157
- limits: Pick<SandboxLimits, "mode">;
158
- signal: AbortSignal;
159
- }): Promise<{
160
- entries: {
161
- name: string;
162
- isDir: boolean;
163
- }[];
164
- truncated: boolean;
165
- } | null>;
166
- /**
167
- * Looks for project-like directories under `base` on the machine (the `scan` op, project root
168
- * §4.1), read in the mode the kernel's current ceiling gives. A machine that did not announce
169
- * `projects` throws `device.projects_unsupported`.
170
- */
171
- scan(h: SandboxHandle, base: string, opts: {
172
- limits: Pick<SandboxLimits, "mode">;
173
- signal: AbortSignal;
174
- }): Promise<{
175
- path: string;
176
- suggestedName: string;
177
- }[]>;
178
- /** The kernel never sends `list` or `scan` to a machine that did not announce `projects`. */
179
- private requireProjects;
180
- /**
181
- * The device's org and current limits for an exec or file read (ruling R27): the effective policy's
182
- * `allowedMode` and the sandbox-mode allowlist. A deleted device is not found. A machine whose
183
- * local policy is auto mode while the organization allows only sandbox mode is refused here, at
184
- * every such operation, so a machine switched locally is not used until it is switched back.
185
- */
186
- private currentLimits;
110
+ /** A v3 machine has no broad kill (permission runtime cutover B-1): nothing is queued. */
111
+ killAll(_h: SandboxHandle, signal: AbortSignal): Promise<void>;
112
+ killTagged(_h: SandboxHandle, _tags: string[], signal: AbortSignal): Promise<void>;
113
+ readonly exec: SandboxProvider["exec"];
114
+ readonly readFile: SandboxProvider["readFile"];
115
+ readonly writeFile: SandboxProvider["writeFile"];
116
+ readonly stat: SandboxProvider["stat"];
117
+ readonly list: NonNullable<SandboxProvider["list"]>;
118
+ readonly scan: NonNullable<SandboxProvider["scan"]>;
187
119
  }