@capybara-hq/kernel 0.1.0-rc.117 → 0.1.0-rc.118

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 (61) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/catalog/component-scope.service.js +2 -1
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/plugin-install.d.ts +1 -0
  6. package/dist/catalog/plugin-install.js +11 -1
  7. package/dist/conversations/conversations.controller.d.ts +1 -1
  8. package/dist/conversations/conversations.controller.js +1 -1
  9. package/dist/conversations/conversations.service.d.ts +4 -2
  10. package/dist/conversations/conversations.service.js +17 -3
  11. package/dist/conversations/events.d.ts +9 -1
  12. package/dist/conversations/events.js +2 -0
  13. package/dist/db/kernel-schema.d.ts +15 -1
  14. package/dist/devices/devices.controller.d.ts +5 -0
  15. package/dist/devices/devices.controller.js +20 -2
  16. package/dist/devices/devices.service.d.ts +3 -1
  17. package/dist/devices/devices.service.js +4 -0
  18. package/dist/evals/plan.d.ts +3 -1
  19. package/dist/evals/plan.js +25 -5
  20. package/dist/evals/runs.service.js +3 -2
  21. package/dist/evals/trajectory.js +1 -0
  22. package/dist/files/blob-references.d.ts +8 -0
  23. package/dist/files/blob-references.js +19 -0
  24. package/dist/files/blob-sweep.job.js +5 -23
  25. package/dist/files/library-files.service.js +8 -4
  26. package/dist/models/cache-write-usage.d.ts +3 -0
  27. package/dist/models/cache-write-usage.js +26 -0
  28. package/dist/models/images.js +5 -1
  29. package/dist/models/prices.d.ts +8 -6
  30. package/dist/models/prices.js +28 -3
  31. package/dist/orgs/settings.controller.d.ts +4 -17
  32. package/dist/orgs/settings.controller.js +5 -9
  33. package/dist/orgs/settings.service.d.ts +12 -0
  34. package/dist/orgs/settings.service.js +24 -0
  35. package/dist/platform/exclusions.js +6 -0
  36. package/dist/platform/ops/admin.ops.js +2 -2
  37. package/dist/platform/ops/conversations.ops.js +1 -1
  38. package/dist/platform/ops/devices.ops.js +7 -0
  39. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  40. package/dist/platform/ops/org-settings.ops.js +10 -10
  41. package/dist/runtime/context/build.d.ts +2 -0
  42. package/dist/runtime/context/build.js +9 -1
  43. package/dist/runtime/usage-report.js +3 -0
  44. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  45. package/dist/sandbox/legacy-retirement.js +243 -3
  46. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  47. package/dist/sandbox/permission-instance-writes.js +55 -1
  48. package/dist/sandbox/providers.d.ts +6 -1
  49. package/dist/sandbox/providers.js +15 -1
  50. package/dist/sandbox/sandbox.service.d.ts +6 -3
  51. package/dist/sandbox/sandbox.service.js +116 -5
  52. package/dist/tools/builtins/sandbox/common.js +10 -6
  53. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  54. package/dist/tools/connectors.service.d.ts +3 -1
  55. package/dist/tools/connectors.service.js +64 -12
  56. package/dist/tools/drift.d.ts +1 -1
  57. package/dist/tools/drift.js +13 -13
  58. package/package.json +2 -2
  59. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  60. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  61. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
@@ -15,6 +15,15 @@ export interface RetirementObligation {
15
15
  /** When it was recorded (a cloud `unknown` one resolves only if recorded after the freeze). */
16
16
  createdAt: Date;
17
17
  }
18
+ /** An owner-initiated proof check, fenced to the machine and current kernel incarnation it read. */
19
+ export interface LocalRetirementCheck {
20
+ orgId: string;
21
+ deviceId: string;
22
+ accountId: string;
23
+ machineId: string;
24
+ currentGeneration: string;
25
+ fence: number;
26
+ }
18
27
  /** {@link LegacyRetirementStore.freeze}'s answer: the freeze is published and enumerated. */
19
28
  export interface LegacyFreezeResult {
20
29
  /** When the freeze was first published (a rerun keeps it). */
@@ -242,6 +251,12 @@ export declare class LegacyRetirementStore {
242
251
  * correlated on `o.id`.
243
252
  */
244
253
  private lateMember;
254
+ /** The exact old obligations the owner may check, within their guarded org. */
255
+ quarantinedLocal(check: LocalRetirementCheck): Promise<RetirementObligation[]>;
256
+ /** Correlate the kernel incarnation to a single exact generation of the local provider. */
257
+ localProviderGeneration(o: RetirementObligation): Promise<string | undefined>;
258
+ /** Commit exact evidence only while all identities seen by the owner check still hold. */
259
+ resolveLocalProof(check: LocalRetirementCheck, o: RetirementObligation, providerGeneration: string | undefined, signal: AbortSignal): Promise<void>;
245
260
  /** The members of one obligation, oldest first. */
246
261
  membersOf(obligationId: string): Promise<RetirementMember[]>;
247
262
  /**
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { parseSandboxExecutionRef } from "@capybara-hq/plugin-sdk";
10
11
  import { Inject, Injectable } from "@nestjs/common";
11
12
  import { sql } from "kysely";
12
13
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -14,6 +15,7 @@ import { asPlatform } from "../infra/database/org-scope.js";
14
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
15
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
16
17
  import { PermissionAuthorityLock } from "./permission-authority-lock.js";
18
+ import { LOCAL_RETIREMENT_PROVIDER, RETIREMENT_GENERATION } from "./providers.js";
17
19
  /**
18
20
  * Legacy retirement (permission runtime cutover phase 8.5): the durable legacy-launch freeze and
19
21
  * the physical no-reuse obligations of old instance incarnations (migration 0157).
@@ -37,7 +39,9 @@ import { PermissionAuthorityLock } from "./permission-authority-lock.js";
37
39
  * (`SandboxService` gate), the same for every provider: an incarnation is destroyed whole by its
38
40
  * provider (confirmed destruction, the file system kept) or found destroyed by a recorded
39
41
  * confirmed destruction; a replaced one without recorded destruction and an unknown one are
40
- * quarantined. Nothing here resolves on a new generation, a timeout or a process scan.
42
+ * quarantined. The owner can resolve exact local retirement through verified machine proof.
43
+ * That path records its provenance and reopens when a newly discovered member needs checking.
44
+ * Nothing here resolves on a new generation, a timeout or a process scan.
41
45
  */
42
46
  /** The freeze's single row id. */
43
47
  const FREEZE_ID = "platform";
@@ -106,6 +110,19 @@ function legacyKey(r) {
106
110
  (current && r.instance_provider ? r.instance_provider : "unknown");
107
111
  return { provider, generation };
108
112
  }
113
+ function localGenerationOf(refValue, deviceId, operationId) {
114
+ try {
115
+ const ref = parseSandboxExecutionRef(refValue);
116
+ return ref.instanceId === deviceId &&
117
+ ref.operationId === operationId &&
118
+ RETIREMENT_GENERATION.test(ref.instanceGeneration)
119
+ ? ref.instanceGeneration
120
+ : undefined;
121
+ }
122
+ catch {
123
+ return undefined;
124
+ }
125
+ }
109
126
  const toObligation = (r) => ({
110
127
  id: r.id,
111
128
  deviceId: r.device_id,
@@ -316,8 +333,8 @@ let LegacyRetirementStore = class LegacyRetirementStore {
316
333
  * all). The `(status = 'running' OR kill_pending OR sid IS NULL)` conjunct is the partial index's
317
334
  * predicate (0157), stated as is so the planner can use it.
318
335
  */
319
- // org-filter: a query fragment, not run here: its callers (the retirement sweep's methods)
320
- // execute it inside their asPlatform
336
+ // org-filter: callers execute this fragment inside the platform sweep or add the owner check's
337
+ // exact org to it before it runs
321
338
  legacyCandidates(deviceId) {
322
339
  let q = this.db
323
340
  .selectFrom("background_tasks as t")
@@ -642,6 +659,226 @@ let LegacyRetirementStore = class LegacyRetirementStore {
642
659
  .where("li.revoke_acknowledged", "=", true))),
643
660
  ]));
644
661
  }
662
+ /** The exact old obligations the owner may check, within their guarded org. */
663
+ async quarantinedLocal(check) {
664
+ const rows = await this.db
665
+ .selectFrom("device_retirement_obligations")
666
+ .selectAll()
667
+ .where("org_id", "=", check.orgId)
668
+ .where("device_id", "=", check.deviceId)
669
+ .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
670
+ .where("state", "=", "quarantined")
671
+ .orderBy("id", "asc")
672
+ .execute();
673
+ return rows
674
+ .map(toObligation)
675
+ .filter((row) => RETIREMENT_GENERATION.test(row.instanceGeneration) &&
676
+ BigInt(row.instanceGeneration) < BigInt(check.currentGeneration));
677
+ }
678
+ /** Correlate the kernel incarnation to a single exact generation of the local provider. */
679
+ async localProviderGeneration(o) {
680
+ if (o.provider !== LOCAL_RETIREMENT_PROVIDER ||
681
+ !RETIREMENT_GENERATION.test(o.instanceGeneration))
682
+ return undefined;
683
+ const identity = await this.db
684
+ .selectFrom("device_instance_retirement_identities")
685
+ .select("provider_generation")
686
+ .where("org_id", "=", o.orgId)
687
+ .where("device_id", "=", o.deviceId)
688
+ .where("provider", "=", o.provider)
689
+ .where("instance_generation", "=", o.instanceGeneration)
690
+ .executeTakeFirst();
691
+ const members = await this.db
692
+ .selectFrom("device_retirement_members as m")
693
+ .leftJoin("sandbox_operation_intents as i", (join) => join.onRef("i.operation_id", "=", "m.ref_id").on("i.org_id", "=", o.orgId))
694
+ .select([
695
+ "m.kind",
696
+ "m.ref_id",
697
+ "i.device_id",
698
+ "i.provider",
699
+ "i.method",
700
+ "i.state",
701
+ "i.instance_generation",
702
+ "i.execution_ref",
703
+ ])
704
+ .where("m.obligation_id", "=", o.id)
705
+ .execute();
706
+ if (members.some((member) => member.kind !== "revoked-start" ||
707
+ member.device_id !== o.deviceId ||
708
+ member.provider !== o.provider ||
709
+ member.method !== "backgroundStart" ||
710
+ member.state !== "revoked" ||
711
+ member.instance_generation !== o.instanceGeneration))
712
+ return undefined;
713
+ // The scanner may not have attached an earlier launch yet. A relevant legacy launch or a
714
+ // divergent retained managed ref defeats proof even before it becomes a member.
715
+ const legacy = await this.legacyCandidates(o.deviceId)
716
+ .where("t.org_id", "=", o.orgId)
717
+ .execute();
718
+ if (legacy.some((candidate) => {
719
+ const origin = legacyKey(candidate);
720
+ return (origin.generation === o.instanceGeneration &&
721
+ (origin.provider === o.provider || origin.provider === "unknown"));
722
+ }))
723
+ return undefined;
724
+ const references = this.db
725
+ .selectFrom("sandbox_operation_intents")
726
+ .select(["operation_id", "execution_ref"])
727
+ .where("org_id", "=", o.orgId)
728
+ .where("device_id", "=", o.deviceId)
729
+ .where("provider", "=", o.provider)
730
+ .where("method", "=", "backgroundStart")
731
+ .where("execution_ref", "is not", null);
732
+ const retained = await references
733
+ .where("instance_generation", "=", o.instanceGeneration)
734
+ .execute();
735
+ let generation = identity?.provider_generation;
736
+ for (const row of [
737
+ ...members.map((member) => ({
738
+ operation_id: member.ref_id,
739
+ execution_ref: member.execution_ref,
740
+ })),
741
+ ...retained,
742
+ ]) {
743
+ const claimed = localGenerationOf(row.execution_ref, o.deviceId, row.operation_id);
744
+ if (claimed === undefined || (generation !== undefined && generation !== claimed))
745
+ return undefined;
746
+ generation = claimed;
747
+ }
748
+ if (generation === undefined)
749
+ return undefined;
750
+ const reverse = await references
751
+ .where("instance_generation", "!=", o.instanceGeneration)
752
+ .where(sql `execution_ref ->> 'instanceGeneration'`, "=", generation)
753
+ .execute();
754
+ if (reverse.some((r) => localGenerationOf(r.execution_ref, o.deviceId, r.operation_id) !== undefined))
755
+ return undefined;
756
+ const conflicting = await this.db
757
+ .selectFrom("device_instance_retirement_identities")
758
+ .select("instance_generation")
759
+ .where("org_id", "=", o.orgId)
760
+ .where("device_id", "=", o.deviceId)
761
+ .where("provider", "=", o.provider)
762
+ .where("provider_generation", "=", generation)
763
+ .where("instance_generation", "!=", o.instanceGeneration)
764
+ .executeTakeFirst();
765
+ return conflicting === undefined ? generation : undefined;
766
+ }
767
+ /** Commit exact evidence only while all identities seen by the owner check still hold. */
768
+ async resolveLocalProof(check, o, providerGeneration, signal) {
769
+ signal.throwIfAborted();
770
+ if (o.orgId !== check.orgId ||
771
+ o.deviceId !== check.deviceId ||
772
+ o.provider !== LOCAL_RETIREMENT_PROVIDER ||
773
+ !RETIREMENT_GENERATION.test(o.instanceGeneration) ||
774
+ BigInt(o.instanceGeneration) >= BigInt(check.currentGeneration))
775
+ return;
776
+ const org = await this.db
777
+ .selectFrom("orgs")
778
+ .select("id")
779
+ .where("id", "=", check.orgId)
780
+ .where("deleted_at", "is", null)
781
+ .forShare()
782
+ .executeTakeFirst();
783
+ const member = org &&
784
+ (await this.db
785
+ .selectFrom("memberships")
786
+ .select("account_id")
787
+ .where("org_id", "=", check.orgId)
788
+ .where("account_id", "=", check.accountId)
789
+ .forShare()
790
+ .executeTakeFirst());
791
+ if (!member)
792
+ return;
793
+ const owner = await this.db
794
+ .selectFrom("devices")
795
+ .select("id")
796
+ .where("org_id", "=", check.orgId)
797
+ .where("id", "=", check.deviceId)
798
+ .where("owner_kind", "=", "personal")
799
+ .where("owner_account_id", "=", check.accountId)
800
+ .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
801
+ .where("deleted_at", "is", null)
802
+ .forNoKeyUpdate()
803
+ .executeTakeFirst();
804
+ if (!owner)
805
+ return;
806
+ const machine = await this.db
807
+ .selectFrom("device_machines")
808
+ .select("id")
809
+ .where("org_id", "=", check.orgId)
810
+ .where("device_id", "=", check.deviceId)
811
+ .where("account_id", "=", check.accountId)
812
+ .where("id", "=", check.machineId)
813
+ .where("revoked_at", "is", null)
814
+ .forShare()
815
+ .executeTakeFirst();
816
+ if (!machine)
817
+ return;
818
+ const instance = await this.db
819
+ .selectFrom("device_instances")
820
+ .select("created_at")
821
+ .where("org_id", "=", check.orgId)
822
+ .where("device_id", "=", check.deviceId)
823
+ .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
824
+ .where("generation", "=", check.fence)
825
+ .where("status", "in", ["running", "suspended"])
826
+ .where("handle", "is not", null)
827
+ .where("had_instance", "=", true)
828
+ .forUpdate()
829
+ .executeTakeFirst();
830
+ if (String(instance?.created_at.getTime()) !== check.currentGeneration)
831
+ return;
832
+ // Same row lock as addMember. A conflicting member that arrived during the RPC defeats proof.
833
+ const obligation = await this.db
834
+ .selectFrom("device_retirement_obligations")
835
+ .select("id")
836
+ .where("org_id", "=", check.orgId)
837
+ .where("device_id", "=", check.deviceId)
838
+ .where("provider", "=", o.provider)
839
+ .where("instance_generation", "=", o.instanceGeneration)
840
+ .where("id", "=", o.id)
841
+ .where("state", "=", "quarantined")
842
+ .forUpdate()
843
+ .executeTakeFirst();
844
+ if (!obligation)
845
+ return;
846
+ const recorded = await this.destructionRecorded(o.deviceId, o.provider, o.instanceGeneration);
847
+ if (!recorded &&
848
+ (providerGeneration === undefined ||
849
+ (await this.localProviderGeneration(o)) !== providerGeneration))
850
+ return;
851
+ signal.throwIfAborted();
852
+ if (!recorded && providerGeneration !== undefined)
853
+ await this.db
854
+ .insertInto("device_instance_retirement_identities")
855
+ .values({
856
+ org_id: o.orgId,
857
+ device_id: o.deviceId,
858
+ provider: o.provider,
859
+ instance_generation: o.instanceGeneration,
860
+ provider_generation: providerGeneration,
861
+ attested_at: sql `now()`,
862
+ })
863
+ .onConflict((oc) => oc
864
+ .columns(["org_id", "device_id", "provider", "instance_generation"])
865
+ .doUpdateSet({ attested_at: sql `now()` }))
866
+ .execute();
867
+ // Unconditional destruction readers, including older replicas and operation reconciliation,
868
+ // must never consume machine proof without checking the whole obligation's provenance.
869
+ await this.db
870
+ .updateTable("device_retirement_obligations")
871
+ .set({
872
+ state: "resolved",
873
+ resolution: "provider-destroyed",
874
+ resolved_at: sql `now()`,
875
+ last_error: null,
876
+ })
877
+ .where("org_id", "=", check.orgId)
878
+ .where("id", "=", o.id)
879
+ .execute();
880
+ signal.throwIfAborted();
881
+ }
645
882
  /** The members of one obligation, oldest first. */
646
883
  async membersOf(obligationId) {
647
884
  const rows = await this.db
@@ -912,6 +1149,9 @@ __decorate([
912
1149
  __decorate([
913
1150
  Transactional({ propagation: "requires_new" })
914
1151
  ], LegacyRetirementStore.prototype, "resolveCancelled", null);
1152
+ __decorate([
1153
+ Transactional({ propagation: "requires_new" })
1154
+ ], LegacyRetirementStore.prototype, "resolveLocalProof", null);
915
1155
  LegacyRetirementStore = __decorate([
916
1156
  Injectable()
917
1157
  // org-filter: deployment-wide retirement of legacy launches: the worker sweeps (retire-legacy-tasks
@@ -40,7 +40,10 @@ export declare class PermissionInstanceWrites {
40
40
  * handle and its evidence appear together (B-15). Absent: none recorded (a failed read leaves
41
41
  * the instance unprobed).
42
42
  */
43
- commitHandle(orgId: string, deviceId: string, generation: number, roots: SandboxRoots, set: UpdateObject<KernelDatabase, "device_instances">, signal: AbortSignal, evidence?: SupportReport): Promise<Date>;
43
+ commitHandle(orgId: string, deviceId: string, generation: number, roots: SandboxRoots, set: UpdateObject<KernelDatabase, "device_instances">, signal: AbortSignal, evidence?: SupportReport, providerGeneration?: string): Promise<Date>;
44
+ /** Preserve the exact old handle pairing before a lifecycle write can discard that handle. */
45
+ preserveRetirementIdentity(orgId: string, deviceId: string, fence: number, providerGeneration: string, signal: AbortSignal): Promise<void>;
46
+ private recordRetirementIdentity;
44
47
  /**
45
48
  * Records an instance's permission support read after a resume, a limits change, a provider
46
49
  * version change or a new report revision, under the caller's lifecycle lease (B-15). Recorded only while the
@@ -16,6 +16,7 @@ import { canonicalJson } from "../tools/canonical-json.js";
16
16
  import { SandboxLockLostError } from "./leases.js";
17
17
  import { PermissionCeilingWrites } from "./permission-ceiling-writes.js";
18
18
  import { PermissionRuntimeReports } from "./permission-runtime-reports.js";
19
+ import { LOCAL_RETIREMENT_PROVIDER } from "./providers.js";
19
20
  const rootKey = (r) => JSON.stringify([r.workspace, r.skills, r.tmp]);
20
21
  /** The greatest epoch millisecond a JavaScript Date (and so a generation) can represent. */
21
22
  export const MAX_GENERATION_MS = 8_640_000_000_000_000;
@@ -46,7 +47,7 @@ let PermissionInstanceWrites = class PermissionInstanceWrites {
46
47
  * handle and its evidence appear together (B-15). Absent: none recorded (a failed read leaves
47
48
  * the instance unprobed).
48
49
  */
49
- async commitHandle(orgId, deviceId, generation, roots, set, signal, evidence) {
50
+ async commitHandle(orgId, deviceId, generation, roots, set, signal, evidence, providerGeneration) {
50
51
  signal.throwIfAborted();
51
52
  await this.lockDevice(orgId, deviceId);
52
53
  await this.ceilings.lock({ orgId, deviceId }, "device");
@@ -83,10 +84,60 @@ let PermissionInstanceWrites = class PermissionInstanceWrites {
83
84
  throw new SandboxLockLostError(deviceId, "generation");
84
85
  if (updated.created_at.getTime() !== createdAt.getTime())
85
86
  throw new Error("Instance generation was not stored exactly; check the database clock type");
87
+ if (providerGeneration !== undefined)
88
+ await this.recordRetirementIdentity(orgId, deviceId, createdAt, providerGeneration);
86
89
  if (evidence)
87
90
  await this.reports.recordSupport(deviceId, evidence.provider, evidence.version, evidence.report);
88
91
  return updated.created_at;
89
92
  }
93
+ /** Preserve the exact old handle pairing before a lifecycle write can discard that handle. */
94
+ async preserveRetirementIdentity(orgId, deviceId, fence, providerGeneration, signal) {
95
+ signal.throwIfAborted();
96
+ await this.lockDevice(orgId, deviceId);
97
+ const row = await this.db
98
+ .selectFrom("device_instances")
99
+ .select("created_at")
100
+ .where("device_id", "=", deviceId)
101
+ .where("org_id", "=", orgId)
102
+ .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
103
+ .where("generation", "=", fence)
104
+ .where("handle", "is not", null)
105
+ .where("had_instance", "=", true)
106
+ .forUpdate()
107
+ .executeTakeFirst();
108
+ if (!row)
109
+ throw new SandboxLockLostError(deviceId, "generation");
110
+ signal.throwIfAborted();
111
+ await this.recordRetirementIdentity(orgId, deviceId, row.created_at, providerGeneration);
112
+ signal.throwIfAborted();
113
+ }
114
+ async recordRetirementIdentity(orgId, deviceId, createdAt, providerGeneration) {
115
+ const generation = String(createdAt.getTime());
116
+ const r = await this.db
117
+ .insertInto("device_instance_retirement_identities")
118
+ .values({
119
+ org_id: orgId,
120
+ device_id: deviceId,
121
+ provider: LOCAL_RETIREMENT_PROVIDER,
122
+ instance_generation: generation,
123
+ provider_generation: providerGeneration,
124
+ })
125
+ .onConflict((oc) => oc.doNothing())
126
+ .returning("provider_generation")
127
+ .executeTakeFirst();
128
+ if (r !== undefined)
129
+ return;
130
+ const existing = await this.db
131
+ .selectFrom("device_instance_retirement_identities")
132
+ .select("provider_generation")
133
+ .where("org_id", "=", orgId)
134
+ .where("device_id", "=", deviceId)
135
+ .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
136
+ .where("instance_generation", "=", generation)
137
+ .executeTakeFirst();
138
+ if (existing?.provider_generation !== providerGeneration)
139
+ throw new InconsistentGenerationError("The local provider returned a conflicting generation");
140
+ }
90
141
  /**
91
142
  * Records an instance's permission support read after a resume, a limits change, a provider
92
143
  * version change or a new report revision, under the caller's lifecycle lease (B-15). Recorded only while the
@@ -216,6 +267,9 @@ let PermissionInstanceWrites = class PermissionInstanceWrites {
216
267
  __decorate([
217
268
  Transactional({ propagation: "requires_new" })
218
269
  ], PermissionInstanceWrites.prototype, "commitHandle", null);
270
+ __decorate([
271
+ Transactional({ propagation: "requires_new" })
272
+ ], PermissionInstanceWrites.prototype, "preserveRetirementIdentity", null);
219
273
  __decorate([
220
274
  Transactional({ propagation: "requires_new" })
221
275
  ], PermissionInstanceWrites.prototype, "recordSupport", null);
@@ -1,10 +1,15 @@
1
- import { type DeviceProvider } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceProvider, type SandboxHandle } from "@capybara-hq/plugin-sdk";
2
2
  import { ExtensionRegistry } from "../extensions/registry.js";
3
3
  /**
4
4
  * An in-process provider name: it starts with `@`, which no extension name can
5
5
  * (`EXTENSION_NAME_RE`), so it never collides with a loaded `device-provider@1` plugin.
6
6
  */
7
7
  export declare const isInProcessName: (name: string) => boolean;
8
+ /** Only this provider's machine journal can attest a local retirement. */
9
+ export declare const LOCAL_RETIREMENT_PROVIDER = "device-local";
10
+ export declare const RETIREMENT_GENERATION: RegExp;
11
+ /** The optional provider identity is immutable evidence about this exact committed handle. */
12
+ export declare function localRetirementGeneration(provider: DeviceProviderEntry, handle: SandboxHandle, deviceId: string): string | undefined;
8
13
  /**
9
14
  * Whether a provider serves its devices over the dial-in channel: it implements
10
15
  * `DeviceProvider.dialIn` (an extension may only when it declares `permissions.dialIn`, checked
@@ -7,7 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { DEVICE_PROVIDER_EXTENSION_POINT } from "@capybara-hq/plugin-sdk";
10
+ import { DEVICE_PROVIDER_EXTENSION_POINT, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { ExtensionRegistry } from "../extensions/registry.js";
13
13
  import { guardProviderConnection } from "./unreachable.js";
@@ -16,6 +16,20 @@ import { guardProviderConnection } from "./unreachable.js";
16
16
  * (`EXTENSION_NAME_RE`), so it never collides with a loaded `device-provider@1` plugin.
17
17
  */
18
18
  export const isInProcessName = (name) => name.startsWith("@");
19
+ /** Only this provider's machine journal can attest a local retirement. */
20
+ export const LOCAL_RETIREMENT_PROVIDER = "device-local";
21
+ export const RETIREMENT_GENERATION = /^[1-9][0-9]{0,15}$/;
22
+ /** The optional provider identity is immutable evidence about this exact committed handle. */
23
+ export function localRetirementGeneration(provider, handle, deviceId) {
24
+ if (provider.plugin !== LOCAL_RETIREMENT_PROVIDER ||
25
+ handle.id !== deviceId ||
26
+ !servesDialIn(provider))
27
+ return undefined;
28
+ const generation = provider.impl.retirement?.generation(handle);
29
+ return typeof generation === "string" && RETIREMENT_GENERATION.test(generation)
30
+ ? generation
31
+ : undefined;
32
+ }
19
33
  /**
20
34
  * Whether a provider serves its devices over the dial-in channel: it implements
21
35
  * `DeviceProvider.dialIn` (an extension may only when it declares `permissions.dialIn`, checked
@@ -20,7 +20,7 @@ import { DeviceReports } from "./device-reports.js";
20
20
  import type { DeviceSandbox, HostGrantCeiling } from "./device-sandbox.js";
21
21
  import { type KernelReadInvocation } from "./kernel-read.js";
22
22
  import { SandboxLeases, type SandboxPathLease } from "./leases.js";
23
- import { LegacyRetirementStore } from "./legacy-retirement.js";
23
+ import { LegacyRetirementStore, type LocalRetirementCheck } from "./legacy-retirement.js";
24
24
  import { type AppliedLimits, type DeviceLimits, type EffectiveDevicePolicy } from "./modes.js";
25
25
  import type { HeldDeviceContextEvidence } from "./permission-context-types.js";
26
26
  import { PermissionFacts } from "./permission-facts.js";
@@ -203,7 +203,7 @@ export declare const retirementPending: () => ApiError;
203
203
  * will ever cover it (an incarnation replaced without a recorded confirmed destruction, or an
204
204
  * unknown one it cannot clear) (503, 8.5): the owner deletes the device and creates it again.
205
205
  */
206
- export declare const recreateRequired: () => ApiError;
206
+ export declare const recreateRequired: (local?: boolean) => ApiError;
207
207
  /**
208
208
  * The kernel's sandbox service over the `device-provider@1` provider, keyed by **device** (spec
209
209
  * 2026-11-07-environments-design §4.2, §5.1): one file system kept until the device is
@@ -308,7 +308,7 @@ export declare class SandboxService {
308
308
  /** Whether a device's provider serves its org now (read at every use, never cached). */
309
309
  selection: Pick<DeviceProviderSelection, "isOnInOrg">, config: Pick<KernelConfigService, "get" | "fieldSource">, log: Pick<KernelLogger, "info" | "warn">, facts: Pick<PermissionFacts, "devicePolicy" | "assertCloudReconciled" | "readHeldEnvironment" | "readDevice" | "deviceSandbox" | "deviceSandboxFacts" | "orgHostGrantCeiling">, operationIntents: SandboxOperationIntents, authority: SandboxOperationAuthority, instanceWrites: PermissionInstanceWrites,
310
310
  /** The retirement obligations every lifecycle acquisition is gated on (8.5). */
311
- retirement: Pick<LegacyRetirementStore, "unresolved" | "hasUnresolved" | "scanUntilStable" | "frozen" | "frozenAt" | "quarantine" | "noteFailure" | "resolveDestroyed" | "resolveCancelled" | "membersOf" | "recordDestruction" | "destructionRecorded">,
311
+ retirement: Pick<LegacyRetirementStore, "unresolved" | "hasUnresolved" | "scanUntilStable" | "frozen" | "frozenAt" | "quarantine" | "noteFailure" | "resolveDestroyed" | "resolveCancelled" | "membersOf" | "recordDestruction" | "destructionRecorded" | "quarantinedLocal" | "localProviderGeneration" | "resolveLocalProof">,
312
312
  /** The cloud snapshot writer's reconcile, for the lifecycle reconcile of marked devices (B-12). */
313
313
  snapshots: Pick<CloudPermissionSnapshots, "reconcileHeld">,
314
314
  /** The stored device report, refreshed after a create or a resume (never fails the use). */
@@ -864,6 +864,9 @@ export declare class SandboxService {
864
864
  * provider is not loaded, or when its instance row names another provider.
865
865
  */
866
866
  resetFileSystem(deviceId: string): Promise<void>;
867
+ /** The owner's proof-only pass of the retirement gate, with no provider lifecycle mutation. */
868
+ checkLocalRetirement(owner: Pick<LocalRetirementCheck, "orgId" | "deviceId" | "accountId">, requested: AbortSignal): Promise<"clear" | "blocked" | "busy">;
869
+ private ownerLocalProvider;
867
870
  /**
868
871
  * The worker's retirement of a device's old incarnations (8.5, `RetireLegacyTasksJob`): one try
869
872
  * at the exclusive lifecycle lease, then the same gate as every acquisition. `busy`: a holder