@capybara-hq/kernel 0.1.0-rc.65 → 0.1.0-rc.67

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 (177) hide show
  1. package/bootstrap.json +0 -8
  2. package/dist/admin/admin.schemas.d.ts +3 -0
  3. package/dist/agents/admin-agents.d.ts +2 -2
  4. package/dist/agents/admin-agents.js +2 -1
  5. package/dist/agents/agent-lookup.js +2 -1
  6. package/dist/agents/agent-profile.service.d.ts +5 -2
  7. package/dist/agents/agent-profile.service.js +13 -2
  8. package/dist/agents/agents.controller.d.ts +4 -3
  9. package/dist/agents/agents.controller.js +7 -3
  10. package/dist/agents/agents.module.js +3 -0
  11. package/dist/agents/agents.schemas.d.ts +6 -6
  12. package/dist/agents/agents.service.d.ts +23 -2
  13. package/dist/agents/agents.service.js +61 -6
  14. package/dist/agents/avatar-view.d.ts +8 -0
  15. package/dist/agents/avatar-view.js +12 -0
  16. package/dist/agents/profile.d.ts +38 -13
  17. package/dist/agents/profile.js +31 -20
  18. package/dist/attribution/platform-attribution.d.ts +15 -6
  19. package/dist/attribution/platform-attribution.js +31 -14
  20. package/dist/background/poll.job.d.ts +1 -1
  21. package/dist/background/poll.job.js +8 -6
  22. package/dist/background/tasks.service.js +1 -1
  23. package/dist/catalog/catalog-content.d.ts +6 -3
  24. package/dist/catalog/catalog-content.js +7 -8
  25. package/dist/catalog/claude/translate.js +1 -1
  26. package/dist/catalog/marketplaces.service.d.ts +1 -1
  27. package/dist/catalog/marketplaces.service.js +2 -1
  28. package/dist/catalog/plugin-package.d.ts +3 -2
  29. package/dist/channels/file-delivery.d.ts +2 -0
  30. package/dist/channels/file-delivery.js +1 -1
  31. package/dist/channels/inbound.d.ts +8 -4
  32. package/dist/channels/inbound.js +14 -7
  33. package/dist/channels/outbound.js +11 -5
  34. package/dist/channels/phrases.d.ts +21 -13
  35. package/dist/channels/phrases.js +21 -14
  36. package/dist/client/client-files.js +1 -1
  37. package/dist/config/product-name.d.ts +8 -0
  38. package/dist/config/product-name.js +9 -0
  39. package/dist/config/schema.d.ts +1 -0
  40. package/dist/config/schema.js +17 -4
  41. package/dist/conversations/conversations.service.d.ts +4 -3
  42. package/dist/conversations/conversations.service.js +15 -2
  43. package/dist/ctx/create-ctx.js +5 -2
  44. package/dist/ctx/device-provider-check.d.ts +7 -0
  45. package/dist/ctx/device-provider-check.js +21 -0
  46. package/dist/db/kernel-schema.d.ts +7 -0
  47. package/dist/devices/access.d.ts +16 -46
  48. package/dist/devices/access.js +26 -62
  49. package/dist/devices/access.module.js +2 -2
  50. package/dist/devices/conversation-devices.d.ts +38 -18
  51. package/dist/devices/conversation-devices.js +69 -51
  52. package/dist/devices/default-provider-setting.d.ts +45 -0
  53. package/dist/devices/default-provider-setting.js +59 -0
  54. package/dist/devices/device-projects.service.js +7 -2
  55. package/dist/devices/device-provider-selection.d.ts +37 -0
  56. package/dist/devices/device-provider-selection.js +86 -0
  57. package/dist/devices/device-provider-selection.module.d.ts +3 -0
  58. package/dist/devices/device-provider-selection.module.js +22 -0
  59. package/dist/devices/devices.controller.d.ts +8 -5
  60. package/dist/devices/devices.controller.js +7 -4
  61. package/dist/devices/devices.module.js +3 -1
  62. package/dist/devices/devices.schemas.js +2 -2
  63. package/dist/devices/devices.service.d.ts +72 -83
  64. package/dist/devices/devices.service.js +139 -248
  65. package/dist/devices/dto.d.ts +9 -0
  66. package/dist/devices/dto.js +15 -2
  67. package/dist/devices/label.d.ts +3 -5
  68. package/dist/devices/label.js +3 -14
  69. package/dist/devices/legacy-cleanup.job.d.ts +2 -2
  70. package/dist/devices/legacy-cleanup.job.js +6 -6
  71. package/dist/errors.d.ts +15 -1
  72. package/dist/errors.js +15 -1
  73. package/dist/extensions/guide-places.d.ts +2 -1
  74. package/dist/extensions/guide-places.js +8 -2
  75. package/dist/extensions/locks.d.ts +1 -1
  76. package/dist/extensions/locks.js +1 -1
  77. package/dist/extensions/org-config.d.ts +20 -4
  78. package/dist/extensions/org-config.js +23 -6
  79. package/dist/extensions/permission-view.d.ts +2 -2
  80. package/dist/extensions/permission-view.js +2 -2
  81. package/dist/extensions/plugin-guides.d.ts +1 -1
  82. package/dist/extensions/plugin-guides.js +11 -3
  83. package/dist/extensions/point-defaults.d.ts +14 -0
  84. package/dist/extensions/point-defaults.js +70 -47
  85. package/dist/extensions/resolve.js +7 -2
  86. package/dist/git/gateway.d.ts +9 -0
  87. package/dist/git/gateway.js +36 -17
  88. package/dist/git/gateway.route.d.ts +1 -1
  89. package/dist/git/gateway.route.js +1 -3
  90. package/dist/http/app.d.ts +1 -1
  91. package/dist/identity/app-auth.d.ts +4 -3
  92. package/dist/identity/app-auth.js +7 -8
  93. package/dist/identity/settings.d.ts +8 -0
  94. package/dist/identity/settings.js +30 -3
  95. package/dist/identity/sso.d.ts +13 -7
  96. package/dist/identity/sso.js +21 -7
  97. package/dist/infra/config/kernel-config.service.js +3 -1
  98. package/dist/lifecycle/kernel-lifecycle.js +7 -6
  99. package/dist/local-devices/device-routes.d.ts +1 -1
  100. package/dist/local-devices/device-routes.js +2 -2
  101. package/dist/local-devices/local-device-provider.d.ts +14 -11
  102. package/dist/local-devices/local-device-provider.js +14 -0
  103. package/dist/local-devices/local-devices.module.d.ts +4 -4
  104. package/dist/local-devices/local-devices.module.js +5 -3
  105. package/dist/local-devices/owner-report.js +2 -1
  106. package/dist/local-devices/targets.d.ts +2 -0
  107. package/dist/local-devices/targets.js +10 -0
  108. package/dist/orgs/offboarding.js +9 -0
  109. package/dist/orgs/settings.service.d.ts +26 -1
  110. package/dist/orgs/settings.service.js +44 -3
  111. package/dist/platform/ops/admin.ops.js +8 -3
  112. package/dist/platform/ops/agents.ops.d.ts +6 -1
  113. package/dist/platform/ops/agents.ops.js +38 -11
  114. package/dist/platform/ops/devices.ops.js +25 -20
  115. package/dist/platform/ops/orgs.ops.js +1 -0
  116. package/dist/platform/ops/platform-icons.ops.js +4 -4
  117. package/dist/platform/ops/platform.ops.js +2 -1
  118. package/dist/platform/ops/themes.ops.js +1 -1
  119. package/dist/runtime/plugin-context.service.js +1 -12
  120. package/dist/sandbox/cloud-permission-snapshot.d.ts +2 -2
  121. package/dist/sandbox/cloud-permission-snapshot.js +3 -3
  122. package/dist/sandbox/device-reports.d.ts +50 -0
  123. package/dist/sandbox/device-reports.js +157 -0
  124. package/dist/sandbox/held-operations.d.ts +8 -8
  125. package/dist/sandbox/leases.d.ts +1 -1
  126. package/dist/sandbox/leases.js +1 -1
  127. package/dist/sandbox/operation-authority.d.ts +5 -2
  128. package/dist/sandbox/operation-authority.js +12 -11
  129. package/dist/sandbox/operation-reconcile.job.d.ts +2 -2
  130. package/dist/sandbox/operation-reconcile.job.js +5 -5
  131. package/dist/sandbox/permission-availability.d.ts +2 -2
  132. package/dist/sandbox/permission-call-types.d.ts +5 -0
  133. package/dist/sandbox/permission-facts.d.ts +2 -2
  134. package/dist/sandbox/permission-facts.js +5 -5
  135. package/dist/sandbox/providers.d.ts +23 -24
  136. package/dist/sandbox/providers.js +38 -46
  137. package/dist/sandbox/providers.module.js +3 -3
  138. package/dist/sandbox/review/classifier.d.ts +6 -0
  139. package/dist/sandbox/review/classifier.js +12 -1
  140. package/dist/sandbox/review/index.d.ts +1 -1
  141. package/dist/sandbox/review/index.js +1 -1
  142. package/dist/sandbox/sandbox.module.d.ts +1 -1
  143. package/dist/sandbox/sandbox.module.js +7 -2
  144. package/dist/sandbox/sandbox.service.d.ts +95 -68
  145. package/dist/sandbox/sandbox.service.js +212 -208
  146. package/dist/setup/setup-guides.service.d.ts +4 -1
  147. package/dist/setup/setup-guides.service.js +6 -1
  148. package/dist/themes/avatar-preset-key.d.ts +6 -0
  149. package/dist/themes/avatar-preset-key.js +9 -0
  150. package/dist/themes/platform-icon.service.js +1 -1
  151. package/dist/themes/theme-delivery.service.d.ts +10 -2
  152. package/dist/themes/theme-delivery.service.js +26 -11
  153. package/dist/themes/theme-state.d.ts +43 -2
  154. package/dist/themes/theme-state.js +61 -4
  155. package/dist/themes/themes-public.controller.d.ts +3 -3
  156. package/dist/themes/themes-public.controller.js +3 -3
  157. package/dist/themes/themes.service.d.ts +28 -1
  158. package/dist/themes/themes.service.js +36 -2
  159. package/dist/tools/builtins/image/generate.d.ts +3 -0
  160. package/dist/tools/builtins/image/generate.js +21 -11
  161. package/dist/tools/builtins/image/index.d.ts +1 -1
  162. package/dist/tools/builtins/image/index.js +1 -1
  163. package/dist/tools/builtins/platform.js +25 -17
  164. package/dist/tools/builtins/sandbox/common.d.ts +37 -13
  165. package/dist/tools/builtins/sandbox/common.js +63 -19
  166. package/dist/tools/builtins/sandbox/read.d.ts +5 -2
  167. package/dist/tools/builtins/sandbox/read.js +9 -6
  168. package/dist/tools/builtins/sandbox/task-output.d.ts +2 -2
  169. package/dist/tools/builtins/sandbox/task-output.js +6 -5
  170. package/dist/tools/builtins/skill-load.js +13 -4
  171. package/dist/tools/connectors.service.js +2 -1
  172. package/dist/tools/oauth/discovery.d.ts +2 -0
  173. package/dist/tools/oauth/discovery.js +3 -1
  174. package/dist/until-aborted.d.ts +5 -0
  175. package/dist/until-aborted.js +16 -0
  176. package/package.json +4 -4
  177. package/src/migrations/0176_device_report.sql +6 -0
@@ -37,6 +37,8 @@ import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnk
37
37
  import { Inject, Injectable } from "@nestjs/common";
38
38
  import { sql, } from "kysely";
39
39
  import { MANAGED_STOP_GRACE_MS } from "../background/managed.js";
40
+ import { deviceInstanceForeign, deviceUnavailable } from "../devices/access.js";
41
+ import { DeviceProviderSelection } from "../devices/device-provider-selection.js";
40
42
  import { deviceNotFound } from "../devices/errors.js";
41
43
  import { ApiError } from "../errors.js";
42
44
  import { readSandboxLimitOverride } from "../identity/settings.js";
@@ -48,6 +50,7 @@ import { isStorageError } from "../runtime/permission-context-errors.js";
48
50
  import { canonicalJson } from "../tools/canonical-json.js";
49
51
  import { attachmentsDir } from "./attachments-path.js";
50
52
  import { CloudPermissionSnapshots, } from "./cloud-permission-snapshot.js";
53
+ import { DeviceReports } from "./device-reports.js";
51
54
  import { isKernelReadMethod, KernelReadNotAdmitted, KernelReadUnsupported, } from "./kernel-read.js";
52
55
  import { SandboxLeases, SandboxLockLostError, sandboxBusy, } from "./leases.js";
53
56
  import { isCloudProvider, LegacyRetirementStore } from "./legacy-retirement.js";
@@ -55,7 +58,7 @@ import { ManagedDeviceContextFailed } from "./managed-device-context.js";
55
58
  import { appliedOf, appliedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
56
59
  import { networkOfSandbox, PermissionFacts } from "./permission-facts.js";
57
60
  import { cloudReportOwed, cloudSupportOf } from "./permission-runtime-reports.js";
58
- import { isInternalProvider, LOCAL_PROVIDER, providerForDevice, SandboxProviders, } from "./providers.js";
61
+ import { DeviceProviders, isInternalProvider, LOCAL_PROVIDER, } from "./providers.js";
59
62
  import { isDeviceRequestNotSent } from "./request-not-sent.js";
60
63
  import { SandboxProviderUnreachableError } from "./unreachable.js";
61
64
  export { deviceNotFound } from "../devices/errors.js";
@@ -69,8 +72,11 @@ const PATH_LEASE_WAIT_MS = 30_000;
69
72
  const SWEEP_OP_TIMEOUT_MS = 120_000;
70
73
  /** How long a cloud device's lifecycle reconcile waits before the sweep tries it again (B-12). */
71
74
  const RECONCILE_RETRY_SECONDS = 600;
72
- /** Where the reconcile sweep goes on from (the last device id it visited; B-12). */
73
- const RECONCILE_CURSOR_KEY = "capk:cloud-reconcile-cursor";
75
+ /**
76
+ * Where the reconcile sweep goes on from for one provider (the last device id it visited; B-12):
77
+ * one cursor per provider, since each provider's rows are swept on their own.
78
+ */
79
+ const reconcileCursorKey = (plugin) => `capk:sandbox-reconcile-cursor:${plugin}`;
74
80
  /** The bound on one cloud `permissionSupport` read under a lifecycle lease (B-15). */
75
81
  const PERMISSION_SUPPORT_TIMEOUT_MS = 30_000;
76
82
  /** How long the suspension sweep holds the intent on a sandbox past `maxRunningMinutes` (ms). */
@@ -185,8 +191,8 @@ function tagged(impl, tag, actor, before) {
185
191
  * Sandbox config problems to tell operators at startup (English log lines):
186
192
  * - `runtime.maxRunSeconds` below `sandbox.limits.maxCommandSeconds`: long commands are cut by the
187
193
  * run time limit (Ruling M20);
188
- * - the current provider plugin refuses the open public network (`refuseOpenNetwork: true` in its
189
- * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
194
+ * - a loaded provider plugin refuses the open public network (`refuseOpenNetwork: true` in its
195
+ * startup config; one line per such provider) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
190
196
  * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
191
197
  * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
192
198
  * - `sandbox.limits.orgHosts: within` while the startup config does not turn auto mode off: the
@@ -195,9 +201,9 @@ function tagged(impl, tag, actor, before) {
195
201
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
196
202
  * nothing to tell.
197
203
  */
198
- export function sandboxConfigWarnings(cfg, providerPlugin) {
204
+ export function sandboxConfigWarnings(cfg, providerPlugins = []) {
199
205
  const out = [];
200
- if (providerPlugin !== undefined && cfg.sandbox.limits.egress !== "none") {
206
+ for (const providerPlugin of cfg.sandbox.limits.egress !== "none" ? providerPlugins : []) {
201
207
  const pc = cfg.extensionConfig[providerPlugin];
202
208
  if (pc?.refuseOpenNetwork === true) {
203
209
  out.push({
@@ -224,13 +230,8 @@ export function sandboxConfigWarnings(cfg, providerPlugin) {
224
230
  }
225
231
  return out;
226
232
  }
227
- /** No sandbox provider (503). */
228
- export const sandboxUnavailable = () => new ApiError("sandbox.unavailable", "Sandbox is not available in this deployment; install a sandbox plugin");
229
- /**
230
- * The device's files are kept by a provider that is not the current one (503); its files are
231
- * not migrated, so it stays unusable until that provider is back (spec §4.2 item 13).
232
- */
233
- const otherProvider = (provider) => new ApiError("device.unavailable", `This device's files are kept by the sandbox provider ${provider}, which is not the current provider; it can be used again once ${provider} is the deployment's sandbox provider`);
233
+ /** No device to run on: none bound and none can be made (no device provider on in the org; 503). */
234
+ export const sandboxUnavailable = () => new ApiError("sandbox.unavailable", "No device provider is on in this organization; ask an org admin to switch one on");
234
235
  /**
235
236
  * An owner browse found no running instance of the device (409): the picker starts the device
236
237
  * for its owner first ({@link SandboxService.ensureRunningForOwner}), so this is an instance that
@@ -295,11 +296,21 @@ async function inPool(items, limit, fn) {
295
296
  };
296
297
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
297
298
  }
299
+ /**
300
+ * Lifecycle work on an instance row runs only with the row's own provider (a device is bound to
301
+ * its provider for life; an instance row of another provider is never written by this kernel).
302
+ */
303
+ function assertOwnRow(row, p) {
304
+ if (row.provider !== null && row.provider !== p.plugin) {
305
+ throw new Error(`device ${row.device_id}: its instance row belongs to ${row.provider}, not ${p.plugin}`);
306
+ }
307
+ }
298
308
  let SandboxService = class SandboxService {
299
309
  db;
300
310
  redis;
301
311
  leases;
302
312
  providers;
313
+ selection;
303
314
  config;
304
315
  log;
305
316
  facts;
@@ -308,19 +319,25 @@ let SandboxService = class SandboxService {
308
319
  instanceWrites;
309
320
  retirement;
310
321
  snapshots;
322
+ reports;
311
323
  constructor(db,
312
324
  /** The record of the instance each holder last used (`capk:sandbox-seen:…`). */
313
325
  redis, leases,
314
326
  /** The providers (read at every call: providers are ready after the extension load). */
315
- providers, config, log, facts, operationIntents, authority, instanceWrites,
327
+ providers,
328
+ /** Whether a device's provider serves its org now (read at every use, never cached). */
329
+ selection, config, log, facts, operationIntents, authority, instanceWrites,
316
330
  /** The retirement obligations every lifecycle acquisition is gated on (8.5). */
317
331
  retirement,
318
332
  /** The cloud snapshot writer's reconcile, for the lifecycle reconcile of marked devices (B-12). */
319
- snapshots) {
333
+ snapshots,
334
+ /** The stored device report, refreshed after a create or a resume (never fails the use). */
335
+ reports) {
320
336
  this.db = db;
321
337
  this.redis = redis;
322
338
  this.leases = leases;
323
339
  this.providers = providers;
340
+ this.selection = selection;
324
341
  this.config = config;
325
342
  this.log = log;
326
343
  this.facts = facts;
@@ -329,42 +346,75 @@ let SandboxService = class SandboxService {
329
346
  this.instanceWrites = instanceWrites;
330
347
  this.retirement = retirement;
331
348
  this.snapshots = snapshots;
349
+ this.reports = reports;
332
350
  }
333
351
  /** Poll interval while waiting for a lease (the leases' own). */
334
352
  get pollMs() {
335
353
  return this.leases.pollMs;
336
354
  }
337
355
  /**
338
- * Whether there is a cloud sandbox provider (a loaded `sandbox@2` extension). For gates that have
339
- * no device yet (tool listing, skill files); a call on a device asks
340
- * {@link availableFor}.
356
+ * Whether the device of `orgId` can be used now: its provider is loaded and on in the org
357
+ * ({@link DeviceProviderSelection.isOnInOrg}; `@local`: registered). A missing device, one of
358
+ * another org or one without a provider is not.
341
359
  */
342
- get cloudAvailable() {
343
- return this.providers.cloud() !== undefined;
360
+ async availableFor(deviceId, orgId) {
361
+ const provider = await this.deviceProvider(deviceId, orgId);
362
+ return provider != null && (await this.selection.isOnInOrg(orgId, provider));
344
363
  }
345
- /** Whether the device's provider is there (`@local` registered, or a cloud provider). */
346
- async availableFor(deviceId) {
364
+ /**
365
+ * Whether the provider the device is bound to is loaded here (`@local`: registered), whatever
366
+ * its org says: for lifecycle work that goes on while the org has the provider off (owed
367
+ * revocations, cleanup).
368
+ */
369
+ async providerLoaded(deviceId) {
347
370
  return (await this.providerOf(deviceId)) !== undefined;
348
371
  }
349
372
  /**
350
- * The provider the device works with, read from its row ({@link providerForDevice});
351
- * a missing row (or one of another org, with `orgId`) reads as a cloud device, whose use
352
- * then fails as not found.
373
+ * The device's `devices.provider` (null: none recorded; undefined: no such device, or one of
374
+ * another org with `orgId`).
353
375
  */
354
- async providerOf(deviceId, orgId) {
376
+ async deviceProvider(deviceId, orgId) {
355
377
  const row = await this.db
356
378
  .selectFrom("devices")
357
379
  .select("provider")
358
380
  .where("id", "=", deviceId)
359
381
  .$if(orgId !== undefined, (q) => q.where("org_id", "=", orgId))
360
382
  .executeTakeFirst();
361
- return providerForDevice(this.providers, row?.provider ?? null);
383
+ return row === undefined ? undefined : row.provider;
362
384
  }
363
- /** {@link providerOf}, or `sandbox.unavailable` (503) without it. */
385
+ /**
386
+ * The loaded provider the device is bound to (no org check: lifecycle work and reads that
387
+ * need no use); undefined when the device is missing, has none or its provider is not loaded.
388
+ */
389
+ async providerOf(deviceId, orgId) {
390
+ return this.providers.forDevice((await this.deviceProvider(deviceId, orgId)) ?? null);
391
+ }
392
+ /**
393
+ * The provider a use of the device of `orgId` runs on: loaded and on in the org, else
394
+ * `device.unavailable` (503, files kept); a missing device or one of another org is
395
+ * `device.not_found`.
396
+ */
364
397
  async require(deviceId, orgId) {
365
- const p = await this.providerOf(deviceId, orgId);
398
+ const provider = await this.deviceProvider(deviceId, orgId);
399
+ if (provider === undefined)
400
+ throw deviceNotFound();
401
+ const p = this.providers.forDevice(provider);
402
+ if (!p || !(await this.selection.isOnInOrg(orgId, p.plugin)))
403
+ throw deviceUnavailable(provider);
404
+ return p;
405
+ }
406
+ /**
407
+ * The loaded provider for lifecycle work on the device (no org check: cleanup and maintenance
408
+ * go on while its org has the provider off), else `device.unavailable`; a missing device is
409
+ * `device.not_found`.
410
+ */
411
+ async loadedFor(deviceId) {
412
+ const provider = await this.deviceProvider(deviceId);
413
+ if (provider === undefined)
414
+ throw deviceNotFound();
415
+ const p = this.providers.forDevice(provider);
366
416
  if (!p)
367
- throw sandboxUnavailable();
417
+ throw deviceUnavailable(provider);
368
418
  return p;
369
419
  }
370
420
  /** Concurrent holders of one device (`sandbox.maxConcurrentCommands`, read at every use). */
@@ -587,7 +637,7 @@ let SandboxService = class SandboxService {
587
637
  * reconcile marker under the shared lease, before any provider call (B-11).
588
638
  */
589
639
  async ifRunningAs(deviceId, instance, fn, signal, use) {
590
- const p = await this.require(deviceId);
640
+ const p = await this.loadedFor(deviceId);
591
641
  const env = deviceId;
592
642
  const deadline = Date.now() + this.config.get().sandbox.lockWaitSeconds * 1000;
593
643
  const token = randomUUID();
@@ -723,7 +773,7 @@ let SandboxService = class SandboxService {
723
773
  const combined = AbortSignal.any([sig, s]);
724
774
  const intent = await this.operationIntents.admitBrowse(ctx, {
725
775
  provider: entry.plugin,
726
- providerVersion: entry.version ?? "internal-v2",
776
+ providerVersion: entry.version,
727
777
  generation: String(row.created_at.getTime()),
728
778
  }, method, input, combined);
729
779
  const admitted = await this.operationIntents.claimBrowse(ctx, intent.operation_id);
@@ -1020,7 +1070,7 @@ let SandboxService = class SandboxService {
1020
1070
  await this.register(env, e.lease.token);
1021
1071
  const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
1022
1072
  provider: p.plugin,
1023
- providerVersion: p.version ?? "internal-v2",
1073
+ providerVersion: p.version,
1024
1074
  generation: String(e.createdAt),
1025
1075
  }, method, input, e.lease.token, sig));
1026
1076
  const pending = await refreshPending();
@@ -1061,7 +1111,7 @@ let SandboxService = class SandboxService {
1061
1111
  const admitted = ["dispatching", "started-or-unknown"].includes(pending.state)
1062
1112
  ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1063
1113
  provider: p.plugin,
1064
- providerVersion: p.version ?? "internal-v2",
1114
+ providerVersion: p.version,
1065
1115
  generation: String(e.createdAt),
1066
1116
  }, method, input, e.lease.token))
1067
1117
  : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
@@ -1153,7 +1203,7 @@ let SandboxService = class SandboxService {
1153
1203
  try {
1154
1204
  const intent = await runOutsideTransaction(() => this.operationIntents.admitKernelRead(ctx, read, {
1155
1205
  provider: p.plugin,
1156
- providerVersion: p.version ?? "internal-v2",
1206
+ providerVersion: p.version,
1157
1207
  generation: String(e.createdAt),
1158
1208
  }, method, given, e.lease.token, sig));
1159
1209
  admitted = await runOutsideTransaction(() => this.operationIntents.claimKernelRead(ctx, read, intent.operation_id, method, given));
@@ -1248,7 +1298,7 @@ let SandboxService = class SandboxService {
1248
1298
  }
1249
1299
  /**
1250
1300
  * Becomes a holder: loops until it has a shared lease on a running instance, or `sandbox.busy`.
1251
- * An instance recorded `running` (with the current provider, not the `gone` instance) is used
1301
+ * An instance recorded `running` (with the device's provider, not the `gone` instance) is used
1252
1302
  * under a shared lease; otherwise the exclusive lease (with intent) makes it run and is
1253
1303
  * downgraded. One token serves both, so the waiter passes its own intent. `wantNow` reads the
1254
1304
  * limits this use wants ({@link wantedLimits}), again after each wait, so a mode narrowed
@@ -1433,7 +1483,7 @@ let SandboxService = class SandboxService {
1433
1483
  return deviceNotFound();
1434
1484
  }
1435
1485
  /**
1436
- * Recorded running with the current provider on files not lost (lost ones go through the
1486
+ * Recorded running with the device's provider on files not lost (lost ones go through the
1437
1487
  * exclusive path, which refuses them), and not the instance found gone.
1438
1488
  */
1439
1489
  usable(row, p, gone) {
@@ -1522,6 +1572,10 @@ let SandboxService = class SandboxService {
1522
1572
  // B-15: a resumed cloud instance reads its permission support again; any other instance
1523
1573
  // whose recorded evidence is stale (a limits change, a provider version change) too
1524
1574
  await this.refreshCloudSupport(ctx, p, s, sig, s.resumed === true);
1575
+ // a new or resumed instance: the provider's report is stored again, still under the exclusive
1576
+ // lease and outside any transaction; a failure keeps the stored one and never fails the use
1577
+ if (s.info.fresh || s.resumed === true)
1578
+ await runOutsideTransaction(() => this.reports.refresh(p, { deviceId: env, orgId: ctx.orgId, handle: s.handle }, sig));
1525
1579
  // staged path (B-8): create → commit → legacy gate (ensure) → cleanup → bind → installed →
1526
1580
  // downgrade. The cleanup a resume or create owes runs first: a retry after a failed bind
1527
1581
  // finds the instance running and would not owe it again. The binder sends the committed
@@ -1716,10 +1770,15 @@ let SandboxService = class SandboxService {
1716
1770
  * many it suspended. Called every minute by the `sandbox-suspend-idle` cron.
1717
1771
  */
1718
1772
  async suspendIdle(now) {
1719
- // cloud only: suspendDue keeps to this provider's rows, so `@local` is never suspended here
1720
- const p = this.providers.cloud();
1721
- if (!p)
1722
- return 0;
1773
+ let n = 0;
1774
+ // each loaded extension provider over its own rows only (`@local` is never one of them, so it
1775
+ // is never suspended here); rows of a provider that is not loaded are left as they are
1776
+ for (const p of this.providers.loaded())
1777
+ n += await this.suspendIdleOf(p, now);
1778
+ return n;
1779
+ }
1780
+ /** {@link suspendIdle} for the rows of one provider. */
1781
+ async suspendIdleOf(p, now) {
1723
1782
  const due = this.suspendDue(now, p.plugin);
1724
1783
  const runningBefore = new Date(now.getTime() - this.config.get().sandbox.limits.maxRunningMinutes * 60_000);
1725
1784
  const rows = await this.candidates(due);
@@ -1764,51 +1823,40 @@ let SandboxService = class SandboxService {
1764
1823
  * hourly by the `sandbox-destroy-inactive` cron.
1765
1824
  */
1766
1825
  async destroyInactive(now) {
1767
- const p = this.providers.cloud();
1768
- const local = this.providers.forName(LOCAL_PROVIDER) !== undefined;
1826
+ const loaded = this.providers.loaded();
1827
+ const local = this.providers.forDevice(LOCAL_PROVIDER);
1769
1828
  let n = 0;
1770
- // Gone devices (deleted, or of a deleted org) on every provider that is here, `@local`
1771
- // too (its destroy calls never need the machine online); rows whose provider is missing wait.
1772
- const here = (eb) => eb.or([
1773
- ...(p ? [this.cloudRow(eb)] : []),
1774
- ...(local ? [eb("provider", "=", LOCAL_PROVIDER)] : []),
1775
- ]);
1776
- const gone = (eb) => eb.and([here(eb), this.deviceGone(eb)]);
1777
- if (p || local) {
1778
- await inPool(await this.candidates(gone), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
1779
- const done = await this.tryLocked(id, async (lease) => {
1780
- const row = await this.db
1781
- .selectFrom("device_instances")
1782
- .selectAll()
1783
- .where("device_id", "=", id)
1784
- .where(gone)
1785
- .executeTakeFirst();
1786
- const owner = row && this.rowProvider(row);
1787
- if (!row || !owner)
1788
- return false;
1789
- await this.destroyRow(row, owner, lease, "device");
1790
- return true;
1791
- });
1792
- if (done)
1793
- n++;
1794
- });
1795
- }
1796
- // inactivity destroys cloud instances only: `@local` instances are never swept
1797
- if (!p)
1798
- return n;
1829
+ // Gone devices (deleted, or of a deleted org), each provider over its own rows: every loaded
1830
+ // one and `@local` (its destroy calls never need the machine online); rows of a provider that
1831
+ // is not loaded wait, untouched.
1832
+ for (const p of local ? [...loaded, local] : loaded) {
1833
+ n += await this.sweepRows(p, (eb) => this.deviceGone(eb), "device");
1834
+ }
1835
+ // inactivity destroys instances of loaded extension providers only: `@local` instances are
1836
+ // never swept
1799
1837
  const due = this.instanceDue(now);
1800
- const idle = (eb) => eb.and([this.cloudRow(eb), due(eb)]);
1801
- await inPool(await this.candidates(idle), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
1838
+ for (const p of loaded)
1839
+ n += await this.sweepRows(p, due, "instance");
1840
+ return n;
1841
+ }
1842
+ /**
1843
+ * One destruction sweep over the rows of provider `p` matching `due` (never another provider's
1844
+ * row: the row's provider is part of the condition, read again under the lease).
1845
+ */
1846
+ async sweepRows(p, due, mode) {
1847
+ const mine = (eb) => eb.and([eb("provider", "=", p.plugin), due(eb)]);
1848
+ let n = 0;
1849
+ await inPool(await this.candidates(mine), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
1802
1850
  const done = await this.tryLocked(id, async (lease) => {
1803
1851
  const row = await this.db
1804
1852
  .selectFrom("device_instances")
1805
1853
  .selectAll()
1806
1854
  .where("device_id", "=", id)
1807
- .where(idle)
1855
+ .where(mine)
1808
1856
  .executeTakeFirst();
1809
1857
  if (!row)
1810
1858
  return false;
1811
- await this.destroyRow(row, p, lease, "instance");
1859
+ await this.destroyRow(row, p, lease, mode);
1812
1860
  return true;
1813
1861
  });
1814
1862
  if (done)
@@ -1820,28 +1868,30 @@ let SandboxService = class SandboxService {
1820
1868
  * Destroys the device's instance, then its file system, then deletes its instance row
1821
1869
  * (device deletion, offboarding); nothing to do without a row. Waits for the exclusive lease
1822
1870
  * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without the
1823
- * device's provider it throws and the row stays, marked `sweep_failed_at` (the job is
1824
- * retried, and the destruction sweep finishes a deleted device once the provider is back).
1825
- * Files kept by another provider that is not loaded cannot be destroyed: it throws and the row
1826
- * stays.
1871
+ * provider of its instance row loaded it throws and the row stays, marked `sweep_failed_at` (the
1872
+ * job is retried, and the destruction sweep finishes a deleted device once the provider is
1873
+ * back). The provider only needs to be loaded: a device is deleted while its org has the
1874
+ * provider off too.
1827
1875
  */
1828
1876
  async destroyDevice(deviceId) {
1829
1877
  const row = await this.db
1830
1878
  .selectFrom("device_instances")
1831
- .select("device_id")
1879
+ .select(["device_id", "provider"])
1832
1880
  .where("device_id", "=", deviceId)
1833
1881
  .executeTakeFirst();
1834
1882
  if (!row)
1835
1883
  return;
1836
- const p = await this.providerOf(deviceId);
1884
+ const p = row.provider !== null
1885
+ ? this.providers.forDevice(row.provider)
1886
+ : await this.providerOf(deviceId);
1837
1887
  if (!p) {
1838
1888
  await this.db
1839
1889
  .updateTable("device_instances")
1840
1890
  .set({ sweep_failed_at: sql `now()` })
1841
1891
  .where("device_id", "=", deviceId)
1842
1892
  .execute();
1843
- throw new Error(`cannot destroy device ${deviceId}: its sandbox provider is not there; ` +
1844
- "the destruction sweep retries it");
1893
+ throw new Error(`cannot destroy device ${deviceId}: its provider ${row.provider ?? "(none)"} is not ` +
1894
+ "loaded; the destruction sweep retries it");
1845
1895
  }
1846
1896
  const lease = await this.leases.acquireExclusive(deviceId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
1847
1897
  try {
@@ -1850,6 +1900,9 @@ let SandboxService = class SandboxService {
1850
1900
  .selectAll()
1851
1901
  .where("device_id", "=", deviceId)
1852
1902
  .executeTakeFirst();
1903
+ if (current && current.provider !== null && current.provider !== p.plugin) {
1904
+ throw new Error(`cannot destroy device ${deviceId}: its instance row changed provider`);
1905
+ }
1853
1906
  if (current)
1854
1907
  await this.destroyRow(current, p, lease, "device");
1855
1908
  }
@@ -1861,10 +1914,11 @@ let SandboxService = class SandboxService {
1861
1914
  * Starts the device over with empty files (after `device.files_lost`, or on request):
1862
1915
  * under the exclusive lease (waited for like {@link destroyDevice}) destroys any instance and
1863
1916
  * the file system (a `lost` one is only dropped), and records no file system; the next use
1864
- * creates a new one. Nothing to do without a row. Throws `sandbox.unavailable` without a provider.
1917
+ * creates a new one. Nothing to do without a row. Throws `device.unavailable` while the device's
1918
+ * provider is not loaded, or when its instance row names another provider.
1865
1919
  */
1866
1920
  async resetFileSystem(deviceId) {
1867
- const p = await this.require(deviceId);
1921
+ const p = await this.loadedFor(deviceId);
1868
1922
  const lease = await this.leases.acquireExclusive(deviceId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
1869
1923
  try {
1870
1924
  const row = await this.db
@@ -1874,10 +1928,13 @@ let SandboxService = class SandboxService {
1874
1928
  .executeTakeFirst();
1875
1929
  if (!row)
1876
1930
  return;
1931
+ if (row.provider !== null && row.provider !== p.plugin) {
1932
+ throw deviceInstanceForeign(p.plugin, row.provider);
1933
+ }
1877
1934
  const fence = { gen: row.generation };
1878
1935
  const signal = opSignal(lease);
1879
1936
  const prev = await this.destroyInstance(row, p, signal);
1880
- await this.destroyFiles(row, p, signal, true);
1937
+ await this.destroyFiles(row, p, signal);
1881
1938
  if (!(await lease.renew()))
1882
1939
  throw new SandboxLockLostError(deviceId);
1883
1940
  await this.fenced(lease, deviceId, fence, {
@@ -1955,7 +2012,7 @@ let SandboxService = class SandboxService {
1955
2012
  try {
1956
2013
  const device = await this.db
1957
2014
  .selectFrom("devices")
1958
- .select("org_id")
2015
+ .select(["org_id", "provider"])
1959
2016
  .where("id", "=", deviceId)
1960
2017
  .executeTakeFirst();
1961
2018
  if (!device)
@@ -1984,6 +2041,7 @@ let SandboxService = class SandboxService {
1984
2041
  !update ||
1985
2042
  p.plugin === LOCAL_PROVIDER ||
1986
2043
  row.provider !== p.plugin ||
2044
+ device.provider !== p.plugin ||
1987
2045
  row.fs_status !== "ready" ||
1988
2046
  (row.status !== "running" && row.status !== "suspended"))
1989
2047
  return before;
@@ -2041,16 +2099,24 @@ let SandboxService = class SandboxService {
2041
2099
  }
2042
2100
  }
2043
2101
  /**
2044
- * The worker's sweep of {@link reconcileLimits} (`sandbox-reconcile-limits`): up to `limit`
2045
- * live cloud devices of the loaded cloud provider carrying the marker on a live instance, in
2046
- * id order from a shared keyset cursor that wraps around (no starvation), each tried at most
2047
- * once per {@link RECONCILE_RETRY_SECONDS} across replicas (a Redis marker).
2048
- * Nothing without a cloud provider that can `update`. Returns how many it reconciled.
2102
+ * The worker's sweep of {@link reconcileLimits} (`sandbox-reconcile-limits`): for each loaded
2103
+ * provider that can `update`, up to `limit` live cloud devices of its own carrying the marker on
2104
+ * a live instance, in id order from that provider's shared keyset cursor that wraps around (no
2105
+ * starvation), each tried at most once per {@link RECONCILE_RETRY_SECONDS} across replicas (a
2106
+ * Redis marker). Rows of a provider that is not loaded are never touched. Returns how many it
2107
+ * reconciled.
2049
2108
  */
2050
2109
  async reconcileMarked(limit = 10) {
2051
- const p = this.providers.cloud();
2052
- if (!p?.impl.update)
2053
- return 0;
2110
+ let n = 0;
2111
+ for (const p of this.providers.loaded()) {
2112
+ if (p.impl.update)
2113
+ n += await this.reconcileMarkedOf(p, limit);
2114
+ }
2115
+ return n;
2116
+ }
2117
+ /** {@link reconcileMarked} for the devices of one provider. */
2118
+ async reconcileMarkedOf(p, limit) {
2119
+ const cursorKey = reconcileCursorKey(p.plugin);
2054
2120
  const page = (after, n) => this.db
2055
2121
  .selectFrom("devices as d")
2056
2122
  .innerJoin("device_instances as i", "i.device_id", "d.id")
@@ -2058,6 +2124,7 @@ let SandboxService = class SandboxService {
2058
2124
  .where("d.source", "=", "cloud")
2059
2125
  .where("d.deleted_at", "is", null)
2060
2126
  .where("d.permission_reconcile_required", "=", true)
2127
+ .where("d.provider", "=", p.plugin)
2061
2128
  .where("i.provider", "=", p.plugin)
2062
2129
  .where("i.handle", "is not", null)
2063
2130
  .where("i.status", "in", ["running", "suspended"])
@@ -2068,7 +2135,7 @@ let SandboxService = class SandboxService {
2068
2135
  // a keyset cursor shared by the replicas (the cron runs once per tick): each tick goes on
2069
2136
  // after the last device the previous one visited and wraps around, so devices that stay
2070
2137
  // marked never starve the ones after them
2071
- const after = (await this.redis.get(RECONCILE_CURSOR_KEY).catch(() => null)) ?? "";
2138
+ const after = (await this.redis.get(cursorKey).catch(() => null)) ?? "";
2072
2139
  const rows = await page(after, limit);
2073
2140
  if (rows.length < limit && after !== "") {
2074
2141
  const seen = new Set(rows.map((r) => r.id));
@@ -2078,7 +2145,7 @@ let SandboxService = class SandboxService {
2078
2145
  }
2079
2146
  const last = rows.at(-1)?.id;
2080
2147
  await this.redis
2081
- .set(RECONCILE_CURSOR_KEY, last ?? "", "EX", 86_400)
2148
+ .set(cursorKey, last ?? "", "EX", 86_400)
2082
2149
  .catch((err) => this.log.warn("cannot record the reconcile cursor", { err }));
2083
2150
  let n = 0;
2084
2151
  for (const { id } of rows) {
@@ -2162,7 +2229,7 @@ let SandboxService = class SandboxService {
2162
2229
  const cancelOnResume = async (o, live) => {
2163
2230
  if (live.status !== "suspended" || !isCloudProvider(o.provider))
2164
2231
  return "skip";
2165
- const impl = this.providers.forName(o.provider)?.impl;
2232
+ const impl = this.providers.forDevice(o.provider)?.impl;
2166
2233
  const background = impl?.background;
2167
2234
  if (!impl || !background)
2168
2235
  return "skip";
@@ -2253,7 +2320,7 @@ let SandboxService = class SandboxService {
2253
2320
  */
2254
2321
  const destroyLive = async (o, live) => {
2255
2322
  const provider = live.provider ?? "unknown";
2256
- const impl = isCloudProvider(provider) ? this.providers.forName(provider)?.impl : undefined;
2323
+ const impl = isCloudProvider(provider) ? this.providers.forDevice(provider)?.impl : undefined;
2257
2324
  if (!impl) {
2258
2325
  await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2259
2326
  return false;
@@ -2299,13 +2366,13 @@ let SandboxService = class SandboxService {
2299
2366
  /**
2300
2367
  * R2-I1: the row is not live (destroyed before 0157 without a record, or a create that left
2301
2368
  * `creating` with no handle). With no `prev_handle`, the row's own cloud provider holds at
2302
- * most one instance of the device's name (sandbox@2 same-name replacement), so its destroy by
2369
+ * most one instance of the device's name (device-provider@1 same-name replacement), so its destroy by
2303
2370
  * that name confirms every incarnation there; it is recorded as the destruction of the row's
2304
2371
  * incarnation. A provider not loaded or a failed destroy keeps the obligation open.
2305
2372
  */
2306
2373
  const destroyNamed = async (o, row) => {
2307
2374
  const provider = row.provider ?? "unknown";
2308
- const impl = isCloudProvider(provider) ? this.providers.forName(provider)?.impl : undefined;
2375
+ const impl = isCloudProvider(provider) ? this.providers.forDevice(provider)?.impl : undefined;
2309
2376
  if (!impl) {
2310
2377
  await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2311
2378
  return false;
@@ -2401,7 +2468,7 @@ let SandboxService = class SandboxService {
2401
2468
  // `prev_handle`; so once the device's current incarnation is destroyed with
2402
2469
  // confirmation, nothing earlier is kept (`prev_handle`) and the obligation was recorded
2403
2470
  // under the freeze (no dispatch after it), no instance of the device can run legacy work.
2404
- // This rests on sandbox@2 same-name replacement: every rebuild on the same provider goes
2471
+ // This rests on device-provider@1 same-name replacement: every rebuild on the same provider goes
2405
2472
  // through `create`, which first removes the old `cap-device-<id>` instance (so a `gone`
2406
2473
  // answer, E2B's token-failure `gone` included, and `applyLimits`' swallowed destroy
2407
2474
  // failure leave nothing behind), and E2B's incarnations are one sandbox (destroying the
@@ -2606,7 +2673,7 @@ let SandboxService = class SandboxService {
2606
2673
  // Every acquisition first does a fenced increment: an old holder whose lease expired while it
2607
2674
  // kept running (a stalled sweep) then fails its next write.
2608
2675
  await this.fenced(held, id, fence, {});
2609
- // the retirement gate (8.5), before any use, resume, rebuild, provider switch or bind: an
2676
+ // the retirement gate (8.5), before any use, resume, rebuild or bind: an
2610
2677
  // old incarnation that may run legacy work is destroyed (cloud, confirmed) or refuses
2611
2678
  signal.throwIfAborted();
2612
2679
  const gate = { resumed: false, running: false };
@@ -2614,18 +2681,10 @@ let SandboxService = class SandboxService {
2614
2681
  try {
2615
2682
  if (row.fs_status === "lost")
2616
2683
  throw deviceFilesLost(p.plugin === LOCAL_PROVIDER);
2617
- if (row.provider !== null &&
2618
- row.provider !== p.plugin &&
2619
- (row.fs_status !== "none" || row.handle !== null)) {
2620
- throw otherProvider(row.provider);
2621
- }
2622
- if (row.provider !== null &&
2623
- row.provider !== p.plugin &&
2624
- row.fs_status === "none" &&
2625
- row.status === "creating") {
2626
- // a create by the previous provider ended before its file system was recorded: that
2627
- // provider may have made it by name, and nothing else would ever destroy it
2628
- await this.dropUnrecordedFiles(id, row.provider, signal);
2684
+ // a device is bound to its provider for life: an instance row of another provider (never
2685
+ // written by this kernel) is refused as it is, never taken over
2686
+ if (row.provider !== null && row.provider !== p.plugin) {
2687
+ throw deviceInstanceForeign(p.plugin, row.provider);
2629
2688
  }
2630
2689
  // read under the lease, after the fence moved: a value read before the wait may be stale
2631
2690
  // (another replica may have changed the mode meanwhile)
@@ -2959,47 +3018,19 @@ let SandboxService = class SandboxService {
2959
3018
  }
2960
3019
  }
2961
3020
  /**
2962
- * Destroys the file system another provider may have made under the device's name without
2963
- * the kernel recording it (`destroyFileSystemByName`; not there is success). That provider not
2964
- * loaded, or a failure, is only warned (the files may leak there) so the device stays
2965
- * usable; an abort is thrown.
3021
+ * Destroys an instance an earlier kernel recorded in `prev_*` (left by a provider replaced back
3022
+ * then) with that provider: still loaded and destroyed → false; otherwise warns and returns true
3023
+ * (the record must be kept).
2966
3024
  */
2967
- async dropUnrecordedFiles(id, provider, signal) {
2968
- const old = this.providers.forName(provider)?.impl;
2969
- if (!old) {
2970
- this.log.warn("device file system may have been made by a provider that is not loaded; it may leak", { deviceId: id, provider });
2971
- return;
2972
- }
2973
- try {
2974
- await old.destroyFileSystemByName(deviceResourceName(id), signal);
2975
- }
2976
- catch (err) {
2977
- if (signal.aborted)
2978
- throw err;
2979
- this.log.warn("cannot destroy the file system of the previous sandbox provider", {
2980
- deviceId: id,
2981
- provider,
2982
- err,
2983
- });
2984
- }
2985
- }
2986
- /**
2987
- * Destroys an instance of another provider with that provider: still loaded and destroyed →
2988
- * false; otherwise warns and returns true (the record must be kept).
2989
- */
2990
- async retire(id, provider, handle, signal,
2991
- /** The retired incarnation's generation when known: its confirmed destroy is recorded (M4). */
2992
- generation) {
2993
- const old = this.providers.forName(provider)?.impl;
3025
+ async retire(id, provider, handle, signal) {
3026
+ const old = this.providers.forDevice(provider)?.impl;
2994
3027
  if (old) {
2995
3028
  try {
2996
3029
  await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]));
2997
- if (generation !== undefined && isCloudProvider(provider))
2998
- await this.retirement.recordDestruction(id, provider, generation);
2999
3030
  return false;
3000
3031
  }
3001
3032
  catch (err) {
3002
- this.log.warn("cannot destroy sandbox instance of the previous provider", {
3033
+ this.log.warn("cannot destroy a sandbox instance recorded from a previous provider", {
3003
3034
  deviceId: id,
3004
3035
  provider,
3005
3036
  err,
@@ -3007,32 +3038,26 @@ let SandboxService = class SandboxService {
3007
3038
  return true;
3008
3039
  }
3009
3040
  }
3010
- this.log.warn("sandbox was created by another provider that is not loaded; its instance may leak", { deviceId: id, provider });
3041
+ this.log.warn("a sandbox instance recorded from a previous provider that is not loaded may leak", { deviceId: id, provider });
3011
3042
  return true;
3012
3043
  }
3013
3044
  /**
3014
- * Under the lease: destroys the row's instance (and a leaked one of an earlier provider). An
3015
- * instance without a handle (a create that ended before the handle was recorded) is destroyed by
3016
- * name. Returns the `prev_*` patch for instances that could not be destroyed.
3045
+ * Under the lease: destroys the row's instance with its own provider `p` (and an instance an
3046
+ * earlier kernel recorded in `prev_*`). An instance without a handle (a create that ended before
3047
+ * the handle was recorded) is destroyed by name. Returns the `prev_*` patch.
3017
3048
  */
3018
3049
  async destroyInstance(row, p, signal) {
3019
3050
  const id = row.device_id;
3020
- const owner = row.provider ?? p.plugin;
3051
+ assertOwnRow(row, p);
3021
3052
  let prev = {};
3022
- if (row.handle && owner === p.plugin) {
3053
+ if (row.handle) {
3023
3054
  await p.impl.destroy(row.handle, signal);
3024
3055
  }
3025
- else if (row.handle && row.status !== "destroyed") {
3026
- if (await this.retire(id, owner, row.handle, signal, String(row.created_at.getTime()))) {
3027
- prev = { prev_provider: owner, prev_handle: JSON.stringify(row.handle) };
3028
- }
3029
- }
3030
- else if (!row.handle && row.status === "creating") {
3056
+ else if (row.status === "creating") {
3031
3057
  // the provider may have built it already: only the name finds it
3032
- const impl = owner === p.plugin ? p.impl : this.providers.forName(owner)?.impl;
3033
- await impl?.destroyByName(deviceResourceName(id), signal);
3058
+ await p.impl.destroyByName(deviceResourceName(id), signal);
3034
3059
  }
3035
- if (row.prev_handle && row.prev_provider && !("prev_handle" in prev)) {
3060
+ if (row.prev_handle && row.prev_provider) {
3036
3061
  if (!(await this.retire(id, row.prev_provider, row.prev_handle, signal))) {
3037
3062
  prev = { prev_provider: null, prev_handle: null };
3038
3063
  }
@@ -3040,31 +3065,16 @@ let SandboxService = class SandboxService {
3040
3065
  return prev;
3041
3066
  }
3042
3067
  /**
3043
- * Under the lease: destroys the row's file system with the provider that made it (by name when
3044
- * no handle was recorded: `createFileSystem` may have finished before the kernel stopped). With
3045
- * that provider not loaded it throws (the row must stay for a retry), or with `lenient` only
3046
- * warns (the files leak at that provider).
3068
+ * Under the lease: destroys the row's file system with its own provider `p` (by name when no
3069
+ * handle was recorded: `createFileSystem` may have finished before the kernel stopped).
3047
3070
  */
3048
- async destroyFiles(row, p, signal, lenient = false) {
3071
+ async destroyFiles(row, p, signal) {
3072
+ assertOwnRow(row, p);
3049
3073
  const id = row.device_id;
3050
- const owner = row.provider ?? p.plugin;
3051
- const impl = owner === p.plugin ? p.impl : this.providers.forName(owner)?.impl;
3052
- if (!impl) {
3053
- if (row.fs_handle === null)
3054
- return;
3055
- if (!lenient) {
3056
- throw new Error(`cannot destroy the file system of device ${id}: its sandbox provider ${owner} is not loaded`);
3057
- }
3058
- this.log.warn("device file system of a provider that is not loaded is leaked", {
3059
- deviceId: id,
3060
- provider: owner,
3061
- });
3062
- return;
3063
- }
3064
3074
  if (row.fs_handle !== null)
3065
- await impl.destroyFileSystem(row.fs_handle, signal);
3075
+ await p.impl.destroyFileSystem(row.fs_handle, signal);
3066
3076
  else
3067
- await impl.destroyFileSystemByName(deviceResourceName(id), signal);
3077
+ await p.impl.destroyFileSystemByName(deviceResourceName(id), signal);
3068
3078
  }
3069
3079
  /**
3070
3080
  * Under the lease: `instance` destroys the instance and marks the row `destroyed` (the file
@@ -3077,9 +3087,8 @@ let SandboxService = class SandboxService {
3077
3087
  const prev = await this.destroyInstance(row, p, signal);
3078
3088
  // the provider's destroy resolved: confirmed destruction of exactly this cloud incarnation
3079
3089
  // (8.5 evidence); a kernel-internal (local) destroy is a no-op and is never recorded
3080
- const owner = row.provider ?? p.plugin;
3081
- if (row.handle && owner === p.plugin && isCloudProvider(owner))
3082
- await this.retirement.recordDestruction(id, owner, String(row.created_at.getTime()));
3090
+ if (row.handle && isCloudProvider(p.plugin))
3091
+ await this.retirement.recordDestruction(id, p.plugin, String(row.created_at.getTime()));
3083
3092
  if (mode === "device")
3084
3093
  await this.destroyFiles(row, p, signal);
3085
3094
  if (!(await held.renew()))
@@ -3115,16 +3124,9 @@ let SandboxService = class SandboxService {
3115
3124
  eb.or([eb("last_used_at", "<", idleBefore), eb("running_since", "<", runningBefore)]),
3116
3125
  ]);
3117
3126
  }
3118
- /** The provider of an instance row: an internal one (`@local`) by name, else the cloud one. */
3127
+ /** The loaded provider of an instance row (its own `provider`); undefined when not loaded. */
3119
3128
  rowProvider(row) {
3120
- return providerForDevice(this.providers, row.provider);
3121
- }
3122
- /**
3123
- * A row the idle sweeps may touch: not on a kernel-internal provider (`@local` instances live on
3124
- * people's machines and are never suspended or destroyed for inactivity).
3125
- */
3126
- cloudRow(eb) {
3127
- return eb.or([eb("provider", "is", null), eb("provider", "not like", "@%")]);
3129
+ return this.providers.forDevice(row.provider);
3128
3130
  }
3129
3131
  /** The device was deleted, or its org was: the instance and the files go. */
3130
3132
  deviceGone(eb) {
@@ -3156,14 +3158,16 @@ SandboxService = __decorate([
3156
3158
  __param(0, Inject(KernelDb)),
3157
3159
  __param(1, Inject(REDIS)),
3158
3160
  __param(2, Inject(SandboxLeases)),
3159
- __param(3, Inject(SandboxProviders)),
3160
- __param(4, Inject(KernelConfigService)),
3161
- __param(5, Inject(KERNEL_LOGGER)),
3162
- __param(6, Inject(PermissionFacts)),
3163
- __param(7, Inject(SandboxOperationIntents)),
3164
- __param(8, Inject(SandboxOperationAuthority)),
3165
- __param(9, Inject(PermissionInstanceWrites)),
3166
- __param(10, Inject(LegacyRetirementStore)),
3167
- __param(11, Inject(CloudPermissionSnapshots))
3161
+ __param(3, Inject(DeviceProviders)),
3162
+ __param(4, Inject(DeviceProviderSelection)),
3163
+ __param(5, Inject(KernelConfigService)),
3164
+ __param(6, Inject(KERNEL_LOGGER)),
3165
+ __param(7, Inject(PermissionFacts)),
3166
+ __param(8, Inject(SandboxOperationIntents)),
3167
+ __param(9, Inject(SandboxOperationAuthority)),
3168
+ __param(10, Inject(PermissionInstanceWrites)),
3169
+ __param(11, Inject(LegacyRetirementStore)),
3170
+ __param(12, Inject(CloudPermissionSnapshots)),
3171
+ __param(13, Inject(DeviceReports))
3168
3172
  ], SandboxService);
3169
3173
  export { SandboxService };