@capybara-hq/kernel 0.1.0-rc.49 → 0.1.0-rc.50

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 (128) hide show
  1. package/dist/admin/admin.schemas.d.ts +0 -6
  2. package/dist/background/launch.d.ts +7 -61
  3. package/dist/background/launch.js +8 -133
  4. package/dist/background/poll.job.d.ts +19 -23
  5. package/dist/background/poll.job.js +30 -66
  6. package/dist/background/render.d.ts +9 -0
  7. package/dist/background/render.js +19 -0
  8. package/dist/background/session.d.ts +3 -66
  9. package/dist/background/session.js +3 -114
  10. package/dist/background/stop.d.ts +26 -33
  11. package/dist/background/stop.js +59 -90
  12. package/dist/background/store.d.ts +26 -60
  13. package/dist/background/store.js +23 -108
  14. package/dist/background/tasks.service.d.ts +9 -29
  15. package/dist/background/tasks.service.js +18 -115
  16. package/dist/catalog/marketplaces.service.d.ts +1 -1
  17. package/dist/channels/cards.d.ts +3 -0
  18. package/dist/channels/cards.js +29 -2
  19. package/dist/channels/phrases.d.ts +35 -0
  20. package/dist/channels/phrases.js +32 -0
  21. package/dist/config/load.d.ts +3 -10
  22. package/dist/config/load.js +26 -21
  23. package/dist/config/schema.js +3 -3
  24. package/dist/conversations/events.d.ts +45 -2
  25. package/dist/conversations/events.js +44 -4
  26. package/dist/db/kernel-schema.d.ts +9 -4
  27. package/dist/devices/devices.service.js +1 -1
  28. package/dist/devices/errors.d.ts +5 -0
  29. package/dist/devices/errors.js +5 -0
  30. package/dist/devices/project-rules.d.ts +2 -2
  31. package/dist/errors.d.ts +9 -11
  32. package/dist/errors.js +9 -11
  33. package/dist/identity/settings.d.ts +4 -17
  34. package/dist/identity/settings.js +9 -32
  35. package/dist/infra/config/kernel-config.service.js +2 -9
  36. package/dist/infra/outbox/registry.d.ts +13 -0
  37. package/dist/infra/outbox/registry.js +8 -0
  38. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  39. package/dist/local-devices/device-auth.controller.js +1 -1
  40. package/dist/local-devices/device-auth.d.ts +4 -3
  41. package/dist/local-devices/device-auth.js +1 -1
  42. package/dist/local-devices/device-policy.service.d.ts +6 -6
  43. package/dist/local-devices/device-routes.d.ts +4 -2
  44. package/dist/local-devices/device-routes.js +7 -6
  45. package/dist/local-devices/instance-bindings.d.ts +4 -4
  46. package/dist/local-devices/instance-bindings.js +2 -2
  47. package/dist/local-devices/local-device-gateway.d.ts +12 -12
  48. package/dist/local-devices/local-device-gateway.js +94 -129
  49. package/dist/local-devices/local-device-provider.d.ts +19 -87
  50. package/dist/local-devices/local-device-provider.js +43 -158
  51. package/dist/local-devices/local-devices.module.d.ts +4 -5
  52. package/dist/local-devices/local-devices.module.js +6 -9
  53. package/dist/local-devices/machines.d.ts +6 -6
  54. package/dist/local-devices/machines.js +4 -4
  55. package/dist/local-devices/owner-report.d.ts +3 -3
  56. package/dist/local-devices/owner-report.js +4 -4
  57. package/dist/local-devices/owner-reports.js +2 -2
  58. package/dist/local-devices/policy-summary.js +2 -2
  59. package/dist/local-devices/relay.d.ts +12 -25
  60. package/dist/local-devices/relay.js +17 -31
  61. package/dist/orgs/settings.controller.d.ts +1 -4
  62. package/dist/orgs/settings.controller.js +3 -3
  63. package/dist/orgs/settings.service.d.ts +7 -21
  64. package/dist/orgs/settings.service.js +16 -40
  65. package/dist/overrides.d.ts +3 -3
  66. package/dist/platform/ops/admin.ops.js +6 -8
  67. package/dist/platform/ops/org-settings.ops.js +4 -4
  68. package/dist/platform/ops/orgs.ops.js +0 -1
  69. package/dist/runtime/maintenance.d.ts +1 -1
  70. package/dist/runtime/maintenance.js +7 -1
  71. package/dist/runtime/run-steps.js +2 -2
  72. package/dist/sandbox/held-operations.d.ts +7 -0
  73. package/dist/sandbox/held-operations.js +25 -1
  74. package/dist/sandbox/leases.d.ts +6 -3
  75. package/dist/sandbox/leases.js +16 -10
  76. package/dist/sandbox/legacy-retirement.d.ts +0 -19
  77. package/dist/sandbox/legacy-retirement.js +6 -37
  78. package/dist/sandbox/managed-device-context.d.ts +12 -0
  79. package/dist/sandbox/managed-device-context.js +49 -1
  80. package/dist/sandbox/modes.d.ts +9 -8
  81. package/dist/sandbox/modes.js +4 -15
  82. package/dist/sandbox/operation-authority-types.d.ts +18 -1
  83. package/dist/sandbox/operation-authority-types.js +20 -1
  84. package/dist/sandbox/operation-authority.d.ts +14 -0
  85. package/dist/sandbox/operation-authority.js +120 -18
  86. package/dist/sandbox/operation-intents.d.ts +43 -0
  87. package/dist/sandbox/operation-intents.js +107 -4
  88. package/dist/sandbox/operation-reconcile.job.d.ts +12 -1
  89. package/dist/sandbox/operation-reconcile.job.js +53 -6
  90. package/dist/sandbox/permission-call-grants.d.ts +4 -0
  91. package/dist/sandbox/permission-call-grants.js +32 -3
  92. package/dist/sandbox/permission-call-types.d.ts +27 -2
  93. package/dist/sandbox/permission-ceiling-writes.js +2 -1
  94. package/dist/sandbox/permission-context-types.d.ts +2 -2
  95. package/dist/sandbox/permission-context-types.js +2 -2
  96. package/dist/sandbox/permission-facts.js +10 -2
  97. package/dist/sandbox/platform-full-access.d.ts +8 -26
  98. package/dist/sandbox/platform-full-access.js +8 -20
  99. package/dist/sandbox/review/classifier.d.ts +2 -2
  100. package/dist/sandbox/review/classifier.js +18 -5
  101. package/dist/sandbox/review/permission-candidate.d.ts +59 -3
  102. package/dist/sandbox/review/permission-candidate.js +192 -25
  103. package/dist/sandbox/review/review.service.d.ts +18 -0
  104. package/dist/sandbox/review/review.service.js +158 -12
  105. package/dist/sandbox/sandbox.service.d.ts +71 -47
  106. package/dist/sandbox/sandbox.service.js +234 -133
  107. package/dist/tools/approvals.service.d.ts +6 -1
  108. package/dist/tools/approvals.service.js +10 -0
  109. package/dist/tools/builtins/builtin-tools.d.ts +1 -4
  110. package/dist/tools/builtins/builtin-tools.js +13 -18
  111. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  112. package/dist/tools/builtins/sandbox/bash.js +92 -270
  113. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  114. package/dist/tools/builtins/sandbox/common.js +55 -19
  115. package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
  116. package/dist/tools/builtins/sandbox/device-owner.js +14 -0
  117. package/dist/tools/builtins/sandbox/task-list.js +2 -2
  118. package/dist/tools/builtins/sandbox/task-output.d.ts +14 -57
  119. package/dist/tools/builtins/sandbox/task-output.js +88 -210
  120. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
  121. package/dist/tools/builtins/sandbox/task-stop.js +15 -26
  122. package/dist/tools/pipeline.d.ts +31 -2
  123. package/dist/tools/pipeline.js +273 -43
  124. package/dist/tools/registry.d.ts +7 -0
  125. package/package.json +4 -4
  126. package/src/migrations/0162_permission_call_escalation.sql +9 -0
  127. package/dist/background/status.d.ts +0 -35
  128. package/dist/background/status.js +0 -57
@@ -10,7 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { posix } from "node:path";
11
11
  import { DEFAULT_SANDBOX_ROOTS, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
12
12
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
13
- import { createHeldOperations, createLegacyHeldProvider, } from "./held-operations.js";
13
+ import { createHeldOperations, createLegacyHeldProvider, withKernelGeneration, } from "./held-operations.js";
14
14
  import { SandboxOperationAuthority } from "./operation-authority.js";
15
15
  import { PermissionAdmissionStale, SandboxOperationIntents, } from "./operation-intents.js";
16
16
  import { PermissionInstanceWrites } from "./permission-instance-writes.js";
@@ -33,12 +33,10 @@ const backgroundBinding = (args, instanceId) => ({
33
33
  instanceId,
34
34
  });
35
35
  import { randomUUID } from "node:crypto";
36
- import { isFileSystemGoneError, isSandboxGoneError, rootsOf, } from "@capybara-hq/plugin-sdk";
36
+ import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, rootsOf, } from "@capybara-hq/plugin-sdk";
37
37
  import { Inject, Injectable } from "@nestjs/common";
38
38
  import { sql, } from "kysely";
39
- import { SESSION_MODE_SCRIPT } from "../background/launch.js";
40
39
  import { MANAGED_STOP_GRACE_MS } from "../background/managed.js";
41
- import { BackgroundTaskStore } from "../background/store.js";
42
40
  import { deviceNotFound } from "../devices/errors.js";
43
41
  import { ApiError } from "../errors.js";
44
42
  import { readSandboxLimitOverride } from "../identity/settings.js";
@@ -82,10 +80,10 @@ const SWEEP_BATCH = 200;
82
80
  const SWEEP_CONCURRENCY = 4;
83
81
  /** How long `destroyDevice` / `resetFileSystem` wait for the exclusive lease (running commands). */
84
82
  const EXCLUSIVE_WAIT_MS = 10 * 60_000;
85
- /** The time limit of the exec that kills lost background tasks after a resume (ms). */
86
- const PENDING_KILL_TIMEOUT_MS = 30_000;
87
- /** A background task's session id as `echo $!` printed it; anything else is never put in a command. */
88
- const SID_RE = /^[1-9][0-9]{0,9}$/;
83
+ /** The time limit of one best-effort maintenance call and of one inline exact revoke (ms). */
84
+ const MAINTENANCE_CALL_TIMEOUT_MS = 30_000;
85
+ /** How many owed operation revokes a lifecycle holder delivers inline (the revoke jobs do the rest). */
86
+ const INLINE_REVOKE_LIMIT = 100;
89
87
  const noticeKey = (deviceId, holder) => `capk:sandbox-notice:${deviceId}:${holder}`;
90
88
  /** A stored {@link DeferredNotice}, or null (none, or not one). */
91
89
  function parseDeferred(raw) {
@@ -304,7 +302,6 @@ let SandboxService = class SandboxService {
304
302
  providers;
305
303
  config;
306
304
  log;
307
- background;
308
305
  facts;
309
306
  operationIntents;
310
307
  authority;
@@ -315,9 +312,7 @@ let SandboxService = class SandboxService {
315
312
  /** The record of the instance each holder last used (`capk:sandbox-seen:…`). */
316
313
  redis, leases,
317
314
  /** The providers (read at every call: providers are ready after the extension load). */
318
- providers, config, log,
319
- /** Background tasks lost while their process may live on (killed after a resume). */
320
- background, facts, operationIntents, authority, instanceWrites,
315
+ providers, config, log, facts, operationIntents, authority, instanceWrites,
321
316
  /** The retirement obligations every lifecycle acquisition is gated on (8.5). */
322
317
  retirement,
323
318
  /** The cloud snapshot writer's reconcile, for the lifecycle reconcile of marked devices (B-12). */
@@ -328,7 +323,6 @@ let SandboxService = class SandboxService {
328
323
  this.providers = providers;
329
324
  this.config = config;
330
325
  this.log = log;
331
- this.background = background;
332
326
  this.facts = facts;
333
327
  this.operationIntents = operationIntents;
334
328
  this.authority = authority;
@@ -555,8 +549,8 @@ let SandboxService = class SandboxService {
555
549
  * creates, resumes or rebuilds one: an instance that is missing, suspended, being created or
556
550
  * destroyed (or recorded with another provider) is `not_running`, one that records another
557
551
  * instance is `other_instance`. Otherwise `fn` runs under a shared lease, as a `withSandbox`
558
- * holder does (its tag on every exec, crashed holders' commands killed), and `last_used_at`
559
- * moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
552
+ * holder does (its tag on every exec, crashed holders' operations revoked exactly), and
553
+ * `last_used_at` moves forward when it ends. Waits for the lease up to `sandbox.lockWaitSeconds`
560
554
  * (`sandbox.busy`); `signal` (optional) ends the wait with its abort reason. The signal passed
561
555
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
562
556
  * too) are thrown as they are.
@@ -758,6 +752,23 @@ let SandboxService = class SandboxService {
758
752
  const e = await this.enter(use, p, signal, null, () => this.wantedLimits(use, p));
759
753
  await this.leave(ctx.deviceId, e);
760
754
  }
755
+ /**
756
+ * Makes the device's instance run for a managed call before its permission review reads the
757
+ * device's facts: the lifecycle `enter` the call's own use takes (the exclusive lease creates
758
+ * or resumes the instance through the retirement gate, the binding, the limits and fencing, and
759
+ * records a cloud instance's permission evidence), then the lease is left at once. Nothing runs
760
+ * in it; what the start caused is kept for the holder's next use to tell (as a silent use).
761
+ */
762
+ async ensureRunning(use, signal) {
763
+ const p = await this.require(use.deviceId, use.orgId);
764
+ const e = await this.enter(use, p, signal, null, () => this.wantedLimits(use, p));
765
+ try {
766
+ await this.deferNotice(use.deviceId, use.holderConversationId, e);
767
+ }
768
+ finally {
769
+ await this.leave(use.deviceId, e);
770
+ }
771
+ }
761
772
  /**
762
773
  * A run start's kernel read of the bound project (permission activation L2, Hook 1): the use
763
774
  * a tool call's would be (the instance made or resumed, the read silent for the holder), whose
@@ -792,6 +803,7 @@ let SandboxService = class SandboxService {
792
803
  const want = () => this.wantedLimits(ctx, p);
793
804
  const seen = (x) => ctx.silent ? this.deferNotice(env, holder, x) : this.seenBy(env, holder, x);
794
805
  let e = await seen(await this.enter(ctx, p, signal, null, want));
806
+ let left = false;
795
807
  try {
796
808
  try {
797
809
  return await this.runAs(e, ctx, p, fn, signal, invocation, trusted, kernelRead);
@@ -799,6 +811,30 @@ let SandboxService = class SandboxService {
799
811
  catch (err) {
800
812
  if (isFileSystemGoneError(err))
801
813
  throw await this.filesGone(env, p, e);
814
+ if (isSandboxOperationOutcomeUnknownError(err) &&
815
+ isSandboxGoneError(err.cause)) {
816
+ // gone after a durable dispatch: the outcome stays unknown and the call is never retried
817
+ // under a new identity, but the gone instance is rebuilt on the kept files now, so the
818
+ // holder's next call runs on it and is told of the restart (its seen record still names
819
+ // the gone instance)
820
+ this.log.info("sandbox instance is gone after a dispatched operation; recreating", {
821
+ deviceId: env,
822
+ });
823
+ const gone = { handle: e.handle, createdAt: e.createdAt };
824
+ await this.leave(env, e);
825
+ left = true;
826
+ try {
827
+ const rebuilt = await this.enter(ctx, p, signal, gone, want);
828
+ await this.leave(env, rebuilt);
829
+ }
830
+ catch (rebuildErr) {
831
+ this.log.warn("cannot recreate the gone sandbox instance; the next use will", {
832
+ deviceId: env,
833
+ err: rebuildErr,
834
+ });
835
+ }
836
+ throw err;
837
+ }
802
838
  if (!isSandboxGoneError(err))
803
839
  throw err;
804
840
  this.log.info("sandbox instance is gone during use; recreating", { deviceId: env });
@@ -821,7 +857,8 @@ let SandboxService = class SandboxService {
821
857
  }
822
858
  }
823
859
  finally {
824
- await this.leave(env, e);
860
+ if (!left)
861
+ await this.leave(env, e);
825
862
  }
826
863
  }
827
864
  /**
@@ -956,8 +993,10 @@ let SandboxService = class SandboxService {
956
993
  if (kernelRead)
957
994
  return fn(e.handle, this.kernelReadProvider(e, ctx, p, kernelRead, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
958
995
  let ordinal = 0;
996
+ // a cloud provider's background starts are told the held instance's kernel generation
997
+ const held = p.binder ? p.impl : withKernelGeneration(p.impl, String(e.createdAt));
959
998
  const impl = invocation
960
- ? createHeldOperations(p.impl, e.handle, sig, async (method, input, invoke, preflight) => {
999
+ ? createHeldOperations(held, e.handle, sig, async (method, input, invoke, preflight) => {
961
1000
  const identity = { ...invocation, ordinal: ordinal++ };
962
1001
  sig.throwIfAborted();
963
1002
  await this.register(env, e.lease.token);
@@ -1036,6 +1075,10 @@ let SandboxService = class SandboxService {
1036
1075
  throw error;
1037
1076
  }
1038
1077
  await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1078
+ // The machine's files are gone (R24): the operation stays unknown, and the caller still
1079
+ // records the files lost so later calls fail without reaching the machine.
1080
+ if (isFileSystemGoneError(error))
1081
+ throw error;
1039
1082
  // A transport/gone error after durable dispatch cannot justify a new identity retry.
1040
1083
  throw new SandboxOperationOutcomeUnknownError("The operation outcome must be reconciled with its recorded identity", { cause: error });
1041
1084
  }
@@ -1385,17 +1428,17 @@ let SandboxService = class SandboxService {
1385
1428
  }
1386
1429
  /**
1387
1430
  * Under a just-taken shared lease: confirms the row is still `accept`ed (else releases and
1388
- * returns null), records the holder and kills crashed holders' commands.
1431
+ * returns null), records the holder and revokes crashed holders' operations exactly.
1389
1432
  */
1390
1433
  async asShared(ctx, p, lease, accept, signal,
1391
1434
  /**
1392
1435
  * Refused (null) while the device has an unresolved retirement obligation, checked under the
1393
- * lease and before anything is killed or bumped; false only for exact-ref managed drains.
1436
+ * lease and before anything is revoked or bumped; false only for exact-ref managed drains.
1394
1437
  */
1395
1438
  gated,
1396
1439
  /**
1397
1440
  * Checked under the lease (which the B1 snapshot writer's exclusive lease excludes) before
1398
- * anything is killed or bumped: `reconciled` and `use` refuse a device carrying the
1441
+ * anything is revoked or bumped: `reconciled` and `use` refuse a device carrying the
1399
1442
  * reconcile marker (B-11); `use` (entering a holder) also returns null on the staged path
1400
1443
  * while the instance's binding is not installed, so the caller binds it exclusively (B-8).
1401
1444
  * `none` for background polls, stops and drains.
@@ -1423,9 +1466,9 @@ let SandboxService = class SandboxService {
1423
1466
  .where("device_id", "=", env)
1424
1467
  .execute();
1425
1468
  await this.register(env, lease.token);
1426
- // other holders (any conversation of the device) may be running: only the dead
1427
- // holders' own commands are killed
1428
- await this.killTagged(env, row.handle, p, await this.claim(env), signal, lease);
1469
+ // other holders (any conversation of the device) may be running: only the dead holders'
1470
+ // own operations are revoked, exactly
1471
+ await this.takeOver(env, this.incarnationOf(row), row.handle, p, signal, lease);
1429
1472
  return {
1430
1473
  lease,
1431
1474
  handle: row.handle,
@@ -1442,27 +1485,22 @@ let SandboxService = class SandboxService {
1442
1485
  }
1443
1486
  /**
1444
1487
  * Under a just-taken exclusive lease: makes the instance run (file system, create / resume /
1445
- * rebuild when the recorded instance is the one found gone), kills leftovers, then downgrades to
1446
- * a shared lease. Crashed holders' records are claimed here: on an instance just resumed from
1447
- * `suspended` one `killAll` covers them and anything else left (nobody else holds the instance),
1448
- * on a new instance there is nothing to kill, and on one that already ran their tags are killed.
1488
+ * rebuild when the recorded instance is the one found gone), revokes what crashed holders left,
1489
+ * then downgrades to a shared lease. A resumed instance's started-or-unknown operations were
1490
+ * revoked by `ensure` before its row said running; here the crashed holders' records are owed and
1491
+ * forgotten and every owed revoke of the instance is delivered (nothing is `killAll`ed).
1449
1492
  */
1450
1493
  async asExclusive(ctx, p, lease, gone, signal) {
1451
1494
  const env = ctx.deviceId;
1452
1495
  const sig = AbortSignal.any([signal, lease.signal]);
1453
1496
  try {
1454
1497
  // under the lease the B1 snapshot writer needs: a device carrying the reconcile marker gets
1455
- // no create, resume, rebuild, limits change, retirement destroy or kill (B-11)
1498
+ // no create, resume, rebuild, limits change, retirement destroy or revocation (B-11)
1456
1499
  await this.facts.assertCloudReconciled(ctx.orgId, env);
1457
1500
  const s = await this.ensure(ctx, p, lease, sig, gone);
1458
- const dead = await this.claim(env);
1459
- if (s.resumed)
1460
- await this.killLeftovers(env, s.handle, p, sig, dead);
1461
- else if (!s.info.fresh)
1462
- await this.killTagged(env, s.handle, p, dead, signal, lease);
1463
- if (s.resumed || s.info.fresh) {
1464
- await this.killPendingTasks(env, s.handle, s.createdAt, p, lease.token, ctx.actor, sig);
1465
- }
1501
+ // the dead holders' records are forgotten only after their revocation is owed (on a fresh
1502
+ // instance too: their intents still name them); a resume delivers what `ensure` revoked
1503
+ await this.takeOver(env, { provider: p.plugin, generation: String(s.createdAt) }, s.handle, p, signal, lease, s.resumed === true);
1466
1504
  // B-15: a resumed cloud instance reads its permission support again; any other instance
1467
1505
  // whose recorded evidence is stale (a limits change, a provider version change) too
1468
1506
  await this.refreshCloudSupport(ctx, p, s, sig, s.resumed === true);
@@ -1514,38 +1552,141 @@ let SandboxService = class SandboxService {
1514
1552
  .unregisterHolder(env, token)
1515
1553
  .catch((err) => this.log.warn("cannot clear sandbox holder record", { deviceId: env, err }));
1516
1554
  }
1517
- /** Crashed holders' tags (claimed); a Redis error counts as none. */
1518
- async claim(env) {
1555
+ /**
1556
+ * The crashed holders' cleanup (permission runtime cutover B-1): their tokens are read without
1557
+ * removing them, their revocation is owed durably ({@link oweDeadHolders}), it runs inline
1558
+ * (`revokeHolders`), and the owed operation revokes of the instance are delivered by operation id
1559
+ * ({@link deliverRevocations}). `delivered`: a resume under the exclusive lease, which delivers
1560
+ * the revokes `ensure` owed on the incarnation even with no crashed holder. A failure after the
1561
+ * revocation is owed is only warned (the outbox retries it); gone and abort are thrown.
1562
+ */
1563
+ async takeOver(env, instance, handle, p, signal, lease, delivered = false) {
1564
+ const dead = await this.oweDeadHolders(env);
1565
+ if (dead.length === 0 && !delivered)
1566
+ return;
1567
+ const sig = AbortSignal.any([signal, lease.signal]);
1568
+ if (dead.length > 0) {
1569
+ try {
1570
+ await runOutsideTransaction(() => this.operationIntents.revokeHolders(env, dead));
1571
+ this.log.info("sandbox taken over from a holder that did not finish; its operations revoked", {
1572
+ deviceId: env,
1573
+ });
1574
+ }
1575
+ catch (err) {
1576
+ if (sig.aborted)
1577
+ throw err;
1578
+ this.log.warn("cannot revoke a crashed sandbox holder's operations now; a worker retries", {
1579
+ deviceId: env,
1580
+ err,
1581
+ });
1582
+ }
1583
+ }
1584
+ await this.deliverRevocations(env, instance, handle, p, sig);
1585
+ }
1586
+ /**
1587
+ * Crashed holders' tokens whose revocation is now owed durably: read without removing them, an
1588
+ * outbox row per token committed ({@link SandboxOperationIntents.oweHolderRevocations}), then
1589
+ * their records forgotten. A Redis or database error leaves the records for the next acquirer
1590
+ * and counts as none.
1591
+ */
1592
+ async oweDeadHolders(env) {
1593
+ let dead;
1519
1594
  try {
1520
- return await this.leases.claimDeadHolders(env);
1595
+ dead = await this.leases.deadHolders(env);
1521
1596
  }
1522
1597
  catch (err) {
1523
1598
  this.log.warn("cannot read sandbox holder records", { deviceId: env, err });
1524
1599
  return [];
1525
1600
  }
1601
+ if (dead.length === 0)
1602
+ return [];
1603
+ try {
1604
+ await runOutsideTransaction(() => this.operationIntents.oweHolderRevocations(env, dead));
1605
+ }
1606
+ catch (err) {
1607
+ this.log.warn("cannot owe a crashed sandbox holder's revocation; the next acquirer will", {
1608
+ deviceId: env,
1609
+ err,
1610
+ });
1611
+ return [];
1612
+ }
1613
+ await this.leases
1614
+ .forgetHolders(env, dead)
1615
+ .catch((err) => this.log.warn("cannot clear crashed sandbox holder records", { deviceId: env, err }));
1616
+ return dead;
1526
1617
  }
1527
- /** Kills the commands of crashed holders by their tags (`killTagged`); nothing without tags. */
1528
- async killTagged(env, handle, p, tags, signal, lease) {
1529
- if (tags.length === 0)
1618
+ /**
1619
+ * The exact cleanup of an incarnation nobody else holds (exclusive lease), in place of a broad
1620
+ * `killAll`: revokes its started-or-unknown operations
1621
+ * ({@link SandboxOperationIntents.revokeIncarnation}) and delivers the owed revokes. Thrown when
1622
+ * the revocation cannot be recorded (`strict`), else only warned: the caller's row still says
1623
+ * suspended, so the next resume revokes again.
1624
+ */
1625
+ async revokeIncarnation(env, instance, handle, p, signal, strict) {
1626
+ try {
1627
+ await runOutsideTransaction(() => this.operationIntents.revokeIncarnation(env, instance));
1628
+ }
1629
+ catch (err) {
1630
+ if (strict || signal.aborted)
1631
+ throw err;
1632
+ this.log.warn("cannot revoke the sandbox instance's leftover operations", {
1633
+ deviceId: env,
1634
+ err,
1635
+ });
1530
1636
  return;
1531
- await runOutsideTransaction(() => this.operationIntents.revokeHolders(env, tags));
1532
- const sig = AbortSignal.any([signal, lease.signal]);
1533
- await this.kill(env, "takeover", () => p.impl.killTagged(handle, tags, sig), sig);
1637
+ }
1638
+ await this.deliverRevocations(env, instance, handle, p, signal);
1534
1639
  }
1535
- /** Runs one kill call: gone and abort are thrown, other failures only warned. */
1536
- async kill(deviceId, why, call, signal) {
1640
+ /**
1641
+ * Delivers the owed operation revokes of one instance generation inline, by operation id
1642
+ * (`revokeOperation`), acknowledging each: what the revoke jobs would deliver, sent before this
1643
+ * holder runs anything. Best effort, as the broad `killAll` it replaces was: at most
1644
+ * {@link INLINE_REVOKE_LIMIT} per call, nothing for a provider without `revokeOperation`, and any
1645
+ * failure only warned. Durability does not depend on it: every revocation wrote its
1646
+ * `sandbox-operation-revoke-<operationId>` outbox job in the same transaction, and those jobs
1647
+ * deliver until acknowledged. Gone and abort are thrown (the use rebuilds / ends).
1648
+ */
1649
+ async deliverRevocations(env, instance, handle, p, signal) {
1650
+ const revoke = p.impl.revokeOperation?.bind(p.impl);
1651
+ if (!revoke)
1652
+ return;
1653
+ let owed;
1537
1654
  try {
1538
- await call();
1539
- if (why === "takeover") {
1540
- this.log.info("sandbox taken over from a holder that did not finish; leftover commands killed", { deviceId });
1541
- }
1655
+ owed = await this.operationIntents.owedRevocations(env, instance, INLINE_REVOKE_LIMIT);
1542
1656
  }
1543
1657
  catch (err) {
1544
- if (signal?.aborted || isSandboxGoneError(err))
1658
+ if (signal.aborted)
1545
1659
  throw err;
1546
- this.log.warn("cannot kill leftover sandbox commands", { deviceId, err });
1660
+ this.log.warn("cannot read the sandbox instance's owed revocations", { deviceId: env, err });
1661
+ return;
1662
+ }
1663
+ for (const o of owed) {
1664
+ try {
1665
+ await revoke(handle, { operationId: o.operationId, admitBeforeMs: o.deadline.getTime() }, AbortSignal.any([signal, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS)]));
1666
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeRevocation(o.operationId));
1667
+ }
1668
+ catch (err) {
1669
+ if (signal.aborted || isSandboxGoneError(err))
1670
+ throw err;
1671
+ this.log.warn("cannot deliver an owed operation revoke now; its job retries", {
1672
+ deviceId: env,
1673
+ operationId: o.operationId,
1674
+ err,
1675
+ });
1676
+ }
1547
1677
  }
1548
1678
  }
1679
+ /** The {@link RevokedIncarnation} of an instance row. */
1680
+ incarnationOf(row) {
1681
+ return { provider: row.provider ?? "", generation: String(row.created_at.getTime()) };
1682
+ }
1683
+ /**
1684
+ * The owed revocation job of one crashed holder (`sandbox-holder-revoke`): revokes its intents
1685
+ * still admitted, dispatching or started-or-unknown and owes each its exact revoke job.
1686
+ */
1687
+ async revokeDeadHolder(deviceId, token) {
1688
+ await this.operationIntents.revokeHolders(deviceId, [token]);
1689
+ }
1549
1690
  /**
1550
1691
  * Suspends running instances idle longer than `suspendAfterIdleMinutes` or running continuously
1551
1692
  * longer than `maxRunningMinutes`. Skips a device with any holder; one past
@@ -1780,8 +1921,8 @@ let SandboxService = class SandboxService {
1780
1921
  * gate's alone (never resumed here). When the
1781
1922
  * marker stays on a live instance whose provider can `update`, the provider applies the
1782
1923
  * reconcile target, which is never wider than the instance in any dimension, so this only
1783
- * narrows; a suspended instance is resumed for it (its leftover commands killed, nobody else
1784
- * holds it) and suspended again, as its row still says. `updated` records the target as
1924
+ * narrows; a suspended instance is resumed for it (its leftover operations revoked exactly,
1925
+ * nobody else holds it) and suspended again, as its row still says. `updated` records the target as
1785
1926
  * applied (fenced) and the reconcile runs again, which clears the marker. No `update`, a
1786
1927
  * `recreate` answer, a gone instance or a failure leave the marker and its file reset action.
1787
1928
  */
@@ -1838,8 +1979,10 @@ let SandboxService = class SandboxService {
1838
1979
  if (suspended && (await p.impl.resume(handle, sig)) === "gone")
1839
1980
  answer = "gone";
1840
1981
  else {
1982
+ // what the pause brought back is revoked exactly before the update (the row still says
1983
+ // suspended: a failure is revoked again on the next resume)
1841
1984
  if (suspended)
1842
- await this.kill(deviceId, "resume", () => p.impl.killAll(handle, sig), sig);
1985
+ await this.revokeIncarnation(deviceId, { provider: p.plugin, generation: String(row.created_at.getTime()) }, handle, p, sig, false);
1843
1986
  answer = await update(handle, want, sig);
1844
1987
  }
1845
1988
  }
@@ -2319,69 +2462,6 @@ let SandboxService = class SandboxService {
2319
2462
  : restartRequired();
2320
2463
  return now;
2321
2464
  }
2322
- /**
2323
- * Under the exclusive lease (before the downgrade), on an instance just resumed from
2324
- * `suspended`: kills every command left in it (`killAll`), crashed holders' (`dead`, already
2325
- * claimed) included. Never on the shared path: other holders may be running commands. A gone
2326
- * instance (`SandboxGoneError`) and an abort are thrown (`withSandbox` rebuilds / ends); other
2327
- * failures are only warned.
2328
- */
2329
- async killLeftovers(deviceId, handle, p, signal, dead) {
2330
- await runOutsideTransaction(() => this.operationIntents.revokeHolders(deviceId, dead));
2331
- await this.kill(deviceId, dead.length > 0 ? "takeover" : "resume", () => p.impl.killAll(handle, signal), signal);
2332
- }
2333
- /**
2334
- * Under the exclusive lease, right after a resume or a (re)build: kills the sessions of the
2335
- * background tasks marked lost while their process may live on (`kill_pending`), in one exec of
2336
- * `pkill -KILL -s <sid>` (`-g` on macOS), then clears their flags. Tasks of another instance have no process
2337
- * here and are only cleared. A gone instance and an abort are thrown; another failure is warned
2338
- * and leaves the flags of this instance's tasks for the next resume.
2339
- */
2340
- async killPendingTasks(deviceId, handle, createdAt, p, tag, actor, signal) {
2341
- // after the legacy-launch freeze a SID is no authority and the kill marks belong to the
2342
- // retirement obligations: nothing is signalled or cleared (C1)
2343
- if (await this.retirement.frozen())
2344
- return;
2345
- const rows = await this.background.pendingKills(deviceId);
2346
- if (rows.length === 0)
2347
- return;
2348
- const mine = rows.filter((r) => r.sandboxCreatedAt?.getTime() === createdAt && r.sid !== null && SID_RE.test(r.sid));
2349
- let cleared = rows;
2350
- if (mine.length > 0) {
2351
- // pkill exits 1 when the session has no process left: only a higher status is a failure
2352
- const command = `${SESSION_MODE_SCRIPT}\nrc=0; for sid in ${mine.map((r) => r.sid).join(" ")}; do tk_kill KILL "$sid"; c=$?; [ "$c" -le 1 ] || rc=$c; done; exit $rc`;
2353
- try {
2354
- const r = await p.impl.exec(handle, {
2355
- command,
2356
- // tk_kill's control files are relative to the workspace root (macOS devices)
2357
- cwd: rootsOf(handle).workspace,
2358
- timeoutMs: PENDING_KILL_TIMEOUT_MS,
2359
- maxOutputBytes: 4096,
2360
- signal,
2361
- tag,
2362
- actor,
2363
- });
2364
- if (r.exitCode !== 0) {
2365
- throw new Error(`pkill exited with ${r.exitCode === null ? "no status" : r.exitCode}: ${r.stderr.slice(0, 500)}`);
2366
- }
2367
- this.log.info("lost background tasks killed after a sandbox resume", {
2368
- deviceId,
2369
- tasks: mine.map((t) => t.id),
2370
- });
2371
- }
2372
- catch (err) {
2373
- if (signal.aborted || isSandboxGoneError(err))
2374
- throw err;
2375
- this.log.warn("cannot kill lost background tasks after a sandbox resume", {
2376
- deviceId,
2377
- err,
2378
- });
2379
- const kept = new Set(mine.map((r) => r.id));
2380
- cleared = rows.filter((r) => !kept.has(r.id));
2381
- }
2382
- }
2383
- await this.background.clearKill(cleared.map((r) => r.id));
2384
- }
2385
2465
  /**
2386
2466
  * A fenced write: only while the lease holds and the row's generation is still the one read
2387
2467
  * under it (and incremented); otherwise {@link SandboxLockLostError}.
@@ -2560,6 +2640,7 @@ let SandboxService = class SandboxService {
2560
2640
  // the retirement gate may have resumed it already, to cancel revoked starts exactly (B-22)
2561
2641
  const r = gate.resumed ? "resumed" : await p.impl.resume(handle, signal);
2562
2642
  if (r === "resumed") {
2643
+ const incarnation = { provider: p.plugin, generation: String(createdAt) };
2563
2644
  // the new limits first: the row says running only once the instance runs with them
2564
2645
  if (want !== null && this.mustApply(row, p, want)) {
2565
2646
  let created;
@@ -2567,14 +2648,30 @@ let SandboxService = class SandboxService {
2567
2648
  created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
2568
2649
  }
2569
2650
  catch (err) {
2570
- // the row still says suspended; the next use resumes and kills what is left
2571
- await this.bestEffort(id, "kill the commands left after a failed limits change", (s) => p.impl.killAll(handle, s));
2651
+ // the work a pause brought back is revoked exactly, never killed broadly; the row
2652
+ // still says suspended, so the next use resumes and revokes again
2653
+ await this.revokeIncarnation(id, incarnation, handle, p, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS), false).catch((e) => this.log.warn("cannot revoke the operations left after a failed limits change", {
2654
+ deviceId: id,
2655
+ err: e,
2656
+ }));
2572
2657
  throw err;
2573
2658
  }
2574
2659
  if (created) {
2575
2660
  return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2576
2661
  }
2577
2662
  }
2663
+ // the work a pause brought back (every admitted, dispatching and started-or-unknown
2664
+ // operation of this generation) is revoked before the row says running; the revokes are
2665
+ // delivered before the downgrade. A failure fails the use closed: the instance is
2666
+ // suspended again (best effort, its failure only warned), the row still says
2667
+ // suspended, and the next use resumes and revokes again
2668
+ try {
2669
+ await runOutsideTransaction(() => this.operationIntents.revokeIncarnation(id, incarnation));
2670
+ }
2671
+ catch (err) {
2672
+ await this.bestEffort(id, "suspend the instance again after a failed revocation", (s) => p.impl.suspend(handle, s));
2673
+ throw err;
2674
+ }
2578
2675
  await this.fenced(held, id, fence, {
2579
2676
  status: "running",
2580
2677
  running_since: sql `now()`,
@@ -2757,7 +2854,10 @@ let SandboxService = class SandboxService {
2757
2854
  else if (signal.aborted || p.impl.limitsApplyAt === "fileSystem") {
2758
2855
  // the instance may run with half-applied limits and cannot be recreated here: stop it,
2759
2856
  // so the next use resumes it and applies them again
2760
- await this.quarantine(held, id, handle, p, fence);
2857
+ await this.quarantine(held, id, handle, p, fence, {
2858
+ provider: p.plugin,
2859
+ generation: String(row.created_at.getTime()),
2860
+ });
2761
2861
  // a provider bound to its file system that refuses the new network (E2B)
2762
2862
  throw providerRefusal(this.log, err, { deviceId: id, provider: p.plugin, op: "update" }, want, signal);
2763
2863
  }
@@ -2794,13 +2894,15 @@ let SandboxService = class SandboxService {
2794
2894
  }
2795
2895
  /**
2796
2896
  * After a failed `update` that cannot be repaired by a recreate: best effort, with fresh short
2797
- * signals (the use's own may be aborted), suspends the instance (or kills its commands) and
2897
+ * signals (the use's own may be aborted), suspends the instance (or revokes its operations) and
2798
2898
  * records it suspended (fenced: a lost lease leaves the record to the new holder).
2799
2899
  */
2800
- async quarantine(held, id, handle, p, fence) {
2900
+ async quarantine(held, id, handle, p, fence, incarnation) {
2801
2901
  const suspended = await this.bestEffort(id, "suspend after a failed limits update", (s) => p.impl.suspend(handle, s));
2802
2902
  if (!suspended) {
2803
- await this.bestEffort(id, "kill commands after a failed limits update", (s) => p.impl.killAll(handle, s));
2903
+ // still running with half-applied limits: its leftover operations are revoked exactly (the
2904
+ // row is recorded suspended, so the next resume revokes again)
2905
+ await this.bestEffort(id, "revoke the operations after a failed limits update", (s) => this.revokeIncarnation(id, incarnation, handle, p, s, false));
2804
2906
  }
2805
2907
  try {
2806
2908
  await this.fenced(held, id, fence, {
@@ -2819,7 +2921,7 @@ let SandboxService = class SandboxService {
2819
2921
  /** Runs `call` with its own short signal; a failure is warned and returns false. */
2820
2922
  async bestEffort(deviceId, what, call) {
2821
2923
  try {
2822
- await call(AbortSignal.timeout(PENDING_KILL_TIMEOUT_MS));
2924
+ await call(AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS));
2823
2925
  return true;
2824
2926
  }
2825
2927
  catch (err) {
@@ -3028,12 +3130,11 @@ SandboxService = __decorate([
3028
3130
  __param(3, Inject(SandboxProviders)),
3029
3131
  __param(4, Inject(KernelConfigService)),
3030
3132
  __param(5, Inject(KERNEL_LOGGER)),
3031
- __param(6, Inject(BackgroundTaskStore)),
3032
- __param(7, Inject(PermissionFacts)),
3033
- __param(8, Inject(SandboxOperationIntents)),
3034
- __param(9, Inject(SandboxOperationAuthority)),
3035
- __param(10, Inject(PermissionInstanceWrites)),
3036
- __param(11, Inject(LegacyRetirementStore)),
3037
- __param(12, Inject(CloudPermissionSnapshots))
3133
+ __param(6, Inject(PermissionFacts)),
3134
+ __param(7, Inject(SandboxOperationIntents)),
3135
+ __param(8, Inject(SandboxOperationAuthority)),
3136
+ __param(9, Inject(PermissionInstanceWrites)),
3137
+ __param(10, Inject(LegacyRetirementStore)),
3138
+ __param(11, Inject(CloudPermissionSnapshots))
3038
3139
  ], SandboxService);
3039
3140
  export { SandboxService };
@@ -11,7 +11,7 @@ import { type OrgRole } from "../orgs/roles.js";
11
11
  import { RunResume } from "../runtime/run-jobs.js";
12
12
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
13
13
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
14
- import type { PermissionCandidate, PermissionExpansion } from "../sandbox/permission-call-types.js";
14
+ import type { PermissionCandidate, PermissionEscalation, PermissionExpansion } from "../sandbox/permission-call-types.js";
15
15
  import { SandboxService } from "../sandbox/sandbox.service.js";
16
16
  import { ScheduledTaskStore } from "../schedules/store.js";
17
17
  import type { ApprovalPolicySource } from "./pipeline.js";
@@ -122,6 +122,11 @@ export interface CommandAskDetail {
122
122
  permissionScope?: PermissionExpansion;
123
123
  targetPath?: string;
124
124
  candidateHash?: string;
125
+ /**
126
+ * The command asks to run outside the OS sandbox for this call only (per-call escalation): the
127
+ * model's justification. An approval grants full execution for exactly this call.
128
+ */
129
+ escalation?: PermissionEscalation;
125
130
  deviceId: string;
126
131
  deviceName: string;
127
132
  mode: "auto" | "sandbox";
@@ -548,6 +548,7 @@ let ApprovalsService = class ApprovalsService {
548
548
  ...(candidate.targetPath
549
549
  ? { targetPath: candidate.targetPath, path: candidate.targetPath }
550
550
  : {}),
551
+ ...(candidate.escalation ? { escalation: candidate.escalation } : {}),
551
552
  }
552
553
  : {}),
553
554
  };
@@ -595,6 +596,15 @@ let ApprovalsService = class ApprovalsService {
595
596
  ...(detail.permissionCandidate.targetPath
596
597
  ? { targetPath: detail.permissionCandidate.targetPath }
597
598
  : {}),
599
+ // an escalation shows its justification and the directory the command runs in
600
+ ...(detail.permissionCandidate.escalation
601
+ ? {
602
+ escalation: detail.permissionCandidate.escalation,
603
+ ...(detail.workingRoot !== undefined && {
604
+ workingRoot: detail.workingRoot,
605
+ }),
606
+ }
607
+ : {}),
598
608
  }
599
609
  : {}),
600
610
  kind: detail.kind,