@capybara-hq/kernel 0.1.0-rc.121 → 0.1.0-rc.123

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 (230) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/background/finish.d.ts +5 -1
  3. package/dist/background/finish.js +29 -18
  4. package/dist/background/launch.d.ts +0 -5
  5. package/dist/background/launch.js +1 -6
  6. package/dist/background/managed.js +1 -4
  7. package/dist/background/poll.job.d.ts +3 -25
  8. package/dist/background/poll.job.js +20 -112
  9. package/dist/background/render.d.ts +2 -8
  10. package/dist/background/render.js +3 -17
  11. package/dist/background/stop.d.ts +15 -16
  12. package/dist/background/stop.js +39 -76
  13. package/dist/background/store.d.ts +17 -45
  14. package/dist/background/store.js +60 -94
  15. package/dist/background/tasks.service.d.ts +2 -5
  16. package/dist/background/tasks.service.js +9 -20
  17. package/dist/background/wake.js +3 -2
  18. package/dist/catalog/admin-catalog.controller.d.ts +2 -18
  19. package/dist/catalog/admin-catalog.controller.js +2 -28
  20. package/dist/catalog/catalog-content.d.ts +1 -5
  21. package/dist/catalog/catalog-items.d.ts +2 -6
  22. package/dist/catalog/catalog-items.js +5 -26
  23. package/dist/catalog/catalog-scope.service.d.ts +1 -121
  24. package/dist/catalog/catalog-scope.service.js +12 -552
  25. package/dist/catalog/catalog.service.d.ts +4 -15
  26. package/dist/catalog/catalog.service.js +7 -35
  27. package/dist/catalog/job-ids.d.ts +0 -18
  28. package/dist/catalog/job-ids.js +0 -20
  29. package/dist/catalog/marketplaces.service.d.ts +1 -1
  30. package/dist/catalog/org-catalog.service.js +6 -20
  31. package/dist/catalog/org-plugin-uploads.controller.d.ts +4 -19
  32. package/dist/catalog/org-plugin-uploads.controller.js +6 -34
  33. package/dist/catalog/org-plugin-uploads.d.ts +3 -10
  34. package/dist/catalog/org-plugin-uploads.js +4 -18
  35. package/dist/catalog/org-plugin-uploads.schemas.js +0 -1
  36. package/dist/catalog/owned-items.d.ts +6 -11
  37. package/dist/catalog/owned-items.js +10 -20
  38. package/dist/catalog/ownership.d.ts +3 -29
  39. package/dist/catalog/ownership.js +4 -54
  40. package/dist/catalog/platform-components.d.ts +5 -11
  41. package/dist/catalog/platform-components.js +8 -15
  42. package/dist/catalog/plugin-import.d.ts +3 -42
  43. package/dist/catalog/plugin-import.js +26 -195
  44. package/dist/catalog/plugin-install.js +1 -6
  45. package/dist/catalog/plugin-package.d.ts +1 -0
  46. package/dist/catalog/plugin-package.js +5 -0
  47. package/dist/catalog/plugin-upgrade.d.ts +3 -26
  48. package/dist/catalog/plugin-upgrade.js +20 -103
  49. package/dist/catalog/request-rules.js +4 -6
  50. package/dist/catalog/scope-sync.js +2 -4
  51. package/dist/catalog/scope.d.ts +2 -5
  52. package/dist/channels/jobs.d.ts +3 -3
  53. package/dist/channels/jobs.js +4 -3
  54. package/dist/channels/outbound.d.ts +1 -0
  55. package/dist/channels/outbound.js +32 -8
  56. package/dist/config/load.d.ts +0 -25
  57. package/dist/config/load.js +0 -57
  58. package/dist/config/schema.js +2 -3
  59. package/dist/conversations/attachments.service.js +3 -5
  60. package/dist/conversations/conversations.service.d.ts +3 -3
  61. package/dist/conversations/conversations.service.js +3 -3
  62. package/dist/conversations/job-org.d.ts +3 -0
  63. package/dist/conversations/job-org.js +11 -0
  64. package/dist/conversations/prompt-suggestions.d.ts +2 -7
  65. package/dist/conversations/prompt-suggestions.js +29 -27
  66. package/dist/conversations/titles.d.ts +3 -4
  67. package/dist/conversations/titles.js +19 -30
  68. package/dist/db/kernel-schema.d.ts +6 -16
  69. package/dist/db/pool.js +7 -2
  70. package/dist/devices/devices.controller.d.ts +0 -5
  71. package/dist/devices/devices.controller.js +2 -20
  72. package/dist/devices/devices.service.d.ts +1 -17
  73. package/dist/devices/devices.service.js +0 -22
  74. package/dist/errors.d.ts +1 -5
  75. package/dist/errors.js +1 -5
  76. package/dist/evals/judge.d.ts +3 -0
  77. package/dist/evals/judge.js +1 -1
  78. package/dist/evals/run-replay.d.ts +1 -1
  79. package/dist/evals/run-replay.js +26 -29
  80. package/dist/evals/step-replay.d.ts +3 -1
  81. package/dist/evals/step-replay.js +10 -1
  82. package/dist/evals/worker.d.ts +3 -1
  83. package/dist/evals/worker.js +53 -21
  84. package/dist/extensions/deployment-config-store.js +18 -14
  85. package/dist/extensions/effective-config.d.ts +1 -5
  86. package/dist/extensions/effective-config.js +1 -5
  87. package/dist/extensions/hooks.d.ts +3 -1
  88. package/dist/extensions/hooks.js +7 -2
  89. package/dist/extensions/installs.d.ts +2 -14
  90. package/dist/extensions/installs.js +10 -32
  91. package/dist/extensions/org-config.d.ts +3 -4
  92. package/dist/extensions/org-config.js +3 -4
  93. package/dist/extensions/plugin-guides.d.ts +0 -1
  94. package/dist/extensions/plugin-guides.js +0 -1
  95. package/dist/extensions/plugin-icons.d.ts +0 -1
  96. package/dist/extensions/plugin-icons.js +0 -3
  97. package/dist/files/blob-sweep.job.d.ts +2 -11
  98. package/dist/files/blob-sweep.job.js +7 -21
  99. package/dist/files/hash-job.d.ts +5 -15
  100. package/dist/files/hash-job.js +14 -33
  101. package/dist/files/library-jobs.module.d.ts +1 -6
  102. package/dist/files/library-jobs.module.js +3 -9
  103. package/dist/identity/api-tokens.js +54 -40
  104. package/dist/identity/auth.guard.js +2 -2
  105. package/dist/identity/sessions.js +7 -3
  106. package/dist/identity/settings.js +5 -21
  107. package/dist/inbox/inbox.service.d.ts +2 -3
  108. package/dist/inbox/org-notices.d.ts +0 -14
  109. package/dist/inbox/platform-inbox.service.d.ts +1 -8
  110. package/dist/inbox/platform-inbox.service.js +2 -6
  111. package/dist/inbox/platform-notices.d.ts +3 -3
  112. package/dist/index.d.ts +0 -4
  113. package/dist/index.js +0 -3
  114. package/dist/infra/database/database.module.js +2 -1
  115. package/dist/infra/database/org-scope.d.ts +5 -3
  116. package/dist/infra/database/org-scope.js +7 -1
  117. package/dist/infra/database/scoped-dialect.d.ts +3 -1
  118. package/dist/infra/database/scoped-dialect.js +17 -5
  119. package/dist/infra/events/kernel-events.d.ts +2 -0
  120. package/dist/infra/outbox/outbox.service.d.ts +2 -0
  121. package/dist/infra/outbox/outbox.service.js +10 -0
  122. package/dist/infra/outbox/registry.d.ts +0 -41
  123. package/dist/infra/outbox/registry.js +0 -37
  124. package/dist/models/embeddings.d.ts +0 -5
  125. package/dist/models/embeddings.js +28 -35
  126. package/dist/models/images.d.ts +3 -8
  127. package/dist/models/images.js +19 -37
  128. package/dist/models/purposes.d.ts +7 -2
  129. package/dist/models/purposes.js +16 -3
  130. package/dist/orgs/device-network-setting.d.ts +0 -44
  131. package/dist/orgs/device-network-setting.js +0 -83
  132. package/dist/orgs/invitations.service.js +34 -30
  133. package/dist/orgs/offboarding.d.ts +2 -2
  134. package/dist/orgs/offboarding.js +2 -2
  135. package/dist/orgs/orgs.service.d.ts +1 -1
  136. package/dist/orgs/orgs.service.js +19 -15
  137. package/dist/orgs/settings.service.d.ts +19 -14
  138. package/dist/orgs/settings.service.js +12 -37
  139. package/dist/platform/exclusions.js +0 -11
  140. package/dist/platform/ops/catalog-admin.ops.js +0 -8
  141. package/dist/platform/ops/devices.ops.js +0 -28
  142. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  143. package/dist/platform/ops/inbox.ops.js +5 -22
  144. package/dist/platform/ops/org-plugins.ops.d.ts +1 -3
  145. package/dist/platform/ops/org-plugins.ops.js +11 -67
  146. package/dist/roles/worker.module.js +0 -9
  147. package/dist/runtime/hook-calls.d.ts +13 -6
  148. package/dist/runtime/hook-calls.js +26 -4
  149. package/dist/runtime/maintenance.d.ts +3 -12
  150. package/dist/runtime/maintenance.js +25 -55
  151. package/dist/runtime/model-call.d.ts +4 -2
  152. package/dist/runtime/model-call.js +59 -58
  153. package/dist/runtime/providers.d.ts +27 -1
  154. package/dist/runtime/providers.js +57 -0
  155. package/dist/runtime/run-jobs.d.ts +1 -1
  156. package/dist/runtime/run-processors.d.ts +3 -9
  157. package/dist/runtime/run-worker.d.ts +2 -0
  158. package/dist/runtime/run-worker.js +23 -8
  159. package/dist/runtime/subagents/deliveries.js +6 -1
  160. package/dist/runtime/subagents/dispatch.d.ts +3 -3
  161. package/dist/runtime/write-base.service.d.ts +2 -3
  162. package/dist/runtime/write-base.service.js +3 -5
  163. package/dist/sandbox/device-sandbox-settings.d.ts +38 -92
  164. package/dist/sandbox/device-sandbox-settings.js +19 -325
  165. package/dist/sandbox/jobs.d.ts +3 -14
  166. package/dist/sandbox/jobs.js +2 -20
  167. package/dist/sandbox/modes.d.ts +5 -45
  168. package/dist/sandbox/modes.js +3 -60
  169. package/dist/sandbox/operation-authority.js +0 -11
  170. package/dist/sandbox/operation-intents.d.ts +32 -9
  171. package/dist/sandbox/operation-intents.js +241 -32
  172. package/dist/sandbox/operation-intents.module.js +2 -1
  173. package/dist/sandbox/operation-reconcile.job.d.ts +9 -11
  174. package/dist/sandbox/operation-reconcile.job.js +119 -33
  175. package/dist/sandbox/operation-revoke.d.ts +20 -0
  176. package/dist/sandbox/operation-revoke.js +3 -0
  177. package/dist/sandbox/permission-ceiling-writes.d.ts +1 -2
  178. package/dist/sandbox/permission-ceiling-writes.js +3 -6
  179. package/dist/sandbox/permission-config-publication.d.ts +1 -28
  180. package/dist/sandbox/permission-config-publication.js +14 -211
  181. package/dist/sandbox/permission-facts.d.ts +4 -15
  182. package/dist/sandbox/permission-facts.js +7 -29
  183. package/dist/sandbox/permission-instance-writes.d.ts +1 -4
  184. package/dist/sandbox/permission-instance-writes.js +1 -55
  185. package/dist/sandbox/providers.d.ts +1 -6
  186. package/dist/sandbox/providers.js +1 -15
  187. package/dist/sandbox/review/classifier.js +12 -13
  188. package/dist/sandbox/sandbox.module.js +3 -6
  189. package/dist/sandbox/sandbox.service.d.ts +17 -123
  190. package/dist/sandbox/sandbox.service.js +239 -998
  191. package/dist/shares/liveness.d.ts +1 -2
  192. package/dist/shares/liveness.js +1 -2
  193. package/dist/shares/shares.module.d.ts +1 -2
  194. package/dist/shares/shares.module.js +2 -5
  195. package/dist/shares/shares.service.js +1 -2
  196. package/dist/tools/builtins/image/generate.js +7 -15
  197. package/dist/tools/builtins/sandbox/common.d.ts +0 -2
  198. package/dist/tools/builtins/sandbox/common.js +1 -27
  199. package/dist/tools/builtins/sandbox/task-list.js +10 -10
  200. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -10
  201. package/dist/tools/builtins/sandbox/task-output.js +13 -83
  202. package/dist/tools/builtins/sandbox/task-stop.js +18 -22
  203. package/dist/tools/builtins/vision/read-image.js +9 -10
  204. package/dist/tools/builtins/web/extract.js +9 -10
  205. package/package.json +3 -3
  206. package/src/migrations/0206_retire_org_extension_uploads.sql +125 -0
  207. package/src/migrations/0207_confirm_device_instance_destruction.sql +25 -0
  208. package/src/migrations/0208_convert_stored_permission_settings.sql +189 -0
  209. package/dist/background/retire-legacy-tasks.job.d.ts +0 -57
  210. package/dist/background/retire-legacy-tasks.job.js +0 -149
  211. package/dist/catalog/owned-plugin-cleanup.d.ts +0 -47
  212. package/dist/catalog/owned-plugin-cleanup.js +0 -140
  213. package/dist/config/permission-migration.d.ts +0 -34
  214. package/dist/config/permission-migration.js +0 -115
  215. package/dist/devices/legacy-cleanup.job.d.ts +0 -34
  216. package/dist/devices/legacy-cleanup.job.js +0 -147
  217. package/dist/files/library-backfill.d.ts +0 -63
  218. package/dist/files/library-backfill.js +0 -143
  219. package/dist/infra/cli/permission-cutover.d.ts +0 -59
  220. package/dist/infra/cli/permission-cutover.js +0 -107
  221. package/dist/sandbox/cloud-permission-snapshot.d.ts +0 -159
  222. package/dist/sandbox/cloud-permission-snapshot.js +0 -430
  223. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +0 -8
  224. package/dist/sandbox/cloud-permission-snapshot.module.js +0 -34
  225. package/dist/sandbox/legacy-retirement.d.ts +0 -284
  226. package/dist/sandbox/legacy-retirement.js +0 -1165
  227. package/dist/sandbox/legacy-retirement.module.d.ts +0 -8
  228. package/dist/sandbox/legacy-retirement.module.js +0 -25
  229. package/dist/shares/share-objects.d.ts +0 -47
  230. package/dist/shares/share-objects.js +0 -93
@@ -12,12 +12,15 @@ import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperatio
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { STOP_CLAIM_TTL_MS } from "../background/store.js";
15
+ import { EventLog } from "../conversations/event-log.js";
16
+ import { afterCommit } from "../infra/database/after-commit.js";
15
17
  import { KernelDb } from "../infra/database/kernel-db.js";
16
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
17
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
20
  import { OutboxService } from "../infra/outbox/outbox.service.js";
19
21
  import { SandboxOperationAuthority } from "./operation-authority.js";
20
22
  import { describeOperationPayload, OperationPayloads, payloadReference, } from "./operation-payloads.js";
23
+ import { MANAGED_REVOKE_ATTEMPTS, OPERATION_REVOKE, } from "./operation-revoke.js";
21
24
  import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
22
25
  import { PermissionAuthorityLock } from "./permission-authority-lock.js";
23
26
  import { permissionScopeHash } from "./permission-facts.js";
@@ -25,7 +28,7 @@ import { DeviceRequestNotSentError } from "./request-not-sent.js";
25
28
  export class PermissionAdmissionStale extends Error {
26
29
  }
27
30
  export const OPERATION_RECONCILE = "sandbox-operation-reconcile";
28
- export const OPERATION_REVOKE = "sandbox-operation-revoke";
31
+ export { OPERATION_REVOKE } from "./operation-revoke.js";
29
32
  /**
30
33
  * The owed revocation of one crashed holder's intents (`revokeHolders`), written before its holder
31
34
  * record is forgotten, under the job id `sandbox-holder-revoke-<deviceId>-<token>`.
@@ -113,7 +116,8 @@ let SandboxOperationIntents = class SandboxOperationIntents {
113
116
  authority;
114
117
  outbox;
115
118
  payloads;
116
- constructor(db, txHost, locks, epochs, authority, outbox, payloads) {
119
+ events;
120
+ constructor(db, txHost, locks, epochs, authority, outbox, payloads, events) {
117
121
  this.db = db;
118
122
  this.txHost = txHost;
119
123
  this.locks = locks;
@@ -121,6 +125,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
121
125
  this.authority = authority;
122
126
  this.outbox = outbox;
123
127
  this.payloads = payloads;
128
+ this.events = events;
124
129
  }
125
130
  /** Current run claim plus its actual tool_call_started row authorize an internal invocation identity. */
126
131
  async assertClaim(ctx, invocation) {
@@ -713,6 +718,9 @@ let SandboxOperationIntents = class SandboxOperationIntents {
713
718
  throw new SandboxOperationOutcomeUnknownError("The task record diverged from its start");
714
719
  return "acknowledged";
715
720
  }
721
+ // A repeat of the same ref never reopens an already delivered stop.
722
+ if (r.state === "revoked" && r.execution_ref !== null)
723
+ return "cancel-pending";
716
724
  const live = ["dispatching", "started-or-unknown"].includes(r.state) && r.execution_id === executionId;
717
725
  if (!live && r.state !== "revoked")
718
726
  throw new SandboxOperationOutcomeUnknownError("The start is not held by this dispatch; reconcile the same identity");
@@ -772,7 +780,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
772
780
  queue: "cap-kernel-maintenance",
773
781
  name: OPERATION_REVOKE,
774
782
  jobId: `${OPERATION_REVOKE}-${id}-ack`,
775
- data: { operationId: id },
783
+ data: { orgId: r.org_id, operationId: id, attempt: r.revoke_attempt },
776
784
  orgId: r.org_id,
777
785
  });
778
786
  return "cancel-pending";
@@ -1326,6 +1334,39 @@ let SandboxOperationIntents = class SandboxOperationIntents {
1326
1334
  orgId: device.org_id,
1327
1335
  });
1328
1336
  }
1337
+ /** Confirmed destruction wakes exact revokes even after a device deletion stopped their retries. */
1338
+ async recordDestruction(orgId, deviceId, instance) {
1339
+ await this.db
1340
+ .insertInto("device_instance_destructions")
1341
+ .values({
1342
+ device_id: deviceId,
1343
+ provider: instance.provider,
1344
+ instance_generation: instance.generation,
1345
+ confirmed: true,
1346
+ })
1347
+ .onConflict((oc) => oc
1348
+ .columns(["device_id", "provider", "instance_generation"])
1349
+ .doUpdateSet({ confirmed: true }))
1350
+ .execute();
1351
+ const rows = await this.db
1352
+ .selectFrom("sandbox_operation_intents")
1353
+ .select("operation_id")
1354
+ .where("org_id", "=", orgId)
1355
+ .where("device_id", "=", deviceId)
1356
+ .where("provider", "=", instance.provider)
1357
+ .where("instance_generation", "=", instance.generation)
1358
+ .where("state", "=", "revoked")
1359
+ .where("revoke_acknowledged", "=", false)
1360
+ .execute();
1361
+ for (const { operation_id: operationId } of rows)
1362
+ await this.outbox.add({
1363
+ queue: "cap-kernel-maintenance",
1364
+ name: OPERATION_REVOKE,
1365
+ jobId: `${OPERATION_REVOKE}-${operationId}-destroyed`,
1366
+ data: { operationId },
1367
+ orgId,
1368
+ });
1369
+ }
1329
1370
  /**
1330
1371
  * The revoked, unacknowledged operation revokes owed on one instance generation (oldest first,
1331
1372
  * at most `limit`), which a lifecycle holder delivers before anything else runs there. A
@@ -1336,61 +1377,216 @@ let SandboxOperationIntents = class SandboxOperationIntents {
1336
1377
  // lease), not caller input
1337
1378
  const rows = await this.db
1338
1379
  .selectFrom("sandbox_operation_intents")
1339
- .select(["operation_id", "deadline"])
1380
+ .select(["operation_id", "deadline", "method"])
1340
1381
  .where("device_id", "=", deviceId)
1341
1382
  .where("provider", "=", instance.provider)
1342
1383
  .where("instance_generation", "=", instance.generation)
1343
1384
  .where("state", "=", "revoked")
1344
1385
  .where("revoke_acknowledged", "=", false)
1345
- .where((eb) => eb.or([eb("method", "!=", "backgroundStart"), eb("execution_ref", "is", null)]))
1386
+ .where((eb) => eb.or([
1387
+ eb("method", "!=", "backgroundStart"),
1388
+ eb.and([
1389
+ eb("execution_ref", "is", null),
1390
+ eb("revoke_attempt", "<", MANAGED_REVOKE_ATTEMPTS),
1391
+ ]),
1392
+ ]))
1346
1393
  .orderBy("created_at")
1347
1394
  .limit(limit)
1348
1395
  .execute();
1349
- return rows.map((r) => ({ operationId: r.operation_id, deadline: r.deadline }));
1396
+ return rows.map((r) => ({
1397
+ operationId: r.operation_id,
1398
+ deadline: r.deadline,
1399
+ method: r.method,
1400
+ }));
1401
+ }
1402
+ /** A person's or tool's stop can outlive the replica which first tried it. */
1403
+ async adoptOwedStop(row) {
1404
+ const updated = await this.db
1405
+ .updateTable("sandbox_operation_intents")
1406
+ .set({ state: "revoked", outcome_unknown: true, updated_at: new Date() })
1407
+ .where("org_id", "=", row.org_id)
1408
+ .where("operation_id", "=", row.operation_id)
1409
+ .where("state", "=", "background-running")
1410
+ .where(({ exists, selectFrom }) => exists(selectFrom("background_tasks as t")
1411
+ .select("t.id")
1412
+ .where("t.org_id", "=", row.org_id)
1413
+ .where("t.operation_id", "=", row.operation_id)
1414
+ .where("t.launch_state", "=", "cancel-pending")))
1415
+ .executeTakeFirst();
1416
+ return updated.numUpdatedRows > 0n;
1417
+ }
1418
+ /** Hand authoritative pre-resume evidence to the worker before admitting new work. */
1419
+ async recordResumeProof(orgId, operationId, proof, repair = 0) {
1420
+ await this.outbox.add({
1421
+ queue: "cap-kernel-maintenance",
1422
+ name: OPERATION_REVOKE,
1423
+ jobId: `${OPERATION_REVOKE}-${operationId}-proof-${permissionScopeHash(proof)}-${repair}`,
1424
+ data: { orgId, operationId, proof, ...(repair > 0 && { repair }) },
1425
+ orgId,
1426
+ ...(repair > 0 && {
1427
+ runAt: new Date(Date.now() + Math.min(30_000 * 2 ** Math.min(repair - 1, 20), 3_600_000)),
1428
+ }),
1429
+ });
1430
+ }
1431
+ /** The intent lock orders proof settlement with exhaustion, late ref attachment, and stops. */
1432
+ async applyResumeProof(orgId, operationId, proof, settle) {
1433
+ const row = await this.db
1434
+ .selectFrom("sandbox_operation_intents")
1435
+ .selectAll()
1436
+ .where("org_id", "=", orgId)
1437
+ .where("operation_id", "=", operationId)
1438
+ .where("device_id", "=", proof.deviceId)
1439
+ .where("provider", "=", proof.provider)
1440
+ .where("instance_generation", "=", proof.instanceGeneration)
1441
+ .where("method", "=", "backgroundStart")
1442
+ .where("state", "in", ["revoked", "background-running"])
1443
+ .where("revoke_acknowledged", "=", false)
1444
+ .forUpdate()
1445
+ .executeTakeFirst();
1446
+ if (!row || permissionScopeHash(row.execution_ref) !== permissionScopeHash(proof.ref))
1447
+ return;
1448
+ if (row.state === "background-running" && !(await this.adoptOwedStop(row)))
1449
+ return;
1450
+ await settle();
1451
+ await this.acknowledgeRevocationIn(operationId);
1350
1452
  }
1351
1453
  /**
1352
1454
  * A disconnected or still-pending revoke remains owed; every retry is a new deterministic
1353
- * persisted attempt, backing off (30 s doubling, at most an hour) so an obligation that only
1354
- * retirement can resolve (a lost or replaced instance) never spins. Retries stop once the
1355
- * device or its org is deleted: nothing can reach its instance any more, the revoke stays
1356
- * unacknowledged (no cleanup is claimed) and the retirement settles it from the device's
1357
- * recorded destruction, if any.
1455
+ * persisted attempt, backing off from 30 seconds to one hour. After device or org deletion,
1456
+ * only recorded destruction can settle the operation. Recording it wakes a suppressed retry.
1457
+ * If settlement itself fails, the proof keeps its retry owed even after deletion.
1358
1458
  */
1359
- async deferRevocation(id) {
1360
- const row = await this.db
1459
+ async deferRevocation(id, delivery) {
1460
+ const managed = delivery && "row" in delivery ? delivery : undefined;
1461
+ const retry = delivery && "retry" in delivery ? delivery.retry : undefined;
1462
+ let update = this.db
1361
1463
  .updateTable("sandbox_operation_intents")
1362
- .set((eb) => ({ reconcile_attempt: eb("reconcile_attempt", "+", 1), updated_at: new Date() }))
1464
+ .set((eb) => ({
1465
+ reconcile_attempt: eb("reconcile_attempt", "+", 1),
1466
+ ...(managed && { revoke_attempt: eb("revoke_attempt", "+", 1) }),
1467
+ updated_at: new Date(),
1468
+ }))
1363
1469
  .where("operation_id", "=", id)
1364
1470
  .where("state", "=", "revoked")
1365
1471
  .where("revoke_acknowledged", "=", false)
1366
- .where(({ exists, selectFrom }) => exists(selectFrom("devices as d")
1367
- .innerJoin("orgs as o", "o.id", "d.org_id")
1368
- .select("d.id")
1369
- .whereRef("d.id", "=", "sandbox_operation_intents.device_id")
1370
- .where("d.deleted_at", "is", null)
1371
- .where("o.deleted_at", "is", null)))
1372
- .returning(["org_id", "reconcile_attempt"])
1472
+ .where((eb) => eb.or([
1473
+ // A released dead letter must be parked again even after the subject was deleted.
1474
+ eb.val((managed?.row.revoke_attempt ?? retry ?? 0) >= MANAGED_REVOKE_ATTEMPTS),
1475
+ eb.and([
1476
+ retry === undefined
1477
+ ? eb.val(true)
1478
+ : eb.or([eb("method", "!=", "backgroundStart"), eb("revoke_attempt", "=", retry)]),
1479
+ eb.exists(eb
1480
+ .selectFrom("devices as d")
1481
+ .innerJoin("orgs as o", "o.id", "d.org_id")
1482
+ .select("d.id")
1483
+ .whereRef("d.id", "=", "sandbox_operation_intents.device_id")
1484
+ .where("d.deleted_at", "is", null)
1485
+ .where("o.deleted_at", "is", null)),
1486
+ ]),
1487
+ eb.exists(eb
1488
+ .selectFrom("device_instance_destructions as d")
1489
+ .select("d.device_id")
1490
+ .where("d.confirmed", "=", true)
1491
+ .whereRef("d.device_id", "=", "sandbox_operation_intents.device_id")
1492
+ .whereRef("d.provider", "=", "sandbox_operation_intents.provider")
1493
+ .whereRef("d.instance_generation", "=", "sandbox_operation_intents.instance_generation")),
1494
+ ]));
1495
+ if (managed)
1496
+ update = update
1497
+ .where("org_id", "=", managed.row.org_id)
1498
+ .where("revoke_attempt", "=", managed.row.revoke_attempt);
1499
+ const row = await update
1500
+ .returning(["org_id", "reconcile_attempt", "revoke_attempt"])
1373
1501
  .executeTakeFirst();
1374
- if (row)
1375
- await this.outbox.add({
1376
- queue: "cap-kernel-maintenance",
1377
- name: OPERATION_REVOKE,
1378
- jobId: `${OPERATION_REVOKE}-${id}-${row.reconcile_attempt}`,
1379
- data: { operationId: id },
1502
+ if (!row)
1503
+ return;
1504
+ const attempt = managed ? row.revoke_attempt : row.reconcile_attempt;
1505
+ const job = {
1506
+ queue: "cap-kernel-maintenance",
1507
+ name: OPERATION_REVOKE,
1508
+ jobId: retry !== undefined
1509
+ ? `${OPERATION_REVOKE}-${id}-check-${row.reconcile_attempt}`
1510
+ : managed
1511
+ ? `${OPERATION_REVOKE}-${id}-attempt-${attempt}`
1512
+ : `${OPERATION_REVOKE}-${id}-${attempt}`,
1513
+ orgId: row.org_id,
1514
+ data: {
1515
+ operationId: id,
1380
1516
  orgId: row.org_id,
1381
- runAt: new Date(Date.now() + Math.min(30_000 * 2 ** Math.min(row.reconcile_attempt - 1, 20), 3_600_000)),
1382
- });
1517
+ ...(managed && { attempt }),
1518
+ ...(retry !== undefined && { attempt: retry }),
1519
+ },
1520
+ };
1521
+ if (managed && attempt >= MANAGED_REVOKE_ATTEMPTS) {
1522
+ if (managed.row.revoke_attempt >= MANAGED_REVOKE_ATTEMPTS)
1523
+ await this.removeDeadRevocation(id, row.org_id, managed.row.revoke_attempt);
1524
+ await managed.exhausted();
1525
+ await this.updateStopReason(id, row.org_id, "stop_unconfirmed");
1526
+ await this.outbox.addDead(job, attempt, "The device did not confirm the exact background stop. Check the command on the device.");
1527
+ return;
1528
+ }
1529
+ await this.outbox.add({
1530
+ ...job,
1531
+ runAt: new Date(Date.now() + Math.min(30_000 * 2 ** Math.min(attempt - 1, 20), 3_600_000)),
1532
+ });
1533
+ }
1534
+ async acknowledgeRevocation(id, opts) {
1535
+ await this.acknowledgeRevocationIn(id, opts);
1383
1536
  }
1384
- async acknowledgeRevocation(id) {
1537
+ async acknowledgeRevocationIn(id, opts) {
1385
1538
  // org-filter: by the kernel-minted operation id of the revoke job's payload (written by this
1386
1539
  // service), not caller input
1387
- await this.db
1540
+ const settled = await this.db
1388
1541
  .updateTable("sandbox_operation_intents")
1389
1542
  .set({ revoke_acknowledged: true, updated_at: new Date() })
1390
1543
  .where("operation_id", "=", id)
1391
1544
  .where("state", "=", "revoked")
1545
+ .$if(opts?.withoutRef === true, (q) => q.where("execution_ref", "is", null))
1546
+ .returning(["org_id", "method", "revoke_attempt"])
1547
+ .executeTakeFirst();
1548
+ if (settled?.method === "backgroundStart" &&
1549
+ settled.revoke_attempt >= MANAGED_REVOKE_ATTEMPTS) {
1550
+ await this.updateStopReason(id, settled.org_id, opts?.destroyed ? "sandbox_gone" : "stop_confirmed");
1551
+ await this.removeDeadRevocation(id, settled.org_id, settled.revoke_attempt);
1552
+ }
1553
+ }
1554
+ async removeDeadRevocation(id, orgId, attempt) {
1555
+ await this.db
1556
+ .deleteFrom("outbox")
1557
+ .where("org_id", "=", orgId)
1558
+ .where("queue", "=", "cap-kernel-maintenance")
1559
+ .where("job_name", "=", OPERATION_REVOKE)
1560
+ .where("job_id", "=", `${OPERATION_REVOKE}-${id}-attempt-${attempt}`)
1561
+ .where("dead_at", "is not", null)
1392
1562
  .execute();
1393
1563
  }
1564
+ /** Reclassify a lost task without appending a second finish or waking its conversation. */
1565
+ async updateStopReason(id, orgId, reason) {
1566
+ const updated = await this.db
1567
+ .updateTable("background_tasks")
1568
+ .set({
1569
+ lost_reason: reason,
1570
+ ...(reason === "sandbox_gone" && { launch_state: "terminal" }),
1571
+ ...(reason === "stop_confirmed" && {
1572
+ launch_state: sql `CASE WHEN execution_ref IS NOT NULL THEN 'terminal' ELSE launch_state END`,
1573
+ }),
1574
+ })
1575
+ .where("operation_id", "=", id)
1576
+ .where("org_id", "=", orgId)
1577
+ .where("status", "=", "lost")
1578
+ .where("lost_reason", reason === "stop_unconfirmed" ? "is distinct from" : "=", "stop_unconfirmed")
1579
+ .returning(["conversation_id", "sandbox_conversation_id"])
1580
+ .executeTakeFirst();
1581
+ if (updated)
1582
+ afterCommit(async () => {
1583
+ for (const conversation of new Set([
1584
+ updated.conversation_id,
1585
+ updated.sandbox_conversation_id,
1586
+ ]))
1587
+ await this.events.publishChanged(conversation, "background");
1588
+ });
1589
+ }
1394
1590
  };
1395
1591
  __decorate([
1396
1592
  Transactional({ propagation: "requires_new" })
@@ -1452,6 +1648,18 @@ __decorate([
1452
1648
  __decorate([
1453
1649
  Transactional({ propagation: "requires_new" })
1454
1650
  ], SandboxOperationIntents.prototype, "revokeIncarnation", null);
1651
+ __decorate([
1652
+ Transactional({ propagation: "requires_new" })
1653
+ ], SandboxOperationIntents.prototype, "recordDestruction", null);
1654
+ __decorate([
1655
+ Transactional()
1656
+ ], SandboxOperationIntents.prototype, "adoptOwedStop", null);
1657
+ __decorate([
1658
+ Transactional({ propagation: "requires_new" })
1659
+ ], SandboxOperationIntents.prototype, "recordResumeProof", null);
1660
+ __decorate([
1661
+ Transactional({ propagation: "requires_new" })
1662
+ ], SandboxOperationIntents.prototype, "applyResumeProof", null);
1455
1663
  __decorate([
1456
1664
  Transactional({ propagation: "requires_new" })
1457
1665
  ], SandboxOperationIntents.prototype, "deferRevocation", null);
@@ -1466,6 +1674,7 @@ SandboxOperationIntents = __decorate([
1466
1674
  __param(3, Inject(PermissionAuthorityEpochStore)),
1467
1675
  __param(4, Inject(SandboxOperationAuthority)),
1468
1676
  __param(5, Inject(OutboxService)),
1469
- __param(6, Inject(OperationPayloads))
1677
+ __param(6, Inject(OperationPayloads)),
1678
+ __param(7, Inject(EventLog))
1470
1679
  ], SandboxOperationIntents);
1471
1680
  export { SandboxOperationIntents };
@@ -5,6 +5,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
7
  import { Module } from "@nestjs/common";
8
+ import { EventLogModule } from "../conversations/event-log.js";
8
9
  import { OperationAuthorityModule } from "./operation-authority.module.js";
9
10
  import { SandboxOperationIntents } from "./operation-intents.js";
10
11
  import { OperationPayloads } from "./operation-payloads.js";
@@ -13,7 +14,7 @@ let OperationIntentsModule = class OperationIntentsModule {
13
14
  };
14
15
  OperationIntentsModule = __decorate([
15
16
  Module({
16
- imports: [OperationAuthorityModule, PermissionAuthorityModule],
17
+ imports: [OperationAuthorityModule, PermissionAuthorityModule, EventLogModule],
17
18
  providers: [OperationPayloads, SandboxOperationIntents],
18
19
  exports: [SandboxOperationIntents],
19
20
  })
@@ -5,6 +5,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import type { KernelLogger } from "../log.js";
7
7
  import { SandboxOperationIntents } from "./operation-intents.js";
8
+ import { type ResumeStopProof } from "./operation-revoke.js";
8
9
  import { DeviceProviders } from "./providers.js";
9
10
  import { SandboxService } from "./sandbox.service.js";
10
11
  /** Called only by the maintenance consumer. It has no native dispatch or lease token API. */
@@ -20,7 +21,7 @@ export declare class SandboxOperationReconcileJob {
20
21
  private readonly log?;
21
22
  /** Tells a page listing the task that reconciliation moved it (a hint, its loss harmless). */
22
23
  private readonly eventLog?;
23
- constructor(intents: SandboxOperationIntents, db: KernelDb, providers: Pick<DeviceProviders, "forDevice">, sandbox: Pick<SandboxService, "ifRunning">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel">, stopper: Pick<BackgroundTaskStopper, "stop" | "settleRevokedUnconfirmed">, config: Pick<KernelConfigService, "get">,
24
+ constructor(intents: SandboxOperationIntents, db: KernelDb, providers: Pick<DeviceProviders, "forDevice">, sandbox: Pick<SandboxService, "ifRunning">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel">, stopper: Pick<BackgroundTaskStopper, "stop" | "settleRevokedUnconfirmed" | "settleDestroyed" | "settleStopUnconfirmed" | "settleResumeExit">, config: Pick<KernelConfigService, "get">,
24
25
  /** Where a recovered start's refusal keeps the provider's own message (never the task's). */
25
26
  log?: Pick<KernelLogger, "warn"> | undefined,
26
27
  /** Tells a page listing the task that reconciliation moved it (a hint, its loss harmless). */
@@ -49,17 +50,14 @@ export declare class SandboxOperationReconcileJob {
49
50
  * ref; one that did not happens once. Never a new operation ID, never refreshed authority.
50
51
  */
51
52
  recoverBackground(operationId: string): Promise<void>;
52
- revoke(operationId: string): Promise<void>;
53
+ revoke(operationId: string, attempt?: number, orgId?: string): Promise<void>;
54
+ /** A failed bookkeeping transaction retries the proof itself, without calling the device again. */
55
+ settleResumeProof(orgId: string, operationId: string, proof: ResumeStopProof, repair?: number): Promise<void>;
53
56
  private revokeOnce;
54
- /**
55
- * Whether a foreground operation (exec, read, write) of an incarnation that no longer runs has
56
- * provably ended, so its owed revoke has nothing left to reach: the provider confirmed that
57
- * incarnation's destruction (recorded in `device_instance_destructions`), or the operation is
58
- * past its device-enforced bound (admitted before its deadline, then cut by the in-sandbox time
59
- * limit of `maxCommandSeconds`). Both read only PostgreSQL and the clock, so every replica
60
- * decides alike; without either the revoke stays owed.
61
- */
62
- private incarnationEnded;
57
+ /** Provider evidence is keyed by the scoped intent's globally unique device and incarnation. */
58
+ private destructionRecorded;
59
+ /** A foreground command is bounded even after its instance stops serving requests. */
60
+ private foregroundTimeLimitPassed;
63
61
  /**
64
62
  * The exact cancellation a revoked background start owes (design B3): the task's own stop by its
65
63
  * exact ref with the five-second grace, which settles and reports the task; the revocation is