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

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 (106) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/automations/unattended.d.ts +2 -0
  4. package/dist/automations/unattended.js +10 -3
  5. package/dist/catalog/component-scope.service.js +2 -1
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-install.d.ts +1 -0
  8. package/dist/catalog/plugin-install.js +11 -1
  9. package/dist/channels/cards.d.ts +2 -4
  10. package/dist/channels/cards.js +11 -6
  11. package/dist/channels/phrases.d.ts +4 -0
  12. package/dist/channels/phrases.js +1 -0
  13. package/dist/conversations/conversations.controller.d.ts +1 -1
  14. package/dist/conversations/conversations.controller.js +1 -1
  15. package/dist/conversations/conversations.service.d.ts +4 -2
  16. package/dist/conversations/conversations.service.js +19 -3
  17. package/dist/conversations/events.d.ts +35 -1
  18. package/dist/conversations/events.js +29 -4
  19. package/dist/ctx/create-ctx.d.ts +1 -1
  20. package/dist/ctx/create-ctx.js +4 -0
  21. package/dist/db/kernel-schema.d.ts +31 -1
  22. package/dist/device-access/device-access.module.js +2 -0
  23. package/dist/device-access/device-access.service.d.ts +16 -2
  24. package/dist/device-access/device-access.service.js +59 -2
  25. package/dist/device-access/site-access-request.d.ts +14 -0
  26. package/dist/device-access/site-access-request.js +35 -0
  27. package/dist/device-access/site-grants.d.ts +53 -0
  28. package/dist/device-access/site-grants.js +268 -0
  29. package/dist/device-access/site-grants.module.d.ts +2 -0
  30. package/dist/device-access/site-grants.module.js +14 -0
  31. package/dist/devices/devices.controller.d.ts +5 -0
  32. package/dist/devices/devices.controller.js +20 -2
  33. package/dist/devices/devices.service.d.ts +3 -1
  34. package/dist/devices/devices.service.js +6 -0
  35. package/dist/evals/plan.d.ts +3 -1
  36. package/dist/evals/plan.js +25 -5
  37. package/dist/evals/runs.service.js +3 -2
  38. package/dist/evals/trajectory.js +1 -0
  39. package/dist/extensions/admin-ops.js +7 -0
  40. package/dist/extensions/org-config.js +4 -0
  41. package/dist/extensions/permission-set.d.ts +3 -0
  42. package/dist/extensions/permission-set.js +5 -0
  43. package/dist/extensions/permission-view.d.ts +1 -1
  44. package/dist/extensions/permission-view.js +7 -1
  45. package/dist/files/blob-references.d.ts +8 -0
  46. package/dist/files/blob-references.js +19 -0
  47. package/dist/files/blob-sweep.job.js +5 -23
  48. package/dist/files/library-files.service.js +8 -4
  49. package/dist/models/cache-write-usage.d.ts +3 -0
  50. package/dist/models/cache-write-usage.js +26 -0
  51. package/dist/models/images.js +5 -1
  52. package/dist/models/prices.d.ts +8 -6
  53. package/dist/models/prices.js +28 -3
  54. package/dist/orgs/offboarding.js +2 -0
  55. package/dist/orgs/settings.controller.d.ts +4 -17
  56. package/dist/orgs/settings.controller.js +5 -9
  57. package/dist/orgs/settings.service.d.ts +12 -0
  58. package/dist/orgs/settings.service.js +24 -0
  59. package/dist/platform/exclusions.js +6 -0
  60. package/dist/platform/ops/admin.ops.js +2 -2
  61. package/dist/platform/ops/conversations.ops.js +1 -1
  62. package/dist/platform/ops/devices.ops.js +7 -0
  63. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  64. package/dist/platform/ops/org-settings.ops.js +10 -10
  65. package/dist/roles/worker.module.js +2 -0
  66. package/dist/runtime/context/build.d.ts +2 -0
  67. package/dist/runtime/context/build.js +9 -1
  68. package/dist/runtime/usage-report.js +3 -0
  69. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  70. package/dist/sandbox/legacy-retirement.js +243 -3
  71. package/dist/sandbox/loopback-expiry.job.d.ts +3 -1
  72. package/dist/sandbox/loopback-expiry.job.js +9 -3
  73. package/dist/sandbox/operation-authority.d.ts +1 -1
  74. package/dist/sandbox/operation-authority.js +14 -6
  75. package/dist/sandbox/permission-call-types.d.ts +2 -2
  76. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  77. package/dist/sandbox/permission-instance-writes.js +55 -1
  78. package/dist/sandbox/providers.d.ts +6 -1
  79. package/dist/sandbox/providers.js +15 -1
  80. package/dist/sandbox/review/classifier.d.ts +13 -4
  81. package/dist/sandbox/review/classifier.js +73 -22
  82. package/dist/sandbox/review/permission-candidate.d.ts +3 -3
  83. package/dist/sandbox/review/permission-candidate.js +10 -8
  84. package/dist/sandbox/review/review.service.d.ts +26 -19
  85. package/dist/sandbox/review/review.service.js +69 -15
  86. package/dist/sandbox/sandbox.service.d.ts +6 -3
  87. package/dist/sandbox/sandbox.service.js +116 -5
  88. package/dist/tools/approvals.service.d.ts +30 -4
  89. package/dist/tools/approvals.service.js +143 -12
  90. package/dist/tools/builtins/sandbox/common.js +10 -6
  91. package/dist/tools/call-scope.d.ts +3 -0
  92. package/dist/tools/call-scope.js +1 -0
  93. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  94. package/dist/tools/connectors.service.d.ts +3 -1
  95. package/dist/tools/connectors.service.js +64 -12
  96. package/dist/tools/drift.d.ts +1 -1
  97. package/dist/tools/drift.js +13 -13
  98. package/dist/tools/network-asks.js +7 -0
  99. package/dist/tools/pipeline.d.ts +16 -5
  100. package/dist/tools/pipeline.js +314 -11
  101. package/dist/tools/tools.module.js +2 -0
  102. package/package.json +2 -2
  103. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  104. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  105. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
  106. package/src/migrations/0205_device_site_grants.sql +30 -0
@@ -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
@@ -1,3 +1,4 @@
1
+ import { DeviceSiteGrants } from "../device-access/site-grants.js";
1
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
3
  import { LockService } from "../infra/lock/lock.service.js";
3
4
  import type { KernelLogger } from "../log.js";
@@ -16,6 +17,7 @@ export declare class LoopbackExpiryJob {
16
17
  readonly config: KernelConfigService;
17
18
  readonly lockService: LockService;
18
19
  readonly log: KernelLogger;
19
- constructor(grants: Pick<LoopbackGrants, "expireDue">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
20
+ private readonly site?;
21
+ constructor(grants: Pick<LoopbackGrants, "expireDue">, config: KernelConfigService, lockService: LockService, log: KernelLogger, site?: DeviceSiteGrants | undefined);
20
22
  expire(): Promise<void>;
21
23
  }
@@ -7,7 +7,8 @@ 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 { Inject, Injectable } from "@nestjs/common";
10
+ import { Inject, Injectable, Optional } from "@nestjs/common";
11
+ import { DeviceSiteGrants } from "../device-access/site-grants.js";
11
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
13
  import { LockService } from "../infra/lock/lock.service.js";
13
14
  import { LockedInterval } from "../infra/schedule/locked-interval.js";
@@ -27,14 +28,17 @@ let LoopbackExpiryJob = class LoopbackExpiryJob {
27
28
  config;
28
29
  lockService;
29
30
  log;
30
- constructor(grants, config, lockService, log) {
31
+ site;
32
+ constructor(grants, config, lockService, log, site) {
31
33
  this.grants = grants;
32
34
  this.config = config;
33
35
  this.lockService = lockService;
34
36
  this.log = log;
37
+ this.site = site;
35
38
  }
36
39
  async expire() {
37
40
  await this.grants.expireDue();
41
+ await this.site?.purgeEnded();
38
42
  }
39
43
  };
40
44
  __decorate([
@@ -45,6 +49,8 @@ LoopbackExpiryJob = __decorate([
45
49
  __param(0, Inject(LoopbackGrants)),
46
50
  __param(1, Inject(KernelConfigService)),
47
51
  __param(2, Inject(LockService)),
48
- __param(3, Inject(KERNEL_LOGGER))
52
+ __param(3, Inject(KERNEL_LOGGER)),
53
+ __param(4, Optional()),
54
+ __param(4, Inject(DeviceSiteGrants))
49
55
  ], LoopbackExpiryJob);
50
56
  export { LoopbackExpiryJob };
@@ -91,7 +91,7 @@ export declare class SandboxOperationAuthority {
91
91
  deviceId: string;
92
92
  rootConversationId: string;
93
93
  }>;
94
- previewCall(ctx: SandboxUseContext, call: PermissionCallRef, signal: AbortSignal): Promise<PermissionReviewSnapshot>;
94
+ previewCall(ctx: SandboxUseContext, call: PermissionCallRef, signal: AbortSignal, crossing?: "site-access"): Promise<PermissionReviewSnapshot>;
95
95
  private previewLocked;
96
96
  resolve(ctx: SandboxUseContext, operation: SandboxAuthorityOperation, signal: AbortSignal): Promise<SandboxOperationScope>;
97
97
  resolveInvocation(ctx: SandboxUseContext, operation: SandboxAuthorityOperation, call: PermissionCallRef, signal: AbortSignal): Promise<{
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { instanceSupported, parseSandboxBrowseScope, parseSandboxOperationScope, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { hasUnattendedTaskRun } from "../automations/unattended.js";
14
15
  import { ACTOR_DEVICE_ACCESS_REASON, ACTOR_NOT_DEVICE_OWNER_REASON, PermissionContextV2Schema, permissionCodePointCompare, } from "../conversations/events.js";
15
16
  import { PermissionProfileStore, } from "../conversations/permission-profile-store.js";
16
17
  import { canonicalRoot, workingRootOf as reviewWorkingRootOf } from "../devices/working-root.js";
@@ -201,12 +202,12 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
201
202
  const root = await this.profiles.readOwnedRoot(ctx.orgId, ctx.holderConversationId, ctx.actor.accountId);
202
203
  return { orgId: ctx.orgId, deviceId: ctx.deviceId, rootConversationId: root.id };
203
204
  }
204
- async previewCall(ctx, call, signal) {
205
+ async previewCall(ctx, call, signal, crossing) {
205
206
  const subject = await this.subjectFor(ctx);
206
- return withTransactionFencePrelude(() => this.locks.acquire(subject, { kind: "admit" }), () => this.previewLocked(ctx, call, signal));
207
+ return withTransactionFencePrelude(() => this.locks.acquire(subject, { kind: "admit" }), () => this.previewLocked(ctx, call, signal, crossing));
207
208
  }
208
- async previewLocked(ctx, call, signal) {
209
- const snapshot = await this.snapshot(ctx, call, signal);
209
+ async previewLocked(ctx, call, signal, crossing) {
210
+ const snapshot = await this.snapshot(ctx, call, signal, undefined, crossing === undefined ? {} : { crossing });
210
211
  const messages = await this.db
211
212
  .selectFrom("conversation_events")
212
213
  .select("payload")
@@ -472,8 +473,15 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
472
473
  throw new ApiError("device.not_found", "The conversation is not bound to this device");
473
474
  await this.facts.preview(ctx.orgId, ctx.actor.accountId, ctx.deviceId, root.project_name ?? undefined);
474
475
  let unattended = root.automation_id !== null;
475
- if (ctx.actor.runId)
476
- unattended ||= await this.runScheduledLocked(ctx.holderConversationId, ctx.actor.accountId, ctx.actor.runId);
476
+ if (ctx.actor.runId && !unattended) {
477
+ const scheduled = await this.runScheduledLocked(ctx.holderConversationId, ctx.actor.accountId, ctx.actor.runId);
478
+ // Attended site actions use the root's profile even after a person joins a scheduled run.
479
+ // Sandbox operation admission keeps its stricter scheduled-run policy.
480
+ unattended =
481
+ scheduled &&
482
+ (opts.crossing !== "site-access" ||
483
+ (await hasUnattendedTaskRun(this.db.db, ctx.actor.runId)));
484
+ }
477
485
  const base = await this.baseScopeLocked({
478
486
  orgId: ctx.orgId,
479
487
  deviceId: ctx.deviceId,
@@ -57,9 +57,9 @@ export type PermissionGrantSource = PermissionGrantDecision["source"];
57
57
  /**
58
58
  * The kind of one boundary crossing, as `ReviewRecord.crossing` records it: a directory outside the
59
59
  * scope, a new host on an allowlist, running one call outside the sandbox, a sensitive command, or
60
- * a device service (the browser) reaching one loopback port on the person's own device.
60
+ * a device service reaching one loopback port or acting on a site using the person's browser session.
61
61
  */
62
- export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive" | "loopback-port";
62
+ export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive" | "loopback-port" | "site-access";
63
63
  /**
64
64
  * What a call grant authorizes: an exact directory and host expansion of the restricted scope, or
65
65
  * one Bash call run outside the OS sandbox (per-call sandbox escalation: full execution for that
@@ -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
@@ -1,4 +1,4 @@
1
- import { type HookParentScope, type Logger, type ModelRequest } from "@capybara-hq/plugin-sdk";
1
+ import { type HookParentScope, type Logger, type ModelRequest, type SiteAccessAction } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import type { ModelRef } from "../../agents/definition.js";
4
4
  import type { EventLog } from "../../conversations/event-log.js";
@@ -34,6 +34,8 @@ export declare const REVIEW_SYSTEM_PROMPT: string;
34
34
  * machine, not a command. Command, write and read reviews keep {@link REVIEW_SYSTEM_PROMPT}.
35
35
  */
36
36
  export declare const LOOPBACK_REVIEW_SYSTEM_PROMPT: string;
37
+ /** The review policy for one browser action using the person's session on a site. */
38
+ export declare const SITE_ACCESS_REVIEW_SYSTEM_PROMPT: string;
37
39
  /** The answer cap of the classifier call (one sentence is far less). */
38
40
  export declare const REVIEW_MAX_OUTPUT_TOKENS = 300;
39
41
  /** The marker a command (or path) cut to fit the review model's context ends with. */
@@ -46,7 +48,7 @@ export declare const REVIEW_ASK_REASON = "The command review could not decide; t
46
48
  export declare const REVIEW_UNAVAILABLE_PREFIX = "Command review is unavailable: ";
47
49
  /**
48
50
  * The system prompt of one classifier call: {@link REVIEW_SYSTEM_PROMPT} naming its data tag, or
49
- * for a loopback port review {@link LOOPBACK_REVIEW_SYSTEM_PROMPT}.
51
+ * the dedicated prompt for a loopback port or site access review.
50
52
  */
51
53
  export declare function reviewSystemPrompt(tag: string, kind?: ReviewClassifierInput["kind"]): string;
52
54
  /** A fresh data tag (`review-` and 16 hex digits): text inside the tags cannot forge the structure. */
@@ -57,9 +59,9 @@ export interface ReviewClassifierInput {
57
59
  mode: "auto" | "sandbox";
58
60
  /**
59
61
  * The command for `Bash`, the path for a file write or a file read, or a device service's
60
- * request to reach a loopback port on the person's own device (`loopback`).
62
+ * request to reach a loopback port or act on a site.
61
63
  */
62
- kind: "command" | "write" | "read" | "loopback-port";
64
+ kind: "command" | "write" | "read" | "loopback-port" | "site-access";
63
65
  text: string;
64
66
  /** The directory the command runs in (the workspace for a file write). */
65
67
  cwd: string;
@@ -86,6 +88,11 @@ export interface ReviewClassifierInput {
86
88
  url: string | null;
87
89
  database: boolean;
88
90
  };
91
+ /** The non-loopback origin and action. The request detail is carried in `text`. */
92
+ siteAccess?: {
93
+ origin: string;
94
+ action: SiteAccessAction;
95
+ };
89
96
  }
90
97
  /**
91
98
  * The user message of the classifier call: the facts, the untrusted command or path, the rule
@@ -216,6 +223,8 @@ export interface ReviewModelCall {
216
223
  usageIdemKey: string;
217
224
  /** The idempotency key of a `hook_denied` event (default `hook_denied_review:<run>:<call>`). */
218
225
  hookDeniedIdemKey?: string | undefined;
226
+ /** Provider diagnostics and free-form classifier output can echo private request detail. */
227
+ privateInput?: true;
219
228
  /** The outcome texts (default the command review's). */
220
229
  outcomes?: ReviewOutcomeTexts | undefined;
221
230
  }