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

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 (247) hide show
  1. package/bootstrap.json +6 -6
  2. package/dist/admin/outbox-dead.service.js +4 -1
  3. package/dist/agents/admin-agents.js +2 -0
  4. package/dist/agents/agent-lookup.js +4 -0
  5. package/dist/agents/agent-profile.service.js +3 -0
  6. package/dist/agents/agents.service.js +7 -0
  7. package/dist/agents/org-templates.js +1 -0
  8. package/dist/agents/pending-connector-requests.js +6 -0
  9. package/dist/agents/pending-connectors.service.js +2 -0
  10. package/dist/agents/readiness.service.d.ts +9 -3
  11. package/dist/agents/readiness.service.js +3 -3
  12. package/dist/agents/templates.js +1 -0
  13. package/dist/background/finish.js +3 -0
  14. package/dist/background/stop.js +2 -0
  15. package/dist/background/store.js +44 -0
  16. package/dist/background/tasks.service.js +3 -2
  17. package/dist/background/wake-rules.js +1 -0
  18. package/dist/catalog/admin-catalog.controller.d.ts +6 -0
  19. package/dist/catalog/admin-catalog.controller.js +13 -0
  20. package/dist/catalog/catalog-content.d.ts +9 -0
  21. package/dist/catalog/catalog-content.js +3 -1
  22. package/dist/catalog/catalog-items.js +4 -0
  23. package/dist/catalog/catalog-scope.service.js +4 -1
  24. package/dist/catalog/component-promotion.js +2 -0
  25. package/dist/catalog/component-scope.controller.d.ts +9 -15
  26. package/dist/catalog/component-scope.controller.js +14 -9
  27. package/dist/catalog/component-scope.service.js +5 -0
  28. package/dist/catalog/component-state.d.ts +4 -1
  29. package/dist/catalog/component-state.js +4 -2
  30. package/dist/catalog/marketplace-fetch.d.ts +1 -1
  31. package/dist/catalog/marketplace-fetch.js +1 -1
  32. package/dist/catalog/marketplaces.service.d.ts +6 -1
  33. package/dist/catalog/marketplaces.service.js +8 -3
  34. package/dist/catalog/org-catalog.controller.d.ts +9 -0
  35. package/dist/catalog/org-catalog.controller.js +18 -0
  36. package/dist/catalog/org-catalog.schemas.d.ts +2 -4
  37. package/dist/catalog/org-catalog.schemas.js +2 -3
  38. package/dist/catalog/org-catalog.service.d.ts +10 -1
  39. package/dist/catalog/org-catalog.service.js +34 -23
  40. package/dist/catalog/org-extension-switch.d.ts +3 -10
  41. package/dist/catalog/org-extension-switch.js +14 -60
  42. package/dist/catalog/org-extension.controller.d.ts +6 -7
  43. package/dist/catalog/org-extension.controller.js +4 -4
  44. package/dist/catalog/org-extension.schemas.d.ts +1 -2
  45. package/dist/catalog/org-extension.schemas.js +1 -3
  46. package/dist/catalog/owned-items.js +10 -1
  47. package/dist/catalog/ownership.js +2 -0
  48. package/dist/catalog/plugin-import.d.ts +3 -0
  49. package/dist/catalog/plugin-import.js +10 -1
  50. package/dist/catalog/plugin-install.d.ts +1 -4
  51. package/dist/catalog/plugin-install.js +11 -12
  52. package/dist/catalog/plugin-upgrade.js +4 -1
  53. package/dist/catalog/request-rules.js +6 -0
  54. package/dist/catalog/requests.service.js +4 -0
  55. package/dist/catalog/scope-orgs.js +1 -0
  56. package/dist/catalog/scope-sync.d.ts +8 -5
  57. package/dist/catalog/scope-sync.js +21 -23
  58. package/dist/catalog/template-description.d.ts +17 -0
  59. package/dist/catalog/template-description.js +18 -0
  60. package/dist/catalog/unshare.js +3 -0
  61. package/dist/channels/connections.service.js +1 -0
  62. package/dist/channels/inbound.js +1 -0
  63. package/dist/channels/jobs.js +1 -0
  64. package/dist/channels/outbound.js +6 -0
  65. package/dist/channels/supervisor.js +1 -0
  66. package/dist/channels/threads.js +1 -0
  67. package/dist/client/client-reports.service.js +1 -0
  68. package/dist/config/fields.js +20 -4
  69. package/dist/config/schema.d.ts +1 -1
  70. package/dist/config/schema.js +13 -13
  71. package/dist/conversations/access.js +1 -0
  72. package/dist/conversations/attachments.service.js +16 -4
  73. package/dist/conversations/conversations.service.js +17 -3
  74. package/dist/conversations/event-log.js +2 -0
  75. package/dist/conversations/events.d.ts +1 -0
  76. package/dist/conversations/events.js +3 -1
  77. package/dist/conversations/files.js +3 -2
  78. package/dist/conversations/permission-profiles.service.js +1 -0
  79. package/dist/conversations/prompt-suggestions.js +2 -0
  80. package/dist/conversations/queue.js +8 -0
  81. package/dist/conversations/queue.service.js +6 -2
  82. package/dist/conversations/source.js +2 -0
  83. package/dist/conversations/titles.js +10 -2
  84. package/dist/conversations/tree.js +6 -0
  85. package/dist/db/kernel-schema.d.ts +5 -1
  86. package/dist/devices/conversation-devices.js +3 -0
  87. package/dist/devices/device-projects.service.js +2 -0
  88. package/dist/devices/devices.service.js +5 -0
  89. package/dist/devices/legacy-cleanup.job.js +5 -2
  90. package/dist/dial-in/handlers.js +2 -0
  91. package/dist/dial-in/machines.js +11 -2
  92. package/dist/dial-in/targets.d.ts +0 -2
  93. package/dist/dial-in/targets.js +0 -10
  94. package/dist/errors.d.ts +0 -1
  95. package/dist/errors.js +0 -1
  96. package/dist/evals/budget.js +14 -1
  97. package/dist/evals/run-replay.js +4 -0
  98. package/dist/evals/runs.service.js +13 -7
  99. package/dist/evals/sets.service.js +23 -8
  100. package/dist/evals/trajectory.service.d.ts +1 -1
  101. package/dist/evals/trajectory.service.js +1 -0
  102. package/dist/evals/worker.js +5 -1
  103. package/dist/extensions/admin-ops.js +1 -0
  104. package/dist/extensions/admin-view.js +3 -1
  105. package/dist/extensions/bootstrap-packages.d.ts +12 -1
  106. package/dist/extensions/bootstrap-packages.js +49 -9
  107. package/dist/extensions/bootstrap.d.ts +17 -2
  108. package/dist/extensions/bootstrap.js +41 -9
  109. package/dist/extensions/config-json-schema.d.ts +2 -2
  110. package/dist/extensions/config-json-schema.js +1 -3
  111. package/dist/extensions/deployment-config.d.ts +5 -3
  112. package/dist/extensions/deployment-config.js +3 -3
  113. package/dist/extensions/effective-config.d.ts +8 -7
  114. package/dist/extensions/effective-config.js +8 -7
  115. package/dist/extensions/enabled.js +1 -0
  116. package/dist/extensions/host.d.ts +4 -3
  117. package/dist/extensions/host.js +11 -12
  118. package/dist/extensions/instance.d.ts +1 -1
  119. package/dist/extensions/instance.js +17 -2
  120. package/dist/extensions/org-config.d.ts +35 -97
  121. package/dist/extensions/org-config.js +48 -315
  122. package/dist/extensions/org-levels.d.ts +22 -9
  123. package/dist/extensions/org-levels.js +100 -20
  124. package/dist/extensions/org-overrides.d.ts +14 -15
  125. package/dist/extensions/org-overrides.js +20 -20
  126. package/dist/extensions/package.js +1 -1
  127. package/dist/extensions/permission-set.d.ts +1 -3
  128. package/dist/extensions/permission-set.js +3 -7
  129. package/dist/extensions/permission-view.d.ts +3 -1
  130. package/dist/extensions/permission-view.js +5 -4
  131. package/dist/extensions/plugin-icons.d.ts +80 -1
  132. package/dist/extensions/plugin-icons.js +211 -2
  133. package/dist/extensions/point-defaults.d.ts +17 -18
  134. package/dist/extensions/point-defaults.js +25 -28
  135. package/dist/git/gateway.js +1 -1
  136. package/dist/git/identity.d.ts +1 -1
  137. package/dist/git/identity.js +2 -2
  138. package/dist/identity/accounts.js +6 -0
  139. package/dist/identity/api-tokens.js +8 -0
  140. package/dist/infra/outbox/outbox.dispatcher.js +4 -1
  141. package/dist/infra/outbox/outbox.service.js +2 -0
  142. package/dist/net/public-address.d.ts +3 -3
  143. package/dist/net/public-address.js +3 -3
  144. package/dist/orgs/directory-sync.d.ts +9 -6
  145. package/dist/orgs/directory-sync.js +15 -12
  146. package/dist/orgs/invitations.service.js +2 -0
  147. package/dist/orgs/members.service.js +2 -0
  148. package/dist/orgs/offboarding.js +2 -0
  149. package/dist/packages/npm.d.ts +10 -2
  150. package/dist/packages/npm.js +38 -6
  151. package/dist/platform/exclusions.js +20 -0
  152. package/dist/platform/ops/admin-items.ops.js +1 -0
  153. package/dist/platform/ops/agents.ops.js +1 -0
  154. package/dist/platform/ops/connectors.ops.js +7 -1
  155. package/dist/platform/ops/extensions.ops.d.ts +6 -8
  156. package/dist/platform/ops/extensions.ops.js +18 -97
  157. package/dist/platform/ops/org-plugins.ops.d.ts +3 -6
  158. package/dist/platform/ops/org-plugins.ops.js +14 -65
  159. package/dist/platform/ops/outbox.ops.js +1 -0
  160. package/dist/platform/ops/person-inputs.d.ts +0 -4
  161. package/dist/platform/ops/person-inputs.js +0 -8
  162. package/dist/platform/ops/plugins.ops.d.ts +4 -1
  163. package/dist/platform/ops/plugins.ops.js +27 -34
  164. package/dist/platform/person-fields.d.ts +1 -1
  165. package/dist/platform/person-fields.js +1 -1
  166. package/dist/platform/sealed-reveals.js +2 -0
  167. package/dist/push/recipients.js +9 -2
  168. package/dist/runtime/permission-context.service.js +1 -0
  169. package/dist/runtime/plugin-context.service.js +1 -0
  170. package/dist/runtime/project/knowledge.service.js +1 -0
  171. package/dist/runtime/run-context.service.js +1 -0
  172. package/dist/runtime/run-deletion.js +4 -0
  173. package/dist/runtime/run-execution.js +2 -0
  174. package/dist/runtime/run-finish.js +3 -0
  175. package/dist/runtime/run-jobs.js +3 -0
  176. package/dist/runtime/run-orphan-check.job.js +7 -0
  177. package/dist/runtime/run-queue.js +21 -2
  178. package/dist/runtime/run-worker.js +5 -0
  179. package/dist/runtime/step-log.js +1 -0
  180. package/dist/runtime/subagents/child.js +2 -0
  181. package/dist/runtime/subagents/deliveries.js +3 -0
  182. package/dist/runtime/subagents/dispatch.js +5 -1
  183. package/dist/runtime/subagents/messages.js +2 -0
  184. package/dist/runtime/subagents/org-agents.d.ts +1 -1
  185. package/dist/runtime/subagents/org-agents.js +2 -1
  186. package/dist/runtime/usage-report-jobs.js +1 -0
  187. package/dist/runtime/usage-report.js +3 -0
  188. package/dist/runtime/waits.js +5 -0
  189. package/dist/sandbox/cloud-permission-snapshot.js +9 -3
  190. package/dist/sandbox/device-reports.js +3 -0
  191. package/dist/sandbox/legacy-retirement.js +5 -1
  192. package/dist/sandbox/managed-device-context.js +1 -0
  193. package/dist/sandbox/modes.d.ts +5 -2
  194. package/dist/sandbox/modes.js +8 -4
  195. package/dist/sandbox/network-grants.js +2 -0
  196. package/dist/sandbox/operation-intents.js +58 -0
  197. package/dist/sandbox/operation-reconcile.job.js +2 -0
  198. package/dist/sandbox/permission-authority-lock.js +12 -6
  199. package/dist/sandbox/permission-call-grants.js +6 -0
  200. package/dist/sandbox/permission-ceiling-writes.js +5 -0
  201. package/dist/sandbox/permission-config-publication.js +5 -0
  202. package/dist/sandbox/permission-instance-writes.js +4 -0
  203. package/dist/sandbox/permission-runtime-reports.js +10 -1
  204. package/dist/sandbox/permission-transitions.js +3 -0
  205. package/dist/sandbox/review/review.service.js +8 -5
  206. package/dist/sandbox/sandbox.service.d.ts +14 -0
  207. package/dist/sandbox/sandbox.service.js +195 -29
  208. package/dist/sandbox/unreachable.js +4 -1
  209. package/dist/schedules/fire.js +9 -3
  210. package/dist/schedules/pause.js +2 -0
  211. package/dist/schedules/run-tracker.js +16 -1
  212. package/dist/schedules/scheduled-tasks.service.js +4 -2
  213. package/dist/schedules/store.js +8 -0
  214. package/dist/schedules/unattended.js +4 -0
  215. package/dist/setup/setup-checks.service.d.ts +1 -10
  216. package/dist/setup/setup-checks.service.js +19 -29
  217. package/dist/shares/share-open.service.js +1 -0
  218. package/dist/shares/shares.service.js +2 -0
  219. package/dist/skills/agent-skills.service.d.ts +1 -1
  220. package/dist/skills/agent-skills.service.js +13 -2
  221. package/dist/skills/catalog.js +3 -0
  222. package/dist/skills/changes.service.js +10 -2
  223. package/dist/skills/conversation-catalog.js +1 -0
  224. package/dist/skills/skills.service.js +4 -0
  225. package/dist/tools/approvals.service.js +40 -0
  226. package/dist/tools/builtins/schedules.js +11 -6
  227. package/dist/tools/builtins/web/fetch.js +1 -1
  228. package/dist/tools/builtins/web/search.js +1 -1
  229. package/dist/tools/connector-account-policies.js +3 -0
  230. package/dist/tools/connectors.controller.d.ts +37 -9
  231. package/dist/tools/connectors.controller.js +47 -12
  232. package/dist/tools/connectors.schemas.d.ts +4 -0
  233. package/dist/tools/connectors.schemas.js +13 -1
  234. package/dist/tools/connectors.service.d.ts +17 -0
  235. package/dist/tools/connectors.service.js +36 -2
  236. package/dist/tools/drift.js +5 -0
  237. package/dist/tools/git-push-policy.js +3 -0
  238. package/dist/tools/oauth/discovery.d.ts +2 -2
  239. package/dist/tools/oauth/discovery.js +2 -2
  240. package/dist/tools/oauth/flow.js +1 -0
  241. package/dist/tools/outputs.js +2 -0
  242. package/dist/tools/permission-approval-jobs.js +3 -0
  243. package/dist/tools/pipeline.js +2 -0
  244. package/dist/tools/policy.js +3 -0
  245. package/dist/tools/questions.service.js +13 -0
  246. package/package.json +3 -3
  247. package/src/migrations/0181_connector_description.sql +3 -0
@@ -39,7 +39,7 @@ const backgroundBinding = (args, instanceId) => ({
39
39
  instanceId,
40
40
  });
41
41
  import { randomUUID } from "node:crypto";
42
- import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, rootsOf, } from "@capybara-hq/plugin-sdk";
42
+ import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, isStaleFenceError, rootsOf, } from "@capybara-hq/plugin-sdk";
43
43
  import { Inject, Injectable, Optional } from "@nestjs/common";
44
44
  import { sql, } from "kysely";
45
45
  import { MANAGED_STOP_GRACE_MS } from "../background/managed.js";
@@ -116,6 +116,11 @@ function parseDeferred(raw) {
116
116
  return null;
117
117
  }
118
118
  }
119
+ /**
120
+ * The token a lifecycle call carries (device update fencing design §3.2): the generation this
121
+ * holder's own last fenced write committed; null without a fence (nothing to compare).
122
+ */
123
+ const tokenOf = (fence) => fence === null ? null : { token: fence.gen };
119
124
  /** The signal of one provider call in maintenance: aborted on timeout or when the lease is lost. */
120
125
  const opSignal = (lease) => AbortSignal.any([lease.signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]);
121
126
  /** The provider-side name of a device's file system and instance. */
@@ -534,10 +539,12 @@ let SandboxService = class SandboxService {
534
539
  appliedLacksHost(rec.applied, effective));
535
540
  const fsBound = differs && row.fs_status === "ready" && this.fsBound(p, rec, effective);
536
541
  const hasInstance = row.handle !== null && (row.status === "running" || row.status === "suspended");
542
+ // an update the kernel never heard back from is applied again at the next use (§7.2)
543
+ const inFlight = row.provider === p.plugin && rec.pending !== null;
537
544
  return {
538
545
  applied: rec.applied,
539
546
  effective,
540
- pendingNextUse: differs && !fsBound && hasInstance,
547
+ pendingNextUse: ((differs && !fsBound) || inFlight) && hasInstance,
541
548
  pendingFilesReset: fsBound,
542
549
  };
543
550
  }
@@ -560,9 +567,15 @@ let SandboxService = class SandboxService {
560
567
  * the exclusive lease once for a narrowing, so `applyLimits` records it as `unapplied` (the
561
568
  * device is then unprobed until the reset, never silently supported); an added host there only
562
569
  * waits for the reset (`pendingFilesReset`).
570
+ *
571
+ * A recorded `pending` (an `update` sent and never answered, device update fencing design §7.2)
572
+ * always applies again, even when `applied` already matches `want`: the instance may enforce
573
+ * the in-flight target, and only a newer call with this holder's higher token settles it.
563
574
  */
564
575
  mustApply(row, p, want) {
565
576
  const rec = readInstanceLimits(row.instance_limits);
577
+ if (rec.pending !== null)
578
+ return true;
566
579
  const target = appliedOf(want);
567
580
  const wider = appliedWider(rec.applied, target);
568
581
  if (sameApplied(rec.applied, target) && !wider && !appliedLacksHost(rec.applied, target))
@@ -593,6 +606,8 @@ let SandboxService = class SandboxService {
593
606
  * instance its own lease keeps.
594
607
  */
595
608
  async currentInstance(deviceId) {
609
+ // org-filter: deviceId is the device its caller already resolved in its org (the tool's bound
610
+ // device); the instance row is keyed by its device
596
611
  const row = await this.db
597
612
  .selectFrom("device_instances")
598
613
  .select(["status", "handle", "created_at", "provider"])
@@ -637,6 +652,8 @@ let SandboxService = class SandboxService {
637
652
  for (;;) {
638
653
  if (signal.aborted)
639
654
  throw abortReason(signal);
655
+ // org-filter: deviceId comes from an org-scoped background task row or a kernel-written
656
+ // operation intent, never caller input; the instance row is keyed by its device
640
657
  const row = await this.db
641
658
  .selectFrom("device_instances")
642
659
  .selectAll()
@@ -946,6 +963,7 @@ let SandboxService = class SandboxService {
946
963
  provider: p.plugin,
947
964
  });
948
965
  try {
966
+ // org-filter: the device this holder entered under its lease after readRow's org check
949
967
  await this.db
950
968
  .updateTable("device_instances")
951
969
  .set((eb) => ({ fs_status: "lost", generation: eb("generation", "+", 1) }))
@@ -1415,6 +1433,7 @@ let SandboxService = class SandboxService {
1415
1433
  .selectFrom("device_instances")
1416
1434
  .select("instance_limits")
1417
1435
  .where("device_id", "=", ctx.deviceId)
1436
+ .where("org_id", "=", ctx.orgId)
1418
1437
  .executeTakeFirst();
1419
1438
  if (!row)
1420
1439
  return;
@@ -1440,6 +1459,8 @@ let SandboxService = class SandboxService {
1440
1459
  .catch((err) => this.log.warn("cannot clear sandbox intent", { deviceId: env, err }));
1441
1460
  }
1442
1461
  async readRow(ctx) {
1462
+ // org-filter: reads org_id and throws foreign below: a filter would turn another org's device
1463
+ // into a missing one
1443
1464
  const row = await this.db
1444
1465
  .selectFrom("device_instances")
1445
1466
  .selectAll()
@@ -1497,6 +1518,7 @@ let SandboxService = class SandboxService {
1497
1518
  .updateTable("device_instances")
1498
1519
  .set((eb) => ({ generation: eb("generation", "+", 1) }))
1499
1520
  .where("device_id", "=", env)
1521
+ .where("org_id", "=", ctx.orgId)
1500
1522
  .execute();
1501
1523
  await this.register(env, lease.token);
1502
1524
  // other holders (any conversation of the device) may be running: only the dead holders'
@@ -1564,6 +1586,7 @@ let SandboxService = class SandboxService {
1564
1586
  async leave(env, e) {
1565
1587
  await this.unregister(env, e.lease.token);
1566
1588
  await e.lease.release();
1589
+ // org-filter: the device this holder entered under its lease after readRow's org check
1567
1590
  await this.db
1568
1591
  .updateTable("device_instances")
1569
1592
  .set({ last_used_at: sql `GREATEST(last_used_at, now())` })
@@ -1742,6 +1765,8 @@ let SandboxService = class SandboxService {
1742
1765
  const overdue = c.running_since !== null && c.running_since < runningBefore;
1743
1766
  const done = await this.tryLocked(c.device_id, async (lease) => {
1744
1767
  const id = c.device_id;
1768
+ // org-filter: deployment-wide suspension sweep (worker) over every org's idle instances,
1769
+ // re-read under each device's lease
1745
1770
  const row = await this.db
1746
1771
  .selectFrom("device_instances")
1747
1772
  .selectAll()
@@ -1798,6 +1823,8 @@ let SandboxService = class SandboxService {
1798
1823
  let n = 0;
1799
1824
  await inPool(await this.candidates(mine), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
1800
1825
  const done = await this.tryLocked(id, async (lease) => {
1826
+ // org-filter: deployment-wide destruction sweep (worker) over every org's due instances,
1827
+ // re-read under each device's lease
1801
1828
  const row = await this.db
1802
1829
  .selectFrom("device_instances")
1803
1830
  .selectAll()
@@ -1825,6 +1852,8 @@ let SandboxService = class SandboxService {
1825
1852
  * abandoned instead ({@link abandonInstance}) and the call returns (#675). The provider only
1826
1853
  * needs to be loaded: a device is deleted while its org has the provider off too.
1827
1854
  */
1855
+ // org-filter: deviceId is the payload of the kernel's sandbox-destroy-for job, owed by the
1856
+ // transaction that soft-deleted the device in its org; never caller input
1828
1857
  async destroyDevice(deviceId) {
1829
1858
  const row = await this.db
1830
1859
  .selectFrom("device_instances")
@@ -1894,6 +1923,7 @@ let SandboxService = class SandboxService {
1894
1923
  * nothing retries the row; a plugin of that name installed again destroys it as before.
1895
1924
  */
1896
1925
  async abandonInstance(deviceId, provider) {
1926
+ // org-filter: only from destroyDevice: the kernel destroy job's device, not caller input
1897
1927
  const written = await this.db
1898
1928
  .with("a", (db) => db
1899
1929
  .updateTable("device_instances")
@@ -1948,6 +1978,8 @@ let SandboxService = class SandboxService {
1948
1978
  const p = await this.loadedFor(deviceId);
1949
1979
  const lease = await this.leases.acquireExclusive(deviceId, AbortSignal.timeout(EXCLUSIVE_WAIT_MS), undefined, { intent: true });
1950
1980
  try {
1981
+ // org-filter: deviceId is the payload of the kernel's sandbox-reset-files job (enqueued after
1982
+ // the org-checked device request), not caller input
1951
1983
  const row = await this.db
1952
1984
  .selectFrom("device_instances")
1953
1985
  .selectAll()
@@ -1959,8 +1991,10 @@ let SandboxService = class SandboxService {
1959
1991
  throw deviceInstanceForeign(p.plugin, row.provider);
1960
1992
  }
1961
1993
  const fence = { gen: row.generation };
1994
+ // the fenced increment first: the provider calls carry this holder's own token (§3.2)
1995
+ await this.fenced(lease, deviceId, fence, {});
1962
1996
  const signal = opSignal(lease);
1963
- const prev = await this.destroyInstance(row, p, signal);
1997
+ const prev = await this.destroyInstance(row, p, signal, lease, fence);
1964
1998
  await this.destroyFiles(row, p, signal);
1965
1999
  if (!(await lease.renew()))
1966
2000
  throw new SandboxLockLostError(deviceId);
@@ -1998,6 +2032,8 @@ let SandboxService = class SandboxService {
1998
2032
  if (!lease)
1999
2033
  return "busy";
2000
2034
  try {
2035
+ // org-filter: deviceId comes from the deployment-wide retire-legacy-tasks worker's due list,
2036
+ // not caller input
2001
2037
  const row = await this.db
2002
2038
  .selectFrom("device_instances")
2003
2039
  .selectAll()
@@ -2037,6 +2073,8 @@ let SandboxService = class SandboxService {
2037
2073
  if (!lease)
2038
2074
  return "busy";
2039
2075
  try {
2076
+ // org-filter: reads the device's own org; deviceId comes from the deployment-wide reconcile
2077
+ // sweep, not caller input
2040
2078
  const device = await this.db
2041
2079
  .selectFrom("devices")
2042
2080
  .select(["org_id", "provider"])
@@ -2049,6 +2087,7 @@ let SandboxService = class SandboxService {
2049
2087
  .selectFrom("device_instances")
2050
2088
  .selectAll()
2051
2089
  .where("device_id", "=", deviceId)
2090
+ .where("org_id", "=", orgId)
2052
2091
  .executeTakeFirst();
2053
2092
  const fence = row ? { gen: row.generation } : null;
2054
2093
  if (row && fence)
@@ -2080,7 +2119,17 @@ let SandboxService = class SandboxService {
2080
2119
  const sig = AbortSignal.any([signal, opSignal(lease)]);
2081
2120
  const facts = { deviceId, provider: p.plugin, to: before.target };
2082
2121
  const suspended = row.status === "suspended";
2122
+ // the intent first (device update fencing design §7.2): an update this holder never hears
2123
+ // back from is applied again by the next exclusive use
2124
+ const rec = readInstanceLimits(row.instance_limits);
2125
+ await this.fenced(lease, deviceId, fence, {
2126
+ instance_limits: instanceLimitsJson(rec.applied, rec.unapplied ?? undefined, appliedOf(want)),
2127
+ });
2083
2128
  let answer;
2129
+ // whether the provider answered without applying (nothing in flight): the intent goes again
2130
+ let settled = false;
2131
+ // a stale holder leaves the instance as it is (a newer holder may use it)
2132
+ let stale = false;
2084
2133
  try {
2085
2134
  if (suspended && (await p.impl.resume(handle, sig)) === "gone")
2086
2135
  answer = "gone";
@@ -2089,10 +2138,16 @@ let SandboxService = class SandboxService {
2089
2138
  // suspended: a failure is revoked again on the next resume)
2090
2139
  if (suspended)
2091
2140
  await this.revokeIncarnation(deviceId, { provider: p.plugin, generation: String(row.created_at.getTime()) }, handle, p, sig, false);
2092
- answer = await update(handle, providerLimits(want), sig);
2141
+ answer = await update(handle, providerLimits(want), sig, { token: fence.gen });
2093
2142
  }
2143
+ settled = answer !== "updated";
2094
2144
  }
2095
2145
  catch (err) {
2146
+ // a newer holder applied a higher token: this one is stale (never recorded, §7.1)
2147
+ if (isStaleFenceError(err)) {
2148
+ stale = true;
2149
+ throw await this.staleHolder(lease, deviceId, p.plugin, fence, "update", err);
2150
+ }
2096
2151
  if (sig.aborted)
2097
2152
  throw err;
2098
2153
  this.log.warn("cannot apply the reconcile limits to the sandbox instance", {
@@ -2102,11 +2157,18 @@ let SandboxService = class SandboxService {
2102
2157
  answer = "recreate";
2103
2158
  }
2104
2159
  finally {
2105
- if (suspended)
2160
+ if (suspended && !stale)
2106
2161
  await this.bestEffort(deviceId, "suspend the instance again after a limits update", (s) => p.impl.suspend(handle, s));
2107
2162
  }
2108
- if (answer !== "updated")
2163
+ if (answer !== "updated") {
2164
+ // the provider answered and changed nothing: the record goes back to what it was; a
2165
+ // failed update keeps the intent for the next use
2166
+ if (settled && (await lease.renew()))
2167
+ await this.fenced(lease, deviceId, fence, {
2168
+ instance_limits: instanceLimitsJson(rec.applied, rec.unapplied ?? undefined, rec.pending ?? undefined),
2169
+ });
2109
2170
  return before;
2171
+ }
2110
2172
  if (!(await lease.renew()))
2111
2173
  throw new SandboxLockLostError(deviceId);
2112
2174
  await this.fenced(lease, deviceId, fence, {
@@ -2143,6 +2205,8 @@ let SandboxService = class SandboxService {
2143
2205
  /** {@link reconcileMarked} for the devices of one provider. */
2144
2206
  async reconcileMarkedOf(p, limit) {
2145
2207
  const cursorKey = reconcileCursorKey(p.plugin);
2208
+ // org-filter: deployment-wide reconcile sweep (worker) over every org's marked devices of
2209
+ // this provider
2146
2210
  const page = (after, n) => this.db
2147
2211
  .selectFrom("devices as d")
2148
2212
  .innerJoin("device_instances as i", "i.device_id", "d.id")
@@ -2268,6 +2332,7 @@ let SandboxService = class SandboxService {
2268
2332
  "execution_ref",
2269
2333
  ])
2270
2334
  .where("operation_id", "=", m.refId)
2335
+ .where("org_id", "=", o.orgId)
2271
2336
  .where("device_id", "=", id)
2272
2337
  .executeTakeFirst();
2273
2338
  if (intent?.revoke_acknowledged === true)
@@ -2350,11 +2415,13 @@ let SandboxService = class SandboxService {
2350
2415
  opSignal(held),
2351
2416
  AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2352
2417
  ...(signal ? [signal] : []),
2353
- ]));
2418
+ ]), tokenOf(fence));
2354
2419
  }
2355
2420
  catch (err) {
2356
2421
  if (held.signal.aborted || signal?.aborted)
2357
2422
  throw err;
2423
+ if (isStaleFenceError(err) && fence)
2424
+ throw await this.staleHolder(held, id, provider, fence, "destroy", err);
2358
2425
  await this.retirement.noteFailure(o.id, err);
2359
2426
  this.log.warn("cannot destroy an instance that may run legacy work; device unavailable", {
2360
2427
  deviceId: id,
@@ -2375,6 +2442,8 @@ let SandboxService = class SandboxService {
2375
2442
  sweep_failed_at: null,
2376
2443
  });
2377
2444
  this.log.info("instance that may run legacy work destroyed", { deviceId: id });
2445
+ // org-filter: the device this retirement gate holds under its exclusive lease; the instance
2446
+ // row is keyed by its device
2378
2447
  now = await this.db
2379
2448
  .selectFrom("device_instances")
2380
2449
  .selectAll()
@@ -2401,11 +2470,13 @@ let SandboxService = class SandboxService {
2401
2470
  opSignal(held),
2402
2471
  AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2403
2472
  ...(signal ? [signal] : []),
2404
- ]));
2473
+ ]), tokenOf(fence));
2405
2474
  }
2406
2475
  catch (err) {
2407
2476
  if (held.signal.aborted || signal?.aborted)
2408
2477
  throw err;
2478
+ if (isStaleFenceError(err) && fence)
2479
+ throw await this.staleHolder(held, id, provider, fence, "destroy", err);
2409
2480
  await this.retirement.noteFailure(o.id, err);
2410
2481
  this.log.warn("cannot destroy by name an instance that may run legacy work", {
2411
2482
  deviceId: id,
@@ -2425,6 +2496,8 @@ let SandboxService = class SandboxService {
2425
2496
  sweep_failed_at: null,
2426
2497
  });
2427
2498
  this.log.info("instance that may run legacy work destroyed by name", { deviceId: id });
2499
+ // org-filter: the device this retirement gate holds under its exclusive lease; the instance
2500
+ // row is keyed by its device
2428
2501
  now = await this.db
2429
2502
  .selectFrom("device_instances")
2430
2503
  .selectAll()
@@ -2552,13 +2625,18 @@ let SandboxService = class SandboxService {
2552
2625
  async fenced(lease, id, fence, set) {
2553
2626
  if (lease.signal.aborted)
2554
2627
  throw new SandboxLockLostError(id);
2555
- const r = await this.db
2628
+ // committed on its own, never inside a caller's transaction: the generation it writes is the
2629
+ // token the next provider call carries, which every replica must see before that call (device
2630
+ // update fencing design §3.2)
2631
+ // org-filter: fenced write on the device this holder leases (entered after the org check, or a
2632
+ // sweep's device); the fence generation guards it
2633
+ const r = await runOutsideTransaction(() => this.db
2556
2634
  .updateTable("device_instances")
2557
2635
  .set({ ...set, generation: fence.gen + 1 })
2558
2636
  .where("device_id", "=", id)
2559
2637
  .where("generation", "=", fence.gen)
2560
2638
  .returning("created_at")
2561
- .executeTakeFirst();
2639
+ .executeTakeFirst());
2562
2640
  if (!r)
2563
2641
  throw new SandboxLockLostError(id, "generation");
2564
2642
  fence.gen++;
@@ -2566,6 +2644,8 @@ let SandboxService = class SandboxService {
2566
2644
  }
2567
2645
  /** Sweep candidates: those whose last sweep failed come last, the rest least recently used first. */
2568
2646
  async candidates(due) {
2647
+ // org-filter: deployment-wide sweep candidates (suspension and destruction workers) across
2648
+ // every org
2569
2649
  return await this.db
2570
2650
  .selectFrom("device_instances")
2571
2651
  .select(["device_id", "running_since"])
@@ -2606,6 +2686,8 @@ let SandboxService = class SandboxService {
2606
2686
  }
2607
2687
  catch (err) {
2608
2688
  this.log.warn("sandbox maintenance failed; will retry", { deviceId, err });
2689
+ // org-filter: sweep bookkeeping on the device this deployment-wide sweep holds under its
2690
+ // lease
2609
2691
  await this.db
2610
2692
  .updateTable("device_instances")
2611
2693
  .set({ sweep_failed_at: sql `now()` })
@@ -2654,6 +2736,8 @@ let SandboxService = class SandboxService {
2654
2736
  .executeTakeFirst();
2655
2737
  if (!live)
2656
2738
  throw deviceNotFound();
2739
+ // org-filter: reads org_id and throws foreign below (the device itself was just checked in
2740
+ // ctx.orgId)
2657
2741
  const read = await this.db
2658
2742
  .selectFrom("device_instances")
2659
2743
  .selectAll()
@@ -2710,6 +2794,10 @@ let SandboxService = class SandboxService {
2710
2794
  created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want);
2711
2795
  }
2712
2796
  catch (err) {
2797
+ // refused as stale: the provider changed nothing, and the instance (the same
2798
+ // incarnation after an in-place update) may already run a newer holder's work
2799
+ if (err instanceof SandboxLockLostError && err.reason === "generation")
2800
+ throw err;
2713
2801
  // the work a pause brought back is revoked exactly, never killed broadly; the row
2714
2802
  // still says suspended, so the next use resumes and revokes again
2715
2803
  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", {
@@ -2837,9 +2925,12 @@ let SandboxService = class SandboxService {
2837
2925
  limits,
2838
2926
  fileSystem: fs,
2839
2927
  signal,
2928
+ fence: { token: fence.gen },
2840
2929
  });
2841
2930
  }
2842
2931
  catch (err) {
2932
+ if (isStaleFenceError(err))
2933
+ throw await this.staleHolder(held, id, p.plugin, fence, "create", err);
2843
2934
  if (!isFileSystemGoneError(err)) {
2844
2935
  throw providerRefusal(this.log, err, { deviceId: id, provider: p.plugin, op: "create" }, limits, signal);
2845
2936
  }
@@ -2879,7 +2970,9 @@ let SandboxService = class SandboxService {
2879
2970
  // (Ruling M10) may then hit the one the new holder just resumed or created; that heals:
2880
2971
  // its next provider call throws SandboxGoneError (or resume returns gone) and the use
2881
2972
  // rebuilds in place. The file system is never touched here.
2882
- await p.impl.destroy(handle, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)).catch((err) => this.log.warn("cannot destroy sandbox created after the lock was lost", {
2973
+ await p.impl
2974
+ .destroy(handle, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS), tokenOf(fence))
2975
+ .catch((err) => this.log.warn("cannot destroy sandbox created after the lock was lost", {
2883
2976
  deviceId: id,
2884
2977
  err,
2885
2978
  }));
@@ -2905,24 +2998,34 @@ let SandboxService = class SandboxService {
2905
2998
  async applyLimits(ctx, p, held, row, handle, fence, signal, want) {
2906
2999
  const id = ctx.deviceId;
2907
3000
  const target = appliedOf(want);
2908
- const was = readInstanceLimits(row.instance_limits).applied;
3001
+ const rec = readInstanceLimits(row.instance_limits);
3002
+ const was = rec.applied;
2909
3003
  const facts = { deviceId: id, provider: p.plugin, from: was, to: target };
2910
3004
  let gone = false;
2911
3005
  if (p.impl.update) {
3006
+ // the intent first (device update fencing design §7.2): should this holder stop hearing
3007
+ // from the provider (a lost lease, a crash), the next exclusive holder applies the desired
3008
+ // limits again with its higher token, even when the record of what succeeded matches them
3009
+ await this.fenced(held, id, fence, {
3010
+ instance_limits: instanceLimitsJson(was, rec.unapplied ?? undefined, target),
3011
+ });
3012
+ let answer;
2912
3013
  try {
2913
- if ((await p.impl.update(handle, providerLimits(want), signal)) === "updated") {
2914
- await this.fenced(held, id, fence, { instance_limits: instanceLimitsJson(target) });
2915
- this.log.info("sandbox instance limits updated", facts);
2916
- return null;
2917
- }
3014
+ answer = await p.impl.update(handle, providerLimits(want), signal, { token: fence.gen });
2918
3015
  }
2919
3016
  catch (err) {
3017
+ // a newer holder already changed the instance: this one is stale and must neither record
3018
+ // nor recreate (a recreate by a stale holder is what the fence exists to stop)
3019
+ if (isStaleFenceError(err))
3020
+ throw await this.staleHolder(held, id, p.plugin, fence, "update", err);
2920
3021
  if (isSandboxGoneError(err)) {
2921
3022
  gone = true;
2922
3023
  }
2923
3024
  else if (signal.aborted || p.impl.limitsApplyAt === "fileSystem") {
2924
3025
  // the instance may run with half-applied limits and cannot be recreated here: stop it,
2925
- // so the next use resumes it and applies them again
3026
+ // so the next use resumes it and applies them again (also after a lost lease: stopping
3027
+ // a possibly half-widened instance fails closed, at worst it pauses a newer holder's
3028
+ // work, which auto-starts on its next call; the intent makes it apply again)
2926
3029
  await this.quarantine(held, id, handle, p, fence, {
2927
3030
  provider: p.plugin,
2928
3031
  generation: String(row.created_at.getTime()),
@@ -2938,6 +3041,13 @@ let SandboxService = class SandboxService {
2938
3041
  });
2939
3042
  }
2940
3043
  }
3044
+ // outside the try: a failed record write is a lost lease, never a reason to recreate (a
3045
+ // holder whose fence moved must not destroy the instance a newer holder is using)
3046
+ if (answer === "updated") {
3047
+ await this.fenced(held, id, fence, { instance_limits: instanceLimitsJson(target) });
3048
+ this.log.info("sandbox instance limits updated", facts);
3049
+ return null;
3050
+ }
2941
3051
  }
2942
3052
  if (p.impl.limitsApplyAt === "fileSystem" && !gone) {
2943
3053
  await this.fenced(held, id, fence, { instance_limits: instanceLimitsJson(was, target) });
@@ -2945,11 +3055,16 @@ let SandboxService = class SandboxService {
2945
3055
  return null;
2946
3056
  }
2947
3057
  this.log.info("sandbox limits changed; recreating the instance on the kept files", facts);
3058
+ // still the holder (a fenced write), so a holder whose lease ended meanwhile never destroys
3059
+ // what a newer one uses; the destroy's token is then this holder's latest
3060
+ await this.fenced(held, id, fence, {});
2948
3061
  if (!gone) {
2949
3062
  try {
2950
- await p.impl.destroy(handle, signal);
3063
+ await p.impl.destroy(handle, signal, { token: fence.gen });
2951
3064
  }
2952
3065
  catch (err) {
3066
+ if (isStaleFenceError(err))
3067
+ throw await this.staleHolder(held, id, p.plugin, fence, "destroy", err);
2953
3068
  // `create` replaces an instance of the same name anyway
2954
3069
  if (signal.aborted)
2955
3070
  throw err;
@@ -2987,6 +3102,41 @@ let SandboxService = class SandboxService {
2987
3102
  });
2988
3103
  }
2989
3104
  }
3105
+ /**
3106
+ * A provider refused a lifecycle call with `StaleFenceError` (device update fencing design
3107
+ * §7.1). Normally another holder took the device and applied a higher token, so this holder's
3108
+ * lease is gone: a fenced no-op write fails and the lock-lost error its next write would raise
3109
+ * is returned. Should the write succeed, the provider holds a token ahead of the device record
3110
+ * (a restored database, a provider fault): the row's generation is raised past it (fenced), so
3111
+ * the next holder's token wins and the device heals at its next use instead of refusing forever;
3112
+ * this use still fails as lock-lost.
3113
+ */
3114
+ async staleHolder(held, id, provider, fence, op, err) {
3115
+ const current = isStaleFenceError(err) ? err.current : undefined;
3116
+ const facts = { deviceId: id, provider, op, token: fence.gen, current };
3117
+ try {
3118
+ await this.fenced(held, id, fence, {});
3119
+ }
3120
+ catch {
3121
+ this.log.warn("a device provider refused a stale lifecycle call; the lease was lost", facts);
3122
+ return new SandboxLockLostError(id, "generation");
3123
+ }
3124
+ if (current !== undefined && Number.isSafeInteger(current) && current >= fence.gen) {
3125
+ // org-filter: fenced write on the device this holder leases (entered after the org check, or
3126
+ // a sweep's device); the fence generation guards it
3127
+ const raised = await runOutsideTransaction(() => this.db
3128
+ .updateTable("device_instances")
3129
+ .set({ generation: current + 1 })
3130
+ .where("device_id", "=", id)
3131
+ .where("generation", "=", fence.gen)
3132
+ .executeTakeFirst());
3133
+ if (Number(raised.numUpdatedRows) === 1)
3134
+ fence.gen = current + 1;
3135
+ }
3136
+ this.log.warn("a device provider holds a fence token ahead of the device record; generation raised so " +
3137
+ "the next use applies again", facts);
3138
+ return new SandboxLockLostError(id, "generation");
3139
+ }
2990
3140
  /** Runs `call` with its own short signal; a failure is warned and returns false. */
2991
3141
  async bestEffort(deviceId, what, call) {
2992
3142
  try {
@@ -3003,14 +3153,17 @@ let SandboxService = class SandboxService {
3003
3153
  * then) with that provider: still loaded and destroyed → false; otherwise warns and returns true
3004
3154
  * (the record must be kept).
3005
3155
  */
3006
- async retire(id, provider, handle, signal) {
3156
+ async retire(id, provider, handle, signal, fence) {
3007
3157
  const old = this.providers.forDevice(provider)?.impl;
3008
3158
  if (old) {
3009
3159
  try {
3010
- await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]));
3160
+ await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]), tokenOf(fence));
3011
3161
  return false;
3012
3162
  }
3013
3163
  catch (err) {
3164
+ // the previous provider's instance carries a higher token: this holder is stale
3165
+ if (isStaleFenceError(err))
3166
+ throw new SandboxLockLostError(id, "generation");
3014
3167
  this.log.warn("cannot destroy a sandbox instance recorded from a previous provider", {
3015
3168
  deviceId: id,
3016
3169
  provider,
@@ -3027,19 +3180,26 @@ let SandboxService = class SandboxService {
3027
3180
  * earlier kernel recorded in `prev_*`). An instance without a handle (a create that ended before
3028
3181
  * the handle was recorded) is destroyed by name. Returns the `prev_*` patch.
3029
3182
  */
3030
- async destroyInstance(row, p, signal) {
3183
+ async destroyInstance(row, p, signal, held, fence) {
3031
3184
  const id = row.device_id;
3032
3185
  assertOwnRow(row, p);
3033
3186
  let prev = {};
3034
- if (row.handle) {
3035
- await p.impl.destroy(row.handle, signal);
3187
+ try {
3188
+ if (row.handle) {
3189
+ await p.impl.destroy(row.handle, signal, tokenOf(fence));
3190
+ }
3191
+ else if (row.status === "creating") {
3192
+ // the provider may have built it already: only the name finds it
3193
+ await p.impl.destroyByName(deviceResourceName(id), signal, tokenOf(fence));
3194
+ }
3036
3195
  }
3037
- else if (row.status === "creating") {
3038
- // the provider may have built it already: only the name finds it
3039
- await p.impl.destroyByName(deviceResourceName(id), signal);
3196
+ catch (err) {
3197
+ if (isStaleFenceError(err))
3198
+ throw await this.staleHolder(held, id, p.plugin, fence, "destroy", err);
3199
+ throw err;
3040
3200
  }
3041
3201
  if (row.prev_handle && row.prev_provider) {
3042
- if (!(await this.retire(id, row.prev_provider, row.prev_handle, signal))) {
3202
+ if (!(await this.retire(id, row.prev_provider, row.prev_handle, signal, fence))) {
3043
3203
  prev = { prev_provider: null, prev_handle: null };
3044
3204
  }
3045
3205
  }
@@ -3064,8 +3224,11 @@ let SandboxService = class SandboxService {
3064
3224
  async destroyRow(row, p, held, mode) {
3065
3225
  const id = row.device_id;
3066
3226
  const fence = { gen: row.generation };
3227
+ // the fenced increment first, so the token the provider calls carry is this holder's own
3228
+ // (strictly higher than any earlier holder's, device update fencing design §3.2)
3229
+ await this.fenced(held, id, fence, {});
3067
3230
  const signal = opSignal(held);
3068
- const prev = await this.destroyInstance(row, p, signal);
3231
+ const prev = await this.destroyInstance(row, p, signal, held, fence);
3069
3232
  // the provider's destroy resolved: confirmed destruction of exactly this incarnation (8.5
3070
3233
  // evidence), the same for every provider
3071
3234
  if (row.handle && isKnownProvider(p.plugin))
@@ -3088,6 +3251,7 @@ let SandboxService = class SandboxService {
3088
3251
  const r = await this.db
3089
3252
  .deleteFrom("device_instances")
3090
3253
  .where("device_id", "=", id)
3254
+ .where("org_id", "=", row.org_id)
3091
3255
  .where("generation", "=", fence.gen)
3092
3256
  .executeTakeFirst();
3093
3257
  if (Number(r.numDeletedRows) !== 1)
@@ -3111,6 +3275,8 @@ let SandboxService = class SandboxService {
3111
3275
  }
3112
3276
  /** The device was deleted, or its org was: the instance and the files go. */
3113
3277
  deviceGone(eb) {
3278
+ // org-filter: deployment-wide sweep condition: a deleted device of any org, correlated to
3279
+ // the instance row
3114
3280
  return eb.or([
3115
3281
  eb.exists(eb
3116
3282
  .selectFrom("devices")
@@ -1,4 +1,4 @@
1
- import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
1
+ import { isFileSystemGoneError, isSandboxGoneError, isSandboxOperationOutcomeUnknownError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, isStaleFenceError, } from "@capybara-hq/plugin-sdk";
2
2
  /** Codes of a connection that was never made (node `net` / `dns`, undici). */
3
3
  const CONNECT_CODES = new Set([
4
4
  "ECONNREFUSED",
@@ -78,6 +78,9 @@ export class SandboxProviderUnreachableError extends Error {
78
78
  function converted(e) {
79
79
  if (e instanceof SandboxProviderUnreachableError)
80
80
  return e;
81
+ // a fence refusal is an answer, never a lost connection, whatever its cause chain holds
82
+ if (isStaleFenceError(e))
83
+ return e;
81
84
  const failure = providerConnectionFailure(e);
82
85
  return failure === undefined ? e : new SandboxProviderUnreachableError(failure, e);
83
86
  }
@@ -144,7 +144,7 @@ let ScheduledTaskFirer = class ScheduledTaskFirer {
144
144
  return;
145
145
  // a Redis read: outside the claim's transaction
146
146
  const offline = pre.fired_at === null && pre.device_id !== null && pre.mode === "new"
147
- ? await this.deviceOffline(pre.device_id)
147
+ ? await this.deviceOffline(pre.org_id, pre.device_id)
148
148
  : false;
149
149
  const claimed = await this.claim(taskRunId, pre.org_id, offline);
150
150
  if (claimed === null || "skip" in claimed)
@@ -440,6 +440,7 @@ let ScheduledTaskFirer = class ScheduledTaskFirer {
440
440
  .updateTable("conversations")
441
441
  .set({ scheduled_task_id: task.id })
442
442
  .where("id", "=", conv.id)
443
+ .where("org_id", "=", task.orgId)
443
444
  .execute();
444
445
  return conv.id;
445
446
  });
@@ -482,6 +483,7 @@ let ScheduledTaskFirer = class ScheduledTaskFirer {
482
483
  .updateTable("conversations")
483
484
  .set({ scheduled_task_id: task.id })
484
485
  .where("id", "=", conv.id)
486
+ .where("org_id", "=", task.orgId)
485
487
  .execute();
486
488
  await t
487
489
  .insertInto("channel_deliveries")
@@ -641,11 +643,12 @@ let ScheduledTaskFirer = class ScheduledTaskFirer {
641
643
  * connected now ({@link DialInRelay.online}). A provider not loaded here is not asked: the run's
642
644
  * own sandbox use refuses it (`device.unavailable`).
643
645
  */
644
- async deviceOffline(deviceId) {
646
+ async deviceOffline(orgId, deviceId) {
645
647
  const row = await this.db
646
648
  .selectFrom("devices")
647
649
  .select(["provider", "deleted_at"])
648
650
  .where("id", "=", deviceId)
651
+ .where("org_id", "=", orgId)
649
652
  .executeTakeFirst();
650
653
  if (!row || row.deleted_at !== null)
651
654
  return true;
@@ -677,7 +680,10 @@ __decorate([
677
680
  Transactional()
678
681
  ], ScheduledTaskFirer.prototype, "setConversation", null);
679
682
  ScheduledTaskFirer = __decorate([
680
- Injectable(),
683
+ Injectable()
684
+ // org-filter: the sched-fire / sched-settle job handler (worker only): the task run id is the
685
+ // kernel-written job payload, and every other id is read from that run's own task row
686
+ ,
681
687
  __param(0, Inject(KernelDb)),
682
688
  __param(1, Inject(TransactionHost)),
683
689
  __param(2, Inject(KernelConfigService)),
@@ -6,6 +6,8 @@ import { audit } from "../identity/audit.js";
6
6
  * already paused or ended keeps its state and reason. A plain function so the run tracker, which
7
7
  * the runtime imports, needs no service of the schedules domain.
8
8
  */
9
+ // org-filter: only kernel paths call it (fire job, run tracker, scan job, channel outbound), each
10
+ // with the task id of a task row or task run row it already holds, never a caller-supplied id
9
11
  export async function pauseTaskIn(t, taskId, reason, by) {
10
12
  const row = await t
11
13
  .updateTable("scheduled_tasks")