@capybara-hq/kernel 0.1.0-rc.75 → 0.1.0-rc.77

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 (76) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/agents/readiness.controller.d.ts +4 -3
  3. package/dist/agents/readiness.controller.js +4 -3
  4. package/dist/agents/readiness.service.d.ts +44 -11
  5. package/dist/agents/readiness.service.js +59 -16
  6. package/dist/catalog/catalog-import.module.d.ts +1 -1
  7. package/dist/catalog/catalog-import.module.js +1 -1
  8. package/dist/catalog/cli.d.ts +9 -2
  9. package/dist/catalog/cli.js +10 -4
  10. package/dist/catalog/marketplaces.service.d.ts +1 -1
  11. package/dist/catalog/plugin-upgrade.d.ts +4 -2
  12. package/dist/catalog/plugin-upgrade.js +9 -3
  13. package/dist/db/kernel-schema.d.ts +5 -0
  14. package/dist/devices/device-projects.service.d.ts +3 -12
  15. package/dist/devices/device-projects.service.js +16 -59
  16. package/dist/extensions/bootstrap.d.ts +34 -3
  17. package/dist/extensions/bootstrap.js +111 -14
  18. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  19. package/dist/lifecycle/kernel-lifecycle.js +16 -11
  20. package/dist/overrides.d.ts +0 -5
  21. package/dist/overrides.js +0 -2
  22. package/dist/platform/file-ref.d.ts +6 -5
  23. package/dist/platform/ops/agent-skills.ops.js +1 -1
  24. package/dist/platform/ops/agents.ops.js +1 -1
  25. package/dist/runtime/model-call.d.ts +2 -2
  26. package/dist/runtime/project/knowledge.d.ts +1 -1
  27. package/dist/runtime/project/knowledge.js +1 -1
  28. package/dist/runtime/project/knowledge.service.d.ts +5 -11
  29. package/dist/runtime/project/knowledge.service.js +12 -23
  30. package/dist/runtime/providers.d.ts +34 -1
  31. package/dist/runtime/providers.js +56 -7
  32. package/dist/runtime/run-steps.d.ts +4 -6
  33. package/dist/runtime/run-steps.js +7 -15
  34. package/dist/runtime/runtime.module.js +1 -1
  35. package/dist/sandbox/held-operations.d.ts +2 -5
  36. package/dist/sandbox/held-operations.js +0 -14
  37. package/dist/sandbox/managed-device-context.d.ts +1 -1
  38. package/dist/sandbox/managed-device-context.js +1 -1
  39. package/dist/sandbox/permission-context-types.d.ts +0 -11
  40. package/dist/sandbox/permission-context-types.js +0 -13
  41. package/dist/sandbox/providers.d.ts +5 -0
  42. package/dist/sandbox/providers.js +1 -1
  43. package/dist/sandbox/sandbox-file-reader.d.ts +7 -12
  44. package/dist/sandbox/sandbox-file-reader.js +12 -29
  45. package/dist/sandbox/sandbox.service.d.ts +53 -32
  46. package/dist/sandbox/sandbox.service.js +217 -141
  47. package/dist/sandbox/use-context.d.ts +4 -1
  48. package/dist/skills/invoke.d.ts +13 -35
  49. package/dist/skills/invoke.js +23 -162
  50. package/dist/tools/builtins/builtin-tools.d.ts +2 -11
  51. package/dist/tools/builtins/builtin-tools.js +5 -23
  52. package/dist/tools/builtins/image/generate.js +2 -2
  53. package/dist/tools/builtins/sandbox/common.d.ts +32 -80
  54. package/dist/tools/builtins/sandbox/common.js +61 -173
  55. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  56. package/dist/tools/builtins/sandbox/device-owner.d.ts +4 -5
  57. package/dist/tools/builtins/sandbox/device-owner.js +5 -6
  58. package/dist/tools/builtins/sandbox/fetch-attachment.js +2 -2
  59. package/dist/tools/builtins/sandbox/glob.js +1 -1
  60. package/dist/tools/builtins/sandbox/grep.js +1 -1
  61. package/dist/tools/builtins/sandbox/index.d.ts +2 -2
  62. package/dist/tools/builtins/sandbox/index.js +2 -2
  63. package/dist/tools/builtins/sandbox/read.js +1 -1
  64. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -3
  65. package/dist/tools/builtins/sandbox/task-output.js +4 -4
  66. package/dist/tools/builtins/sandbox/task-stop.js +1 -1
  67. package/dist/tools/builtins/skill-load.d.ts +10 -9
  68. package/dist/tools/builtins/skill-load.js +15 -19
  69. package/dist/tools/connectors.service.d.ts +4 -2
  70. package/dist/tools/connectors.service.js +15 -3
  71. package/dist/tools/pipeline.d.ts +0 -2
  72. package/dist/tools/pipeline.js +7 -14
  73. package/dist/tools/tools.module.js +1 -1
  74. package/package.json +2 -2
  75. package/src/migrations/0179_device_report_limit_text.sql +28 -0
  76. package/src/migrations/0180_device_instance_abandoned.sql +6 -0
@@ -28,7 +28,7 @@ import { DeviceProviders } from "./providers.js";
28
28
  import type { SandboxUseContext } from "./use-context.js";
29
29
  export { SANDBOX_LOCK_PREFIX, SANDBOX_LOCK_TTL_MS, SandboxLockLostError, sandboxBusy, } from "./leases.js";
30
30
  export type { SandboxUseContext } from "./use-context.js";
31
- /** The third argument of the `withSandbox` callback. */
31
+ /** The third argument of a use's callback ({@link SandboxService.withOperations} and others). */
32
32
  export interface SandboxUseInfo {
33
33
  /** This call created the instance (first use, or a rebuild). */
34
34
  fresh: boolean;
@@ -56,6 +56,10 @@ export interface SandboxUseInfo {
56
56
  */
57
57
  contextEvidence?: HeldDeviceContextEvidence;
58
58
  }
59
+ /** The callback of an operation use or a kernel read: every provider call admitted first. */
60
+ export type SandboxUseCallback<T> = (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>;
61
+ /** An entry bound to one route (its invocation or kernel read), as a caller hands it on. */
62
+ export type SandboxUseEntry = <T>(ctx: SandboxUseContext, fn: SandboxUseCallback<T>, signal: AbortSignal) => Promise<T>;
59
63
  type Row = Selectable<DeviceInstancesTable>;
60
64
  type ExecArgs = Parameters<DeviceProvider["exec"]>[1];
61
65
  /**
@@ -67,10 +71,6 @@ interface Instance {
67
71
  handle: SandboxHandle;
68
72
  createdAt: number;
69
73
  }
70
- /**
71
- * The provider {@link SandboxService.withSandbox} passes to its callback: every `exec` carries the
72
- * holder's tag and the caller's actor, so the callback passes neither.
73
- */
74
74
  /**
75
75
  * The provider {@link SandboxService.ifRunning} passes to its callback: every `exec` carries the
76
76
  * holder's tag; the caller names the actor.
@@ -178,9 +178,9 @@ export declare const recreateRequired: () => ApiError;
178
178
  * deleted, plus one instance attached to it that comes and goes; all conversations bound to the
179
179
  * device (and their sub-agents) share both.
180
180
  *
181
- * - **Lazy creation**: the first {@link withSandbox} creates the file system
182
- * (`createFileSystem`, name `cap-device-<deviceId>`) and then the instance on it; state lives
183
- * in `device_instances`. A file system gone at the provider is never replaced silently:
181
+ * - **Lazy creation**: the first use ({@link withOperations} and the others) creates the file
182
+ * system (`createFileSystem`, name `cap-device-<deviceId>`) and then the instance on it; state
183
+ * lives in `device_instances`. A file system gone at the provider is never replaced silently:
184
184
  * `fs_status` becomes `lost` and uses fail with `device.files_lost` until
185
185
  * {@link resetFileSystem}.
186
186
  * - **Leases** (phase C, spec §10, {@link SandboxLeases}), keyed by device id: using an
@@ -423,7 +423,7 @@ export declare class SandboxService {
423
423
  } | null>;
424
424
  /**
425
425
  * The instance the device records now (its `created_at`), while it has one that runs or is
426
- * suspended; null otherwise. Read without a lease: a caller inside `withSandbox` reads the
426
+ * suspended; null otherwise. Read without a lease: a caller inside a use reads the
427
427
  * instance its own lease keeps.
428
428
  */
429
429
  currentInstance(deviceId: string): Promise<{
@@ -435,8 +435,8 @@ export declare class SandboxService {
435
435
  * `instance.createdAt` (background tasks, spec 2026-11-05-background-bash-design §4.3). It never
436
436
  * creates, resumes or rebuilds one: an instance that is missing, suspended, being created or
437
437
  * destroyed (or recorded with another provider) is `not_running`, one that records another
438
- * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a `withSandbox`
439
- * holder does (its tag on every exec, crashed holders' operations revoked exactly), and
438
+ * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a use's
439
+ * holder does (crashed holders' operations revoked exactly), with its tag on every exec, and
440
440
  * `last_used_at` moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
441
441
  * (`sandbox.busy`); `signal` (optional) ends the wait with its abort reason. The signal passed
442
442
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
@@ -463,23 +463,6 @@ export declare class SandboxService {
463
463
  * aborts when a renewal finds it lost.
464
464
  */
465
465
  pathLease(deviceId: string, path: string, signal: AbortSignal): Promise<SandboxPathLease>;
466
- /**
467
- * Runs `fn` on the device's instance: take a lease → make sure the instance runs (file
468
- * system, create / resume / rebuild, under the exclusive lease) → `fn` under a shared lease →
469
- * update `last_used_at` → release.
470
- * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
471
- * the wait and the creation / resume.
472
- * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
473
- * stop when the lease is lost.
474
- * - The provider passed to `fn` labels every `exec` with this holder's tag and `ctx.actor`.
475
- * - When `fn` throws `SandboxGoneError` (the instance is gone) the instance is rebuilt on the
476
- * kept files (or the one another holder rebuilt is taken) and `fn` runs once more with
477
- * `restarted: true`; a second `gone` is thrown. Other errors are thrown as they are.
478
- * - Lost files throw `device.files_lost` (409), also when `fn` throws
479
- * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
480
- * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
481
- * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
482
- */
483
466
  /** Trusted staging only. The callback receives no exec, browsing or lifecycle methods. */
484
467
  withPreparation<T>(ctx: SandboxUseContext, purpose: SandboxPreparationScope["purpose"], roots: readonly string[], fn: (p: SandboxPreparation, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
485
468
  private prepareFor;
@@ -522,7 +505,27 @@ export declare class SandboxService {
522
505
  */
523
506
  withKernelRead<T>(ctx: SandboxUseContext, read: KernelReadInvocation, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
524
507
  withOperations<T>(ctx: SandboxUseContext, invocation: OperationSessionInvocation, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
525
- withSandbox<T>(ctx: SandboxUseContext, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
508
+ /**
509
+ * Every use of the device's instance ({@link withOperations}, {@link withPreparation},
510
+ * {@link withKernelRead}; there is no raw route): take a lease → make sure the instance runs
511
+ * (file system, create / resume / rebuild, under the exclusive lease) → the route's callback
512
+ * under a shared lease → update `last_used_at` → release.
513
+ * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
514
+ * the wait and the creation / resume.
515
+ * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
516
+ * stop when the lease is lost.
517
+ * - The provider passed to `fn` admits and claims every call (an operation or a kernel read)
518
+ * before it reaches the provider; a preparation gets only the staging methods.
519
+ * - When `SandboxGoneError` is raised outside a dispatched operation (staging, context
520
+ * evidence), the instance is rebuilt on the kept files (or the one another holder rebuilt is
521
+ * taken) and the route runs once more with `restarted: true`; a second `gone` is thrown. A
522
+ * gone after a durable dispatch stays unknown: the instance is rebuilt, the call is not
523
+ * retried. Other errors are thrown as they are.
524
+ * - Lost files throw `device.files_lost` (409), also when `fn` throws
525
+ * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
526
+ * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
527
+ * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
528
+ */
526
529
  private withSandboxUse;
527
530
  /**
528
531
  * The limits a device's instance must run with for this use (auto mode spec §4.2), read fresh,
@@ -556,7 +559,7 @@ export declare class SandboxService {
556
559
  * logs.
557
560
  */
558
561
  private seenBy;
559
- /** Runs `fn` as the holder `e`: its tag and the caller's actor on every exec, its lease's signal. */
562
+ /** Runs the route as the holder `e`, under its lease's signal. */
560
563
  private runAs;
561
564
  /**
562
565
  * The held provider of a kernel read ({@link withKernelRead}): every call admitted and claimed
@@ -702,10 +705,28 @@ export declare class SandboxService {
702
705
  * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without the
703
706
  * provider of its instance row loaded it throws and the row stays, marked `sweep_failed_at` (the
704
707
  * job is retried, and the destruction sweep finishes a deleted device once the provider is
705
- * back). The provider only needs to be loaded: a device is deleted while its org has the
706
- * provider off too.
708
+ * back). A provider that is no longer installed on this deployment (no install record, or its
709
+ * catalog item removed; never an in-process `@…` one) will not be back: the instance is
710
+ * abandoned instead ({@link abandonInstance}) and the call returns (#675). The provider only
711
+ * needs to be loaded: a device is deleted while its org has the provider off too.
707
712
  */
708
713
  destroyDevice(deviceId: string): Promise<void>;
714
+ /**
715
+ * Whether `provider` is still installed on this deployment: an in-process `@…` provider always
716
+ * counts (code, not an install), a plugin while its install record exists and the catalog item
717
+ * it was installed from (if any) is not removed. Not loaded on this replica is a separate case.
718
+ */
719
+ private providerInstalled;
720
+ /**
721
+ * Abandons the instance of a deleted device whose provider is no longer installed (#675): the
722
+ * kernel can never destroy it, so the row is kept as the record of the provider-side names
723
+ * (`handle`, `fs_handle`, `prev_handle`), marked `abandoned_at`, and one platform audit event
724
+ * (`device.instance_abandoned`, for the super admin) carries the same names. One statement, so
725
+ * the mark and its event commit together, and only the first call writes either (a retried job
726
+ * finds the row abandoned and does nothing). The sweeps iterate loaded providers only, so
727
+ * nothing retries the row; a plugin of that name installed again destroys it as before.
728
+ */
729
+ private abandonInstance;
709
730
  /**
710
731
  * Starts the device over with empty files (after `device.files_lost`, or on request):
711
732
  * under the exclusive lease (waited for like {@link destroyDevice}) destroys any instance and
@@ -10,7 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { posix } from "node:path";
11
11
  import { isDeviceOfflineError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
12
12
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
13
- import { createHeldOperations, createLegacyHeldProvider, withKernelGeneration, } from "./held-operations.js";
13
+ import { createHeldOperations, withKernelGeneration, } from "./held-operations.js";
14
14
  import { SandboxOperationAuthority } from "./operation-authority.js";
15
15
  import { PermissionAdmissionStale, SandboxOperationIntents, } from "./operation-intents.js";
16
16
  import { PermissionInstanceWrites } from "./permission-instance-writes.js";
@@ -65,7 +65,7 @@ import { ManagedDeviceContextFailed } from "./managed-device-context.js";
65
65
  import { appliedLacksHost, appliedOf, appliedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
66
66
  import { PermissionFacts } from "./permission-facts.js";
67
67
  import { reportOwed, supportOf } from "./permission-runtime-reports.js";
68
- import { DeviceProviders, servesDialIn } from "./providers.js";
68
+ import { DeviceProviders, isInProcessName, servesDialIn, } from "./providers.js";
69
69
  import { isDeviceRequestNotSent } from "./request-not-sent.js";
70
70
  import { SandboxProviderUnreachableError } from "./unreachable.js";
71
71
  // Moved to leases.ts (phase C); re-exported for existing importers
@@ -589,7 +589,7 @@ let SandboxService = class SandboxService {
589
589
  }
590
590
  /**
591
591
  * The instance the device records now (its `created_at`), while it has one that runs or is
592
- * suspended; null otherwise. Read without a lease: a caller inside `withSandbox` reads the
592
+ * suspended; null otherwise. Read without a lease: a caller inside a use reads the
593
593
  * instance its own lease keeps.
594
594
  */
595
595
  async currentInstance(deviceId) {
@@ -609,8 +609,8 @@ let SandboxService = class SandboxService {
609
609
  * `instance.createdAt` (background tasks, spec 2026-11-05-background-bash-design §4.3). It never
610
610
  * creates, resumes or rebuilds one: an instance that is missing, suspended, being created or
611
611
  * destroyed (or recorded with another provider) is `not_running`, one that records another
612
- * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a `withSandbox`
613
- * holder does (its tag on every exec, crashed holders' operations revoked exactly), and
612
+ * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a use's
613
+ * holder does (crashed holders' operations revoked exactly), with its tag on every exec, and
614
614
  * `last_used_at` moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
615
615
  * (`sandbox.busy`); `signal` (optional) ends the wait with its abort reason. The signal passed
616
616
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
@@ -692,28 +692,12 @@ let SandboxService = class SandboxService {
692
692
  pathLease(deviceId, path, signal) {
693
693
  return this.leases.pathLease(deviceId, path, signal, PATH_LEASE_WAIT_MS);
694
694
  }
695
- /**
696
- * Runs `fn` on the device's instance: take a lease → make sure the instance runs (file
697
- * system, create / resume / rebuild, under the exclusive lease) → `fn` under a shared lease →
698
- * update `last_used_at` → release.
699
- * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
700
- * the wait and the creation / resume.
701
- * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
702
- * stop when the lease is lost.
703
- * - The provider passed to `fn` labels every `exec` with this holder's tag and `ctx.actor`.
704
- * - When `fn` throws `SandboxGoneError` (the instance is gone) the instance is rebuilt on the
705
- * kept files (or the one another holder rebuilt is taken) and `fn` runs once more with
706
- * `restarted: true`; a second `gone` is thrown. Other errors are thrown as they are.
707
- * - Lost files throw `device.files_lost` (409), also when `fn` throws
708
- * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
709
- * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
710
- * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
711
- */
712
695
  /** Trusted staging only. The callback receives no exec, browsing or lifecycle methods. */
713
696
  async withPreparation(ctx, purpose, roots, fn, signal) {
714
- return this.withSandboxUse(ctx, async () => {
715
- throw new Error("Preparation callback was not installed");
716
- }, signal, undefined, (h, provider, info, sig) => this.prepareFor(ctx, h, provider, info, purpose, roots, fn, sig));
697
+ return this.withSandboxUse(ctx, {
698
+ kind: "preparation",
699
+ run: (h, provider, info, sig) => this.prepareFor(ctx, h, provider, info, purpose, roots, fn, sig),
700
+ }, signal);
717
701
  }
718
702
  async prepareFor(ctx, h, provider, info, purpose, roots, fn, sig) {
719
703
  if (!provider.prepare)
@@ -843,15 +827,33 @@ let SandboxService = class SandboxService {
843
827
  c.runId !== ctx.actor.runId ||
844
828
  ctx.actor.conversationId !== ctx.holderConversationId)
845
829
  throw new SandboxScopeDeniedError("The kernel read does not match its run start");
846
- return this.withSandboxUse(ctx, fn, signal, undefined, undefined, read);
830
+ return this.withSandboxUse(ctx, { kind: "kernelRead", read, fn }, signal);
847
831
  }
848
832
  async withOperations(ctx, invocation, fn, signal) {
849
- return this.withSandboxUse(ctx, fn, signal, invocation);
850
- }
851
- async withSandbox(ctx, fn, signal) {
852
- return this.withSandboxUse(ctx, fn, signal);
833
+ return this.withSandboxUse(ctx, { kind: "operations", invocation, fn }, signal);
853
834
  }
854
- async withSandboxUse(ctx, fn, signal, invocation, trusted, kernelRead) {
835
+ /**
836
+ * Every use of the device's instance ({@link withOperations}, {@link withPreparation},
837
+ * {@link withKernelRead}; there is no raw route): take a lease → make sure the instance runs
838
+ * (file system, create / resume / rebuild, under the exclusive lease) → the route's callback
839
+ * under a shared lease → update `last_used_at` → release.
840
+ * - Waiting longer than `sandbox.lockWaitSeconds` throws `sandbox.busy` (409); `signal` aborts
841
+ * the wait and the creation / resume.
842
+ * - The fourth argument of `fn` combines `signal` with the lease's: use it for commands, so they
843
+ * stop when the lease is lost.
844
+ * - The provider passed to `fn` admits and claims every call (an operation or a kernel read)
845
+ * before it reaches the provider; a preparation gets only the staging methods.
846
+ * - When `SandboxGoneError` is raised outside a dispatched operation (staging, context
847
+ * evidence), the instance is rebuilt on the kept files (or the one another holder rebuilt is
848
+ * taken) and the route runs once more with `restarted: true`; a second `gone` is thrown. A
849
+ * gone after a durable dispatch stays unknown: the instance is rebuilt, the call is not
850
+ * retried. Other errors are thrown as they are.
851
+ * - Lost files throw `device.files_lost` (409), also when `fn` throws
852
+ * `FileSystemGoneError` (the files are then recorded lost, ruling R24).
853
+ * - When `ctx.holderConversationId` last used another instance (another holder rebuilt it
854
+ * meanwhile), `info.restarted` is true, so it learns its processes are gone (final review m5).
855
+ */
856
+ async withSandboxUse(ctx, route, signal) {
855
857
  const p = await this.require(ctx.deviceId, ctx.orgId);
856
858
  const env = ctx.deviceId;
857
859
  const holder = ctx.holderConversationId;
@@ -863,7 +865,7 @@ let SandboxService = class SandboxService {
863
865
  let left = false;
864
866
  try {
865
867
  try {
866
- return await this.runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead);
868
+ return await this.runAs(e, ctx, p, route, signal);
867
869
  }
868
870
  catch (err) {
869
871
  if (isFileSystemGoneError(err))
@@ -909,7 +911,7 @@ let SandboxService = class SandboxService {
909
911
  ? { fresh: true, restarted: false, filesReset: true }
910
912
  : { fresh: true, restarted: true };
911
913
  try {
912
- return await this.runAs({ ...e, info }, ctx, p, fn, signal, invocation, trusted, kernelRead);
914
+ return await this.runAs({ ...e, info }, ctx, p, route, signal);
913
915
  }
914
916
  catch (err2) {
915
917
  if (isFileSystemGoneError(err2))
@@ -1043,131 +1045,128 @@ let SandboxService = class SandboxService {
1043
1045
  }
1044
1046
  return e;
1045
1047
  }
1046
- /** Runs `fn` as the holder `e`: its tag and the caller's actor on every exec, its lease's signal. */
1047
- async runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead) {
1048
+ /** Runs the route as the holder `e`, under its lease's signal. */
1049
+ async runAs(e, ctx, p, route, signal) {
1048
1050
  const sig = AbortSignal.any([signal, e.lease.signal]);
1049
- if (trusted)
1050
- return trusted(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
1051
+ if (route.kind === "preparation")
1052
+ return route.run(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
1051
1053
  const env = ctx.deviceId;
1052
- if (kernelRead)
1053
- return fn(e.handle, this.kernelReadProvider(e, ctx, p, kernelRead, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
1054
+ if (route.kind === "kernelRead")
1055
+ return route.fn(e.handle, this.kernelReadProvider(e, ctx, p, route.read, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
1056
+ const { invocation, fn } = route;
1054
1057
  let ordinal = 0;
1055
1058
  // a provider's background starts are told the held instance's kernel generation
1056
1059
  const held = withKernelGeneration(p.impl, String(e.createdAt));
1057
- const impl = invocation
1058
- ? createHeldOperations(held, e.handle, sig, async (method, input, invoke, preflight) => {
1059
- const identity = { ...invocation, ordinal: ordinal++ };
1060
- sig.throwIfAborted();
1061
- await this.register(env, e.lease.token);
1062
- const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
1063
- provider: p.plugin,
1064
- providerVersion: p.version,
1065
- generation: String(e.createdAt),
1066
- }, method, input, e.lease.token, sig));
1067
- const pending = await refreshPending();
1068
- // An acknowledged start returns its recorded exact ref; it never dispatches again.
1069
- if (pending.state === "background-running" && pending.execution_ref)
1070
- return parseSandboxExecutionRef(pending.execution_ref);
1071
- if (pending.state === "completed")
1072
- return (await this.operationIntents.result(pending));
1073
- let current;
1074
- try {
1075
- current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1076
- }
1077
- catch (error) {
1078
- if (!(error instanceof PermissionAdmissionStale))
1079
- throw error;
1080
- await refreshPending();
1081
- current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1082
- }
1083
- // Kernel checks on the admitted scope come before any dispatch state is written.
1084
- if (preflight &&
1085
- current.state !== "completed" &&
1086
- current.state !== "background-running") {
1087
- try {
1088
- await preflight(parseSandboxOperationScope(current.scope), sig);
1089
- }
1090
- catch (error) {
1091
- if (current.state === "admitted" &&
1092
- (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
1093
- const kind = failureKindOf(error);
1094
- await runOutsideTransaction(() => this.operationIntents.refusePreDispatch(ctx, identity, {
1095
- kind,
1096
- message: error.message,
1097
- }));
1098
- }
1099
- throw error;
1100
- }
1101
- }
1102
- const reconciling = ["dispatching", "started-or-unknown"].includes(pending.state);
1103
- // a dial-in device's machine must be connected before a new dispatch is recorded: its
1104
- // typed answer (offline, machine revoked, device deleted) proves nothing was sent
1105
- if (!reconciling && current.state === "admitted" && this.relay && servesDialIn(p))
1106
- await this.relay.connection(env);
1107
- const admitted = reconciling
1108
- ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1109
- provider: p.plugin,
1110
- providerVersion: p.version,
1111
- generation: String(e.createdAt),
1112
- }, method, input, e.lease.token))
1113
- : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
1114
- ? backgroundBinding(input, e.handle.id)
1115
- : undefined));
1116
- if (admitted.state === "revoked")
1117
- throw admitted.outcome_unknown
1118
- ? new SandboxOperationOutcomeUnknownError("The background task was stopped before its start was confirmed; it is not started again and its cancellation is owed")
1119
- : new SandboxScopeDeniedError("The background task was stopped or settled before it launched; nothing was started");
1120
- if (admitted.state === "background-running" && admitted.execution_ref)
1121
- return parseSandboxExecutionRef(admitted.execution_ref);
1122
- if (admitted.state === "completed")
1123
- return (await this.operationIntents.result(admitted));
1124
- sig.throwIfAborted();
1125
- let result;
1060
+ const impl = createHeldOperations(held, e.handle, sig, async (method, input, invoke, preflight) => {
1061
+ const identity = { ...invocation, ordinal: ordinal++ };
1062
+ sig.throwIfAborted();
1063
+ await this.register(env, e.lease.token);
1064
+ const refreshPending = () => runOutsideTransaction(() => this.operationIntents.pending(ctx, identity, {
1065
+ provider: p.plugin,
1066
+ providerVersion: p.version,
1067
+ generation: String(e.createdAt),
1068
+ }, method, input, e.lease.token, sig));
1069
+ const pending = await refreshPending();
1070
+ // An acknowledged start returns its recorded exact ref; it never dispatches again.
1071
+ if (pending.state === "background-running" && pending.execution_ref)
1072
+ return parseSandboxExecutionRef(pending.execution_ref);
1073
+ if (pending.state === "completed")
1074
+ return (await this.operationIntents.result(pending));
1075
+ let current;
1076
+ try {
1077
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1078
+ }
1079
+ catch (error) {
1080
+ if (!(error instanceof PermissionAdmissionStale))
1081
+ throw error;
1082
+ await refreshPending();
1083
+ current = await runOutsideTransaction(() => this.operationIntents.admit(ctx, identity));
1084
+ }
1085
+ // Kernel checks on the admitted scope come before any dispatch state is written.
1086
+ if (preflight && current.state !== "completed" && current.state !== "background-running") {
1126
1087
  try {
1127
- result = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1088
+ await preflight(parseSandboxOperationScope(current.scope), sig);
1128
1089
  }
1129
1090
  catch (error) {
1130
- if (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error)) {
1131
- if (["dispatching", "started-or-unknown"].includes(pending.state)) {
1132
- await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1133
- throw new SandboxOperationOutcomeUnknownError("The recorded operation remains unknown; changed runtime authority cannot prove it had no effect", { cause: error });
1134
- }
1091
+ if (current.state === "admitted" &&
1092
+ (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error))) {
1135
1093
  const kind = failureKindOf(error);
1136
- await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1137
- $failure: { kind, message: error.message },
1094
+ await runOutsideTransaction(() => this.operationIntents.refusePreDispatch(ctx, identity, {
1095
+ kind,
1096
+ message: error.message,
1138
1097
  }));
1139
- throw error;
1140
1098
  }
1141
- await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1142
- // The machine's files are gone (R24): the operation stays unknown, and the caller still
1143
- // records the files lost so later calls fail without reaching the machine.
1144
- if (isFileSystemGoneError(error))
1145
- throw error;
1146
- // A transport/gone error after durable dispatch cannot justify a new identity retry.
1147
- throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1099
+ throw error;
1148
1100
  }
1149
- // The provider has returned: storage/serialization errors cannot establish denial.
1150
- if (method === "backgroundStart") {
1151
- try {
1152
- await runOutsideTransaction(() => this.operationIntents.acknowledgeBackground(admitted.operation_id, admitted.execution_id, result, e.handle.id));
1153
- }
1154
- catch (error) {
1101
+ }
1102
+ const reconciling = ["dispatching", "started-or-unknown"].includes(pending.state);
1103
+ // a dial-in device's machine must be connected before a new dispatch is recorded: its
1104
+ // typed answer (offline, machine revoked, device deleted) proves nothing was sent
1105
+ if (!reconciling && current.state === "admitted" && this.relay && servesDialIn(p))
1106
+ await this.relay.connection(env);
1107
+ const admitted = reconciling
1108
+ ? await runOutsideTransaction(() => this.operationIntents.claimReconciliation(ctx, identity, {
1109
+ provider: p.plugin,
1110
+ providerVersion: p.version,
1111
+ generation: String(e.createdAt),
1112
+ }, method, input, e.lease.token))
1113
+ : await runOutsideTransaction(() => this.operationIntents.claimDispatch(ctx, identity, e.lease.token, method === "backgroundStart"
1114
+ ? backgroundBinding(input, e.handle.id)
1115
+ : undefined));
1116
+ if (admitted.state === "revoked")
1117
+ throw admitted.outcome_unknown
1118
+ ? new SandboxOperationOutcomeUnknownError("The background task was stopped before its start was confirmed; it is not started again and its cancellation is owed")
1119
+ : new SandboxScopeDeniedError("The background task was stopped or settled before it launched; nothing was started");
1120
+ if (admitted.state === "background-running" && admitted.execution_ref)
1121
+ return parseSandboxExecutionRef(admitted.execution_ref);
1122
+ if (admitted.state === "completed")
1123
+ return (await this.operationIntents.result(admitted));
1124
+ sig.throwIfAborted();
1125
+ let result;
1126
+ try {
1127
+ result = await invoke(parseSandboxOperationScope(admitted.scope), sig);
1128
+ }
1129
+ catch (error) {
1130
+ if (isSandboxScopeDeniedError(error) || isSandboxPermissionUnsupportedError(error)) {
1131
+ if (["dispatching", "started-or-unknown"].includes(pending.state)) {
1155
1132
  await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1156
- throw new SandboxOperationOutcomeUnknownError("The start returned but could not be acknowledged; reconcile the same identity", { cause: error });
1133
+ throw new SandboxOperationOutcomeUnknownError("The recorded operation remains unknown; changed runtime authority cannot prove it had no effect", { cause: error });
1157
1134
  }
1158
- return result;
1135
+ const kind = failureKindOf(error);
1136
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1137
+ $failure: { kind, message: error.message },
1138
+ }));
1139
+ throw error;
1159
1140
  }
1141
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1142
+ // The machine's files are gone (R24): the operation stays unknown, and the caller still
1143
+ // records the files lost so later calls fail without reaching the machine.
1144
+ if (isFileSystemGoneError(error))
1145
+ throw error;
1146
+ // A transport/gone error after durable dispatch cannot justify a new identity retry.
1147
+ throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1148
+ }
1149
+ // The provider has returned: storage/serialization errors cannot establish denial.
1150
+ if (method === "backgroundStart") {
1160
1151
  try {
1161
- await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, result));
1152
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeBackground(admitted.operation_id, admitted.execution_id, result, e.handle.id));
1162
1153
  }
1163
1154
  catch (error) {
1164
1155
  await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1165
- throw new SandboxOperationOutcomeUnknownError("The operation returned but its result could not be retained; reconcile the same identity", { cause: error });
1156
+ throw new SandboxOperationOutcomeUnknownError("The start returned but could not be acknowledged; reconcile the same identity", { cause: error });
1166
1157
  }
1167
1158
  return result;
1168
- })
1169
- : createLegacyHeldProvider(p.impl, e.lease.token, ctx.actor, () => this.register(env, e.lease.token));
1170
- const contextEvidence = invocation?.contextEvidence
1159
+ }
1160
+ try {
1161
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, result));
1162
+ }
1163
+ catch (error) {
1164
+ await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1165
+ throw new SandboxOperationOutcomeUnknownError("The operation returned but its result could not be retained; reconcile the same identity", { cause: error });
1166
+ }
1167
+ return result;
1168
+ });
1169
+ const contextEvidence = invocation.contextEvidence
1171
1170
  ? await this.heldContextEvidence(ctx, p, e)
1172
1171
  : undefined;
1173
1172
  const info = {
@@ -1175,7 +1174,7 @@ let SandboxService = class SandboxService {
1175
1174
  roots: rootsOf(e.handle),
1176
1175
  ...(contextEvidence && { contextEvidence }),
1177
1176
  };
1178
- if (invocation?.beforeUser)
1177
+ if (invocation.beforeUser)
1179
1178
  await invocation.beforeUser({
1180
1179
  prepare: (purpose, roots, stage) => this.prepareFor(ctx, e.handle, p.impl, info, purpose, roots, stage, sig),
1181
1180
  }, info, sig);
@@ -1821,8 +1820,10 @@ let SandboxService = class SandboxService {
1821
1820
  * (with intent, so running commands finish and new ones wait) up to 10 minutes. Without the
1822
1821
  * provider of its instance row loaded it throws and the row stays, marked `sweep_failed_at` (the
1823
1822
  * job is retried, and the destruction sweep finishes a deleted device once the provider is
1824
- * back). The provider only needs to be loaded: a device is deleted while its org has the
1825
- * provider off too.
1823
+ * back). A provider that is no longer installed on this deployment (no install record, or its
1824
+ * catalog item removed; never an in-process `@…` one) will not be back: the instance is
1825
+ * abandoned instead ({@link abandonInstance}) and the call returns (#675). The provider only
1826
+ * needs to be loaded: a device is deleted while its org has the provider off too.
1826
1827
  */
1827
1828
  async destroyDevice(deviceId) {
1828
1829
  const row = await this.db
@@ -1835,6 +1836,10 @@ let SandboxService = class SandboxService {
1835
1836
  const p = row.provider !== null
1836
1837
  ? this.providers.forDevice(row.provider)
1837
1838
  : await this.providerOf(deviceId);
1839
+ if (!p && row.provider !== null && !(await this.providerInstalled(row.provider))) {
1840
+ await this.abandonInstance(deviceId, row.provider);
1841
+ return;
1842
+ }
1838
1843
  if (!p) {
1839
1844
  await this.db
1840
1845
  .updateTable("device_instances")
@@ -1861,6 +1866,77 @@ let SandboxService = class SandboxService {
1861
1866
  await lease.release();
1862
1867
  }
1863
1868
  }
1869
+ /**
1870
+ * Whether `provider` is still installed on this deployment: an in-process `@…` provider always
1871
+ * counts (code, not an install), a plugin while its install record exists and the catalog item
1872
+ * it was installed from (if any) is not removed. Not loaded on this replica is a separate case.
1873
+ */
1874
+ async providerInstalled(provider) {
1875
+ if (isInProcessName(provider))
1876
+ return true;
1877
+ const install = await this.db
1878
+ .selectFrom("extension_installs as i")
1879
+ .leftJoin("catalog_items as c", "c.id", "i.catalog_item_id")
1880
+ .select(["i.catalog_item_id", "c.id as item_id", "c.deleted_at"])
1881
+ .where("i.name", "=", provider)
1882
+ .executeTakeFirst();
1883
+ if (!install)
1884
+ return false;
1885
+ return install.catalog_item_id === null || (install.item_id !== null && !install.deleted_at);
1886
+ }
1887
+ /**
1888
+ * Abandons the instance of a deleted device whose provider is no longer installed (#675): the
1889
+ * kernel can never destroy it, so the row is kept as the record of the provider-side names
1890
+ * (`handle`, `fs_handle`, `prev_handle`), marked `abandoned_at`, and one platform audit event
1891
+ * (`device.instance_abandoned`, for the super admin) carries the same names. One statement, so
1892
+ * the mark and its event commit together, and only the first call writes either (a retried job
1893
+ * finds the row abandoned and does nothing). The sweeps iterate loaded providers only, so
1894
+ * nothing retries the row; a plugin of that name installed again destroys it as before.
1895
+ */
1896
+ async abandonInstance(deviceId, provider) {
1897
+ const written = await this.db
1898
+ .with("a", (db) => db
1899
+ .updateTable("device_instances")
1900
+ .set({ abandoned_at: sql `now()`, sweep_failed_at: null })
1901
+ .where("device_id", "=", deviceId)
1902
+ .where("provider", "=", provider)
1903
+ .where("abandoned_at", "is", null)
1904
+ .returning([
1905
+ "device_id",
1906
+ "provider",
1907
+ "handle",
1908
+ "fs_handle",
1909
+ "prev_provider",
1910
+ "prev_handle",
1911
+ ]))
1912
+ .insertInto("audit_events")
1913
+ .columns(["action", "target", "detail"])
1914
+ .expression((eb) => eb
1915
+ .selectFrom("a")
1916
+ .leftJoin("devices as d", "d.id", "a.device_id")
1917
+ .select([
1918
+ sql `'device.instance_abandoned'`.as("action"),
1919
+ "a.device_id as target",
1920
+ sql `jsonb_build_object(
1921
+ 'orgId', d.org_id,
1922
+ 'provider', a.provider,
1923
+ 'handle', a.handle,
1924
+ 'fsHandle', a.fs_handle,
1925
+ 'prevProvider', a.prev_provider,
1926
+ 'prevHandle', a.prev_handle,
1927
+ 'reason', 'provider_uninstalled'
1928
+ )`.as("detail"),
1929
+ ]))
1930
+ .returning("detail")
1931
+ .execute();
1932
+ if (written.length > 0) {
1933
+ this.log.warn("device instance abandoned: its provider is no longer installed", {
1934
+ deviceId,
1935
+ provider,
1936
+ detail: written[0]?.detail,
1937
+ });
1938
+ }
1939
+ }
1864
1940
  /**
1865
1941
  * Starts the device over with empty files (after `device.files_lost`, or on request):
1866
1942
  * under the exclusive lease (waited for like {@link destroyDevice}) destroys any instance and
@@ -2801,7 +2877,7 @@ let SandboxService = class SandboxService {
2801
2877
  // Lease lost (or the device read failed) before the handle was recorded: destroy the new
2802
2878
  // instance (best effort) so it does not leak. A provider that reuses instances by name
2803
2879
  // (Ruling M10) may then hit the one the new holder just resumed or created; that heals:
2804
- // its next provider call throws SandboxGoneError (or resume returns gone) and withSandbox
2880
+ // its next provider call throws SandboxGoneError (or resume returns gone) and the use
2805
2881
  // rebuilds in place. The file system is never touched here.
2806
2882
  await p.impl.destroy(handle, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)).catch((err) => this.log.warn("cannot destroy sandbox created after the lock was lost", {
2807
2883
  deviceId: id,