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

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/admin.controller.d.ts +2 -2
  3. package/dist/admin/admin.controller.js +1 -1
  4. package/dist/admin/health.service.js +5 -5
  5. package/dist/admin/overview.service.d.ts +2 -2
  6. package/dist/admin/overview.service.js +1 -1
  7. package/dist/agents/agents.module.js +4 -0
  8. package/dist/agents/agents.schemas.js +1 -0
  9. package/dist/agents/models.controller.d.ts +2 -2
  10. package/dist/agents/onboarding-checklist.d.ts +30 -0
  11. package/dist/agents/onboarding-checklist.js +176 -0
  12. package/dist/agents/readiness.controller.d.ts +1 -0
  13. package/dist/agents/readiness.controller.js +12 -2
  14. package/dist/agents/readiness.service.d.ts +5 -2
  15. package/dist/agents/readiness.service.js +14 -3
  16. package/dist/automations/automations.service.js +7 -21
  17. package/dist/automations/events/acceptance.d.ts +2 -0
  18. package/dist/automations/events/acceptance.js +14 -3
  19. package/dist/automations/events/sweep.job.d.ts +3 -36
  20. package/dist/automations/events/sweep.job.js +5 -127
  21. package/dist/automations/fire.d.ts +3 -0
  22. package/dist/automations/fire.js +18 -1
  23. package/dist/automations/grant-rules.d.ts +0 -14
  24. package/dist/automations/grant-rules.js +0 -18
  25. package/dist/automations/scan.job.js +22 -16
  26. package/dist/catalog/catalog.module.d.ts +4 -7
  27. package/dist/catalog/catalog.module.js +4 -10
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/plugin-import.js +2 -1
  30. package/dist/catalog/plugin-install.d.ts +2 -2
  31. package/dist/catalog/plugin-install.js +2 -2
  32. package/dist/catalog/template-connector-ensure.d.ts +4 -7
  33. package/dist/catalog/template-connector-ensure.js +11 -15
  34. package/dist/channels/supervisor.js +34 -23
  35. package/dist/channels/webhook.d.ts +1 -0
  36. package/dist/channels/webhook.js +10 -5
  37. package/dist/conversations/job-org.d.ts +2 -0
  38. package/dist/conversations/job-org.js +12 -0
  39. package/dist/ctx/create-ctx.js +2 -1
  40. package/dist/db/kernel-schema.d.ts +1 -0
  41. package/dist/dial-in/auth.controller.js +3 -2
  42. package/dist/dial-in/auth.service.js +3 -2
  43. package/dist/dial-in/gateway.d.ts +0 -1
  44. package/dist/dial-in/gateway.js +6 -9
  45. package/dist/extensions/host.d.ts +2 -2
  46. package/dist/extensions/host.js +22 -13
  47. package/dist/extensions/installs.d.ts +1 -0
  48. package/dist/extensions/installs.js +2 -0
  49. package/dist/html/html-document.controller.js +3 -0
  50. package/dist/html/html-document.service.js +2 -0
  51. package/dist/http/plugin-route-access.js +7 -2
  52. package/dist/identity/account-avatar.controller.js +4 -2
  53. package/dist/identity/accounts.js +19 -32
  54. package/dist/identity/api-tokens.d.ts +2 -0
  55. package/dist/identity/api-tokens.js +14 -10
  56. package/dist/identity/audit.js +10 -5
  57. package/dist/identity/binding.d.ts +1 -1
  58. package/dist/identity/binding.js +19 -10
  59. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -8
  60. package/dist/lifecycle/kernel-lifecycle.js +11 -37
  61. package/dist/models/purposes.d.ts +24 -3
  62. package/dist/models/purposes.js +131 -14
  63. package/dist/orgs/directory-sync.js +6 -4
  64. package/dist/orgs/roles.d.ts +1 -1
  65. package/dist/orgs/roles.js +1 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +1 -1
  68. package/dist/platform/ops/agents.ops.js +1 -1
  69. package/dist/platform/ops/models.ops.js +3 -3
  70. package/dist/push/fanout.d.ts +1 -0
  71. package/dist/push/fanout.js +11 -4
  72. package/dist/push/recipients.d.ts +3 -1
  73. package/dist/push/recipients.js +29 -22
  74. package/dist/runtime/maintenance.d.ts +5 -1
  75. package/dist/runtime/maintenance.js +50 -11
  76. package/dist/runtime/providers.d.ts +12 -9
  77. package/dist/runtime/providers.js +2 -23
  78. package/dist/runtime/run-orphan-check.job.d.ts +1 -0
  79. package/dist/runtime/run-orphan-check.job.js +23 -21
  80. package/dist/runtime/usage-report.d.ts +2 -1
  81. package/dist/runtime/usage-report.js +26 -4
  82. package/dist/sandbox/providers.d.ts +2 -0
  83. package/dist/sandbox/providers.js +2 -0
  84. package/dist/shares/liveness.d.ts +3 -2
  85. package/dist/shares/liveness.js +26 -11
  86. package/dist/shares/share-open.service.js +2 -0
  87. package/dist/skills/usable.d.ts +2 -0
  88. package/dist/skills/usable.js +56 -0
  89. package/dist/tools/builtins/platform.js +17 -12
  90. package/dist/tools/connector-setup.d.ts +5 -1
  91. package/dist/tools/connector-setup.js +14 -0
  92. package/dist/tools/credentials.d.ts +5 -0
  93. package/dist/tools/credentials.js +10 -0
  94. package/dist/tools/oauth/flow.d.ts +1 -0
  95. package/dist/tools/oauth/flow.js +8 -3
  96. package/dist/tools/registry.d.ts +2 -0
  97. package/dist/tools/registry.js +6 -0
  98. package/package.json +3 -3
  99. package/src/migrations/0209_onboarding_checklist.sql +5 -0
  100. package/dist/catalog/template-connector-reconcile.d.ts +0 -44
  101. package/dist/catalog/template-connector-reconcile.js +0 -114
@@ -40,7 +40,7 @@ import { readAutomationSettings } from "./effective-settings.js";
40
40
  import { acceptanceFixed, automationDisabled, automationForbidden, automationNotFound, eventSourceUnavailable, eventTypeUnknown, filterInvalid, grantNotAllowed, runNowUnsupported, targetInvalid, } from "./errors.js";
41
41
  import { TriggerSourceTimeout, withDeadline } from "./events/deadline.js";
42
42
  import { validateFilter } from "./events/guards.js";
43
- import { GIT_GRANT_SPEC_HASH, GIT_PUSH_GRANT, gitGrantRefusal, grantRefusal, grantRefusalOf, isGitGrantKey, isNetworkGrantKey, isPolicyGrantKey, isTierGrantKey, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantHost, networkGrantRefusal, normalizeGitGrantKey, tierGrantRefusal, } from "./grant-rules.js";
43
+ import { GIT_GRANT_SPEC_HASH, GIT_PUSH_GRANT, gitGrantRefusal, grantRefusal, grantRefusalOf, isGitGrantKey, isNetworkGrantKey, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantHost, networkGrantRefusal, normalizeGitGrantKey, } from "./grant-rules.js";
44
44
  import { oweAutomationFire, oweAutomationSettleUnfired } from "./job-ids.js";
45
45
  import { pauseTaskIn } from "./pause.js";
46
46
  import { jitterForGap, minGapMinutes, nextTick, validateTrigger } from "./schedule-math.js";
@@ -50,11 +50,8 @@ export { grantRefusal, grantRefusalOf, networkGrantRefusal, };
50
50
  const NETWORK_GRANT_NEEDS_PERSON = "Network domains are approved on the task page by a person.";
51
51
  /** Why a git push grant needs a person (sandbox git credentials spec §7). */
52
52
  const GIT_GRANT_NEEDS_PERSON = "Git pushes are approved on the task page by a person.";
53
- /**
54
- * A grant that belongs to no tool: a network domain, a git push or a stale sandbox-level key
55
- * (never stale, never re-resolved).
56
- */
57
- const isNonToolGrantKey = (key) => isPolicyGrantKey(key) || isGitGrantKey(key);
53
+ /** Network and Git grants have no tool definition to re-resolve. */
54
+ const isNonToolGrantKey = (key) => isNetworkGrantKey(key) || isGitGrantKey(key);
58
55
  const RUNS_DEFAULT = 50;
59
56
  const RUNS_MAX = 200;
60
57
  const DAY_MS = 86_400_000;
@@ -712,7 +709,7 @@ let AutomationsService = class AutomationsService {
712
709
  : await this.agentToolFacts(orgId, task.accountId, task.agentId);
713
710
  return grants.map((g) => ({
714
711
  ...g,
715
- // a network, git or sandbox tier grant names no tool definition: never stale
712
+ // a network or git grant names no tool definition: never stale
716
713
  stale: isNonToolGrantKey(g.toolKey)
717
714
  ? false
718
715
  : current === null
@@ -857,15 +854,14 @@ let AutomationsService = class AutomationsService {
857
854
  // a refused tool granted since drops out, unless its grant no longer matches the tool's
858
855
  // definition (stale: it would be refused again); a refused domain granted since drops out
859
856
  // while the org's network allowlist admits it (network ask-to-allow spec §8.3)
860
- // a refused git push drops out once the task holds a grant for it or for every repository;
861
- // a stale sandbox-level grant can never be granted again, so it stays missing
857
+ // a refused git push drops out once the task holds a grant for it or for every repository
862
858
  const isTool = (k) => !k.startsWith("connection:") && !isNonToolGrantKey(k);
863
859
  const facts = refused.some(isTool) ? await toolsOf(task.agentId) : null;
864
860
  const limits = refused.some(isNetworkGrantKey) ? await orgLimits() : null;
865
- const admits = (k) => !isTierGrantKey(k) && limits !== null && orgAllows(networkGrantHost(k), limits);
861
+ const admits = (k) => limits !== null && orgAllows(networkGrantHost(k), limits);
866
862
  const missing = refused.filter((k) => {
867
863
  const hash = have?.get(k);
868
- if (isPolicyGrantKey(k))
864
+ if (isNetworkGrantKey(k))
869
865
  return hash === undefined || !admits(k);
870
866
  if (isGitGrantKey(k))
871
867
  return hash === undefined && have?.get(GIT_PUSH_GRANT) === undefined;
@@ -1225,16 +1221,6 @@ let AutomationsService = class AutomationsService {
1225
1221
  out.set(toolKey, { toolKey, specHash: GIT_GRANT_SPEC_HASH, connectorId: null });
1226
1222
  }
1227
1223
  }
1228
- const tiers = grants.filter((g) => isTierGrantKey(g.toolKey));
1229
- for (const g of tiers) {
1230
- if (g.connectorId !== undefined) {
1231
- throw grantNotAllowed(`${g.toolKey} is a sandbox level and comes from no connector`);
1232
- }
1233
- // a stale tier:<...> grant from before auto mode: no tier can be granted now
1234
- const why = tierGrantRefusal(g.toolKey);
1235
- if (why !== null)
1236
- throw grantNotAllowed(why.message);
1237
- }
1238
1224
  const toolGrants = grants.filter((g) => !isNonToolGrantKey(g.toolKey));
1239
1225
  if (toolGrants.length === 0)
1240
1226
  return [...out.values()];
@@ -115,6 +115,8 @@ export declare class AcceptanceService {
115
115
  * or self-triggered) or `undelivered`.
116
116
  */
117
117
  route(ev: EventRow, ctx: RouteContext): Promise<RouteOutcome>;
118
+ /** Settle a routing refusal and owe its notice in the same transaction. */
119
+ private refuseIn;
118
120
  /** {@link route}'s writes, in one transaction under the event row's lock. */
119
121
  private routeIn;
120
122
  /**
@@ -121,7 +121,7 @@ let AcceptanceService = class AcceptanceService {
121
121
  const log = { orgId, eventId: ev.id, plugin: ev.plugin, type: ev.type };
122
122
  const refuse = (why) => {
123
123
  this.log.info(`directed trigger event undelivered: ${why}`, log);
124
- return this.settle(orgId, ev.id, "undelivered").then(() => "undelivered");
124
+ return this.refuseIn(ev, audience);
125
125
  };
126
126
  if (!ctx.decl.directed)
127
127
  return refuse("its type is not declared directed");
@@ -143,6 +143,13 @@ let AcceptanceService = class AcceptanceService {
143
143
  const mode = await this.modeFor(orgId, audience.accountId, ev.plugin, ctx.settings);
144
144
  return this.routeIn(ev, mode, ctx);
145
145
  }
146
+ /** Settle a routing refusal and owe its notice in the same transaction. */
147
+ async refuseIn(ev, audience) {
148
+ if (!(await this.settle(ev.org_id, ev.id, "undelivered")))
149
+ return "skipped";
150
+ await this.oweDeclined(ev, audience, "undelivered");
151
+ return "undelivered";
152
+ }
146
153
  /** {@link route}'s writes, in one transaction under the event row's lock. */
147
154
  async routeIn(ev, mode, ctx) {
148
155
  const db = this.kdb.db;
@@ -393,13 +400,14 @@ let AcceptanceService = class AcceptanceService {
393
400
  return row?.name ?? "";
394
401
  }
395
402
  async settle(orgId, eventId, state) {
396
- await this.kdb.db
403
+ const result = await this.kdb.db
397
404
  .updateTable("trigger_events")
398
405
  .set({ state })
399
406
  .where("org_id", "=", orgId)
400
407
  .where("id", "=", eventId)
401
408
  .where("state", "=", "pending")
402
- .execute();
409
+ .executeTakeFirst();
410
+ return result.numUpdatedRows > 0n;
403
411
  }
404
412
  /**
405
413
  * The caller's rules (`GET automations/acceptance`): each trigger source that serves the org
@@ -784,6 +792,9 @@ let AcceptanceService = class AcceptanceService {
784
792
  return row;
785
793
  }
786
794
  };
795
+ __decorate([
796
+ Transactional()
797
+ ], AcceptanceService.prototype, "refuseIn", null);
787
798
  __decorate([
788
799
  Transactional()
789
800
  ], AcceptanceService.prototype, "routeIn", null);
@@ -10,12 +10,6 @@ import { AcceptanceService } from "./acceptance.js";
10
10
  * logs it once and stops).
11
11
  */
12
12
  export declare const WINDOW_GIVE_UP_MS = 86400000;
13
- /**
14
- * A directed event still `pending` this long after it was stored was passed over by a dispatch
15
- * job (a worker from before acceptance routing, during a rolling deploy): the sweep owes it a
16
- * dispatch job again.
17
- */
18
- export declare const PENDING_DIRECTED_STALE_MS: number;
19
13
  /**
20
14
  * What the sweep does at `nowMs` for a lost pair whose newest waiting delivery is `ageMs` old:
21
15
  * `owe` its job (every sweep for the first hour, then at sweeps on boundaries of a period that
@@ -38,9 +32,8 @@ export declare function reoweDecision(ageMs: number, nowMs: number): "owe" | "wa
38
32
  * `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run and with
39
33
  * no open work offer, is deleted with its deliveries (the foreign key cascades), in batches of
40
34
  * {@link DELETE_BATCH}, one transaction each. A `pending` event (its dispatch has not settled
41
- * it) stays, until the pending-directed rule below ends it. A run keeps its `trigger_key` and a
42
- * kernel run its `trigger_event_id` (neither has a foreign key); a chain whose event is gone
43
- * restarts at depth 0.
35
+ * it) stays. A run keeps its `trigger_key` and a kernel run its `trigger_event_id` (neither
36
+ * has a foreign key). A chain whose event is gone restarts at depth 0.
44
37
  * - **Lost windows.** The dispatcher owes one coalesce job per window, from the delivery that opens
45
38
  * it (`<coalesceJobIdOfKey>-<eventId>`, due `coalesceSeconds` on). A pair whose newest waiting
46
39
  * delivery has waited longer than the org's `coalesceSeconds` plus {@link COALESCE_STALE_MS}
@@ -53,13 +46,6 @@ export declare function reoweDecision(ageMs: number, nowMs: number): "owe" | "wa
53
46
  * The age is the newest window's, never the oldest's: an old window given up on does not stop a
54
47
  * newer window of the pair that lost its job from being owed one (its flush takes both). The
55
48
  * flush is idempotent, so a duplicate finds nothing waiting.
56
- * - **Pending directed events.** A directed event still `pending` more than
57
- * {@link PENDING_DIRECTED_STALE_MS} after it was stored (a dispatch job of a worker from before
58
- * acceptance routing passed it over) is owed its dispatch job again
59
- * (`trigger-dispatch-<eventId>-sweep-<minute>`) unless one is pending in the outbox, backing off
60
- * by its age as a lost window does and giving up after {@link WINDOW_GIVE_UP_MS}: past it the
61
- * event is marked `undelivered` with a warning, so retention can delete it, and its source is
62
- * told `run.lifecycle` `offer_declined` with reason `undelivered` in the same transaction.
63
49
  * - **Cause handles.** Expired `trigger_cause_handles` (`ctx.triggers.causeOf`) are deleted.
64
50
  * - **Inbox items.** An inbox item resolved, or past its expiry, more than `inbox.retentionDays`
65
51
  * ago is deleted (an open item past its expiry already left the inbox).
@@ -76,8 +62,7 @@ export declare class TriggerEventSweepJob {
76
62
  sweep(): Promise<void>;
77
63
  /**
78
64
  * One sweep as of `now` (tests pass their own): how many offers it expired, events it deleted,
79
- * windows it owed, cause handles and inbox items it deleted, and stale pending directed events
80
- * it owed a dispatch again.
65
+ * windows it owed, and cause handles and inbox items it deleted.
81
66
  */
82
67
  sweepAt(now: Date): Promise<{
83
68
  expiredOffers: number;
@@ -85,7 +70,6 @@ export declare class TriggerEventSweepJob {
85
70
  owed: number;
86
71
  handles: number;
87
72
  inboxItems: number;
88
- redispatched: number;
89
73
  }>;
90
74
  /** Runs `batch` (one transaction each) until it deletes fewer than a full batch; the total. */
91
75
  private inBatches;
@@ -110,23 +94,6 @@ export declare class TriggerEventSweepJob {
110
94
  * on before).
111
95
  */
112
96
  private waitingWindows;
113
- /**
114
- * Directed events still `pending` more than {@link PENDING_DIRECTED_STALE_MS} after they were
115
- * stored, oldest first, at most {@link MAX_PENDING_DIRECTED}; no upper bound on age: one past
116
- * {@link WINDOW_GIVE_UP_MS} is marked `undelivered` by the sweep and so leaves this list.
117
- */
118
- private stalePendingDirected;
119
- /**
120
- * Marks a directed event that is still pending `undelivered` and tells its source
121
- * (`run.lifecycle` `offer_declined`, reason `undelivered`) in the same transaction; true when it
122
- * was pending.
123
- */
124
- private giveUpPending;
125
- /**
126
- * Owes the event's dispatch job again unless a dispatch row of it is still pending in the
127
- * outbox; true when it owed one.
128
- */
129
- private oweDispatch;
130
97
  /**
131
98
  * Owes the window's coalesce job unless an outbox row of the pair (the dispatcher's for any of
132
99
  * its windows, or an earlier sweep's) is still pending; true when it owed one.
@@ -9,7 +9,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
- import { oweOfferDeclinedIn } from "../../extensions/run-lifecycle-owe.js";
13
12
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
14
13
  import { KernelDb } from "../../infra/database/kernel-db.js";
15
14
  import { asPlatform, withOrgScope } from "../../infra/database/org-scope.js";
@@ -21,7 +20,7 @@ import { LockedCron } from "../../infra/schedule/locked-cron.decorator.js";
21
20
  import { KERNEL_LOGGER } from "../../infra/tokens.js";
22
21
  import { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
23
22
  import { readAutomationSettings } from "../effective-settings.js";
24
- import { AUTOMATION_COALESCE_JOB, TRIGGER_DISPATCH_JOB, TRIGGER_EVENT_SWEEP_JOB, triggerDispatchJobId, } from "../job-ids.js";
23
+ import { AUTOMATION_COALESCE_JOB, TRIGGER_EVENT_SWEEP_JOB, } from "../job-ids.js";
25
24
  import { AcceptanceService, OFFER_TTL_SECONDS } from "./acceptance.js";
26
25
  import { COALESCE_STALE_MS, coalesceJobIdOfKey } from "./guards.js";
27
26
  const DAY_MS = 86_400_000;
@@ -39,14 +38,6 @@ const DELETE_BATCH = 500;
39
38
  const MAX_BATCHES = 40;
40
39
  /** Waiting windows looked at per sweep. */
41
40
  const MAX_WINDOWS = 1000;
42
- /**
43
- * A directed event still `pending` this long after it was stored was passed over by a dispatch
44
- * job (a worker from before acceptance routing, during a rolling deploy): the sweep owes it a
45
- * dispatch job again.
46
- */
47
- export const PENDING_DIRECTED_STALE_MS = 10 * 60_000;
48
- /** Stale pending directed events looked at per sweep. */
49
- const MAX_PENDING_DIRECTED = 1000;
50
41
  /** Stale open work offers expired per sweep; what is left waits for the next one. */
51
42
  const MAX_STALE_OFFERS = 1000;
52
43
  /**
@@ -76,9 +67,8 @@ export function reoweDecision(ageMs, nowMs) {
76
67
  * `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run and with
77
68
  * no open work offer, is deleted with its deliveries (the foreign key cascades), in batches of
78
69
  * {@link DELETE_BATCH}, one transaction each. A `pending` event (its dispatch has not settled
79
- * it) stays, until the pending-directed rule below ends it. A run keeps its `trigger_key` and a
80
- * kernel run its `trigger_event_id` (neither has a foreign key); a chain whose event is gone
81
- * restarts at depth 0.
70
+ * it) stays. A run keeps its `trigger_key` and a kernel run its `trigger_event_id` (neither
71
+ * has a foreign key). A chain whose event is gone restarts at depth 0.
82
72
  * - **Lost windows.** The dispatcher owes one coalesce job per window, from the delivery that opens
83
73
  * it (`<coalesceJobIdOfKey>-<eventId>`, due `coalesceSeconds` on). A pair whose newest waiting
84
74
  * delivery has waited longer than the org's `coalesceSeconds` plus {@link COALESCE_STALE_MS}
@@ -91,13 +81,6 @@ export function reoweDecision(ageMs, nowMs) {
91
81
  * The age is the newest window's, never the oldest's: an old window given up on does not stop a
92
82
  * newer window of the pair that lost its job from being owed one (its flush takes both). The
93
83
  * flush is idempotent, so a duplicate finds nothing waiting.
94
- * - **Pending directed events.** A directed event still `pending` more than
95
- * {@link PENDING_DIRECTED_STALE_MS} after it was stored (a dispatch job of a worker from before
96
- * acceptance routing passed it over) is owed its dispatch job again
97
- * (`trigger-dispatch-<eventId>-sweep-<minute>`) unless one is pending in the outbox, backing off
98
- * by its age as a lost window does and giving up after {@link WINDOW_GIVE_UP_MS}: past it the
99
- * event is marked `undelivered` with a warning, so retention can delete it, and its source is
100
- * told `run.lifecycle` `offer_declined` with reason `undelivered` in the same transaction.
101
84
  * - **Cause handles.** Expired `trigger_cause_handles` (`ctx.triggers.causeOf`) are deleted.
102
85
  * - **Inbox items.** An inbox item resolved, or past its expiry, more than `inbox.retentionDays`
103
86
  * ago is deleted (an open item past its expiry already left the inbox).
@@ -124,8 +107,7 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
124
107
  }
125
108
  /**
126
109
  * One sweep as of `now` (tests pass their own): how many offers it expired, events it deleted,
127
- * windows it owed, cause handles and inbox items it deleted, and stale pending directed events
128
- * it owed a dispatch again.
110
+ * windows it owed, and cause handles and inbox items it deleted.
129
111
  */
130
112
  async sweepAt(now) {
131
113
  const cfg = this.config.get();
@@ -166,25 +148,7 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
166
148
  const inboxItems = await this.inBatches((b) => this.deleteInboxItems(new Date(now.getTime() - inboxDays * DAY_MS), b));
167
149
  if (inboxItems > 0)
168
150
  this.log.info("old inbox items deleted", { deleted: inboxItems, retentionDays: inboxDays });
169
- let redispatched = 0;
170
- for (const e of await this.stalePendingDirected(now)) {
171
- const decision = reoweDecision(now.getTime() - e.createdAt.getTime(), now.getTime());
172
- if (typeof decision === "object") {
173
- // a day of re-owed dispatches never settled it: end it, so retention can delete it
174
- if (await withOrgScope(e.orgId, () => this.giveUpPending(e.orgId, e.id)))
175
- this.log.warn("directed trigger event stayed pending for a day; marked undelivered", {
176
- orgId: e.orgId,
177
- eventId: e.id,
178
- pendingSince: e.createdAt.toISOString(),
179
- });
180
- continue;
181
- }
182
- if (decision !== "owe")
183
- continue;
184
- if (await withOrgScope(e.orgId, () => this.oweDispatch(e.orgId, e.id, now)))
185
- redispatched++;
186
- }
187
- return { expiredOffers, deleted, owed, handles, inboxItems, redispatched };
151
+ return { expiredOffers, deleted, owed, handles, inboxItems };
188
152
  }
189
153
  /** Runs `batch` (one transaction each) until it deletes fewer than a full batch; the total. */
190
154
  async inBatches(batch) {
@@ -315,86 +279,6 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
315
279
  }
316
280
  return out;
317
281
  }
318
- /**
319
- * Directed events still `pending` more than {@link PENDING_DIRECTED_STALE_MS} after they were
320
- * stored, oldest first, at most {@link MAX_PENDING_DIRECTED}; no upper bound on age: one past
321
- * {@link WINDOW_GIVE_UP_MS} is marked `undelivered` by the sweep and so leaves this list.
322
- */
323
- async stalePendingDirected(now) {
324
- const older = new Date(now.getTime() - PENDING_DIRECTED_STALE_MS);
325
- const rows = await asPlatform("deployment-wide stale directed trigger event sweep", () => sql `
326
- SELECT org_id, id, created_at FROM capybara.trigger_events
327
- WHERE state = 'pending' AND audience IS NOT NULL
328
- AND created_at < ${older}
329
- ORDER BY created_at
330
- LIMIT ${MAX_PENDING_DIRECTED}`.execute(this.kdb.db));
331
- return rows.rows.map((r) => ({
332
- orgId: r.org_id,
333
- id: r.id,
334
- createdAt: new Date(r.created_at),
335
- }));
336
- }
337
- /**
338
- * Marks a directed event that is still pending `undelivered` and tells its source
339
- * (`run.lifecycle` `offer_declined`, reason `undelivered`) in the same transaction; true when it
340
- * was pending.
341
- */
342
- async giveUpPending(orgId, eventId) {
343
- const db = this.kdb.db;
344
- const r = await db
345
- .updateTable("trigger_events")
346
- .set({ state: "undelivered" })
347
- .where("org_id", "=", orgId)
348
- .where("id", "=", eventId)
349
- .where("state", "=", "pending")
350
- .returning(["plugin", "dedupe_key", "audience", "subject"])
351
- .executeTakeFirst();
352
- if (r === undefined)
353
- return false;
354
- if (r.audience !== null) {
355
- await oweOfferDeclinedIn(db, this.outbox, {
356
- orgId,
357
- plugin: r.plugin,
358
- eventId,
359
- dedupeKey: r.dedupe_key,
360
- accountId: r.audience.accountId,
361
- agentId: r.audience.agentId,
362
- subject: r.subject,
363
- reason: "undelivered",
364
- });
365
- }
366
- return true;
367
- }
368
- /**
369
- * Owes the event's dispatch job again unless a dispatch row of it is still pending in the
370
- * outbox; true when it owed one.
371
- */
372
- async oweDispatch(orgId, eventId, now) {
373
- const prefix = triggerDispatchJobId(eventId);
374
- const pending = await this.kdb.db
375
- .selectFrom("outbox")
376
- .select("id")
377
- .where("org_id", "=", orgId)
378
- .where("queue", "=", MAINTENANCE_QUEUE_NAME)
379
- .where("job_name", "=", TRIGGER_DISPATCH_JOB)
380
- .where(sql `starts_with(job_id, ${prefix})`)
381
- .where("dead_at", "is", null)
382
- .limit(1)
383
- .executeTakeFirst();
384
- if (pending !== undefined)
385
- return false;
386
- this.log.warn("directed trigger event still pending; the sweep owes its dispatch again", {
387
- orgId,
388
- eventId,
389
- });
390
- return this.outbox.add({
391
- queue: MAINTENANCE_QUEUE_NAME,
392
- name: TRIGGER_DISPATCH_JOB,
393
- jobId: `${prefix}-sweep-${Math.floor(now.getTime() / 60_000)}`,
394
- data: { orgId, eventId },
395
- orgId,
396
- });
397
- }
398
282
  /**
399
283
  * Owes the window's coalesce job unless an outbox row of the pair (the dispatcher's for any of
400
284
  * its windows, or an earlier sweep's) is still pending; true when it owed one.
@@ -444,12 +328,6 @@ __decorate([
444
328
  __decorate([
445
329
  Transactional()
446
330
  ], TriggerEventSweepJob.prototype, "deleteEvents", null);
447
- __decorate([
448
- Transactional()
449
- ], TriggerEventSweepJob.prototype, "giveUpPending", null);
450
- __decorate([
451
- Transactional()
452
- ], TriggerEventSweepJob.prototype, "oweDispatch", null);
453
331
  __decorate([
454
332
  Transactional()
455
333
  ], TriggerEventSweepJob.prototype, "oweFlush", null);
@@ -76,6 +76,8 @@ export declare class AutomationFirer {
76
76
  private get db();
77
77
  /** Fires task run `taskRunId` (see the class); a run not `pending` is left as it is. */
78
78
  fire(taskRunId: string): Promise<void>;
79
+ private inTaskRunOrg;
80
+ private fireInOrg;
79
81
  /**
80
82
  * The `automation-settle` job (ruling R26; `job-ids.ts`). The claimed check: a task run claimed
81
83
  * (`fired_at`) and still `pending` goes through the run tracker's check, which links it to its
@@ -87,6 +89,7 @@ export declare class AutomationFirer {
87
89
  * since is left as it is (the claimed check follows a claimed run).
88
90
  */
89
91
  settle(data: AutomationSettleJobData): Promise<void>;
92
+ private settleInOrg;
90
93
  /** The unfired check (see {@link settle}), task row first (the one lock order). */
91
94
  private settleUnfired;
92
95
  /** Step 1 (see the class): a skip, the plan, or null when there is nothing to fire. */
@@ -23,6 +23,7 @@ import { DialInRelayModule } from "../dial-in/relay.module.js";
23
23
  import { ApiError } from "../errors.js";
24
24
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
25
25
  import { KernelDb } from "../infra/database/kernel-db.js";
26
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
26
27
  import { TransactionHost } from "../infra/database/transaction-host.js";
27
28
  import { Transactional } from "../infra/database/transactional.decorator.js";
28
29
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -142,6 +143,19 @@ let AutomationFirer = class AutomationFirer {
142
143
  }
143
144
  /** Fires task run `taskRunId` (see the class); a run not `pending` is left as it is. */
144
145
  async fire(taskRunId) {
146
+ await this.inTaskRunOrg(taskRunId, () => this.fireInOrg(taskRunId));
147
+ }
148
+ async inTaskRunOrg(taskRunId, run) {
149
+ // org-filter: deployment-wide lookup of the org owning a queued automation run
150
+ const owner = await asPlatform("resolve the owner of a queued automation run", () => this.db
151
+ .selectFrom("automation_runs")
152
+ .select("org_id")
153
+ .where("id", "=", taskRunId)
154
+ .executeTakeFirst());
155
+ if (owner)
156
+ await withOrgScope(owner.org_id, run);
157
+ }
158
+ async fireInOrg(taskRunId) {
145
159
  const pre = await this.db
146
160
  .selectFrom("automation_runs as r")
147
161
  .innerJoin("automations as t", "t.id", "r.automation_id")
@@ -170,6 +184,9 @@ let AutomationFirer = class AutomationFirer {
170
184
  * since is left as it is (the claimed check follows a claimed run).
171
185
  */
172
186
  async settle(data) {
187
+ await this.inTaskRunOrg(data.taskRunId, () => this.settleInOrg(data));
188
+ }
189
+ async settleInOrg(data) {
173
190
  const { taskRunId } = data;
174
191
  if ("unfired" in data) {
175
192
  await this.settleUnfired(taskRunId);
@@ -889,7 +906,7 @@ let AutomationFirer = class AutomationFirer {
889
906
  };
890
907
  __decorate([
891
908
  Transactional()
892
- ], AutomationFirer.prototype, "settle", null);
909
+ ], AutomationFirer.prototype, "settleInOrg", null);
893
910
  __decorate([
894
911
  Transactional()
895
912
  ], AutomationFirer.prototype, "claim", null);
@@ -93,20 +93,6 @@ export declare function gitGrantRefusal(key: string, ctx: Pick<GrantContext, "fo
93
93
  code: GrantRefusalCode;
94
94
  message: string;
95
95
  } | null;
96
- /** The prefix of a former sandbox tier grant's key (`tier:<tier>`); no such grant exists now. */
97
- export declare const TIER_GRANT_PREFIX = "tier:";
98
- /** Whether a grant key is a former sandbox tier grant (`tier:<tier>`), refused as not grantable. */
99
- export declare const isTierGrantKey: (key: string) => boolean;
100
- /** Whether a grant key names no tool: a network grant or a former tier grant. */
101
- export declare const isPolicyGrantKey: (key: string) => boolean;
102
- /**
103
- * Why `key` cannot be a task's grant: a `tier:` key is a stale sandbox-level grant from before auto
104
- * mode, and no tier can be granted now (`not_grantable`). Null for other keys.
105
- */
106
- export declare function tierGrantRefusal(key: string): {
107
- code: GrantRefusalCode;
108
- message: string;
109
- } | null;
110
96
  /**
111
97
  * Whether the org's `forbiddenTools` forbid the git push grant `key` (normalized): it lists
112
98
  * `git:push` or the key, each entry compared normalized (`git:push:Acme/App` forbids
@@ -142,24 +142,6 @@ export function gitGrantRefusal(key, ctx) {
142
142
  }
143
143
  return null;
144
144
  }
145
- /** The prefix of a former sandbox tier grant's key (`tier:<tier>`); no such grant exists now. */
146
- export const TIER_GRANT_PREFIX = "tier:";
147
- /** Whether a grant key is a former sandbox tier grant (`tier:<tier>`), refused as not grantable. */
148
- export const isTierGrantKey = (key) => key.startsWith(TIER_GRANT_PREFIX);
149
- /** Whether a grant key names no tool: a network grant or a former tier grant. */
150
- export const isPolicyGrantKey = (key) => isNetworkGrantKey(key) || isTierGrantKey(key);
151
- /**
152
- * Why `key` cannot be a task's grant: a `tier:` key is a stale sandbox-level grant from before auto
153
- * mode, and no tier can be granted now (`not_grantable`). Null for other keys.
154
- */
155
- export function tierGrantRefusal(key) {
156
- if (!isTierGrantKey(key))
157
- return null;
158
- return {
159
- code: "not_grantable",
160
- message: `${key} cannot be approved for an automation: sandbox levels are no longer task grants`,
161
- };
162
- }
163
145
  /**
164
146
  * Whether the org's `forbiddenTools` forbid the git push grant `key` (normalized): it lists
165
147
  * `git:push` or the key, each entry compared normalized (`git:push:Acme/App` forbids
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { withOrgScope } from "../infra/database/org-scope.js";
14
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
15
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
16
17
  import { LockService } from "../infra/lock/lock.service.js";
@@ -33,9 +34,11 @@ const EXPIRED = { status: "ended", pauseReason: "expired", nextRunAt: null };
33
34
  */
34
35
  class TaskScanFailed extends Error {
35
36
  taskId;
36
- constructor(taskId, cause) {
37
+ orgId;
38
+ constructor(taskId, orgId, cause) {
37
39
  super(`automation ${taskId} cannot be advanced`, { cause });
38
40
  this.taskId = taskId;
41
+ this.orgId = orgId;
39
42
  }
40
43
  }
41
44
  /**
@@ -94,7 +97,7 @@ let AutomationScanJob = class AutomationScanJob {
94
97
  taskId: err.taskId,
95
98
  err: err.cause,
96
99
  });
97
- await this.quarantine(err.taskId);
100
+ await withOrgScope(err.orgId, () => this.quarantine(err.taskId));
98
101
  }
99
102
  }
100
103
  await this.endExpiredEvents(now);
@@ -104,8 +107,9 @@ let AutomationScanJob = class AutomationScanJob {
104
107
  async endExpiredEvents(now) {
105
108
  const t = this.db;
106
109
  const expired = await this.store.lockExpiredEvent(t, now, MAX_TASKS);
107
- for (const task of expired)
108
- await this.store.updateTask(t, task.id, EXPIRED);
110
+ for (const task of expired) {
111
+ await withOrgScope(task.orgId, () => this.store.updateTask(t, task.id, EXPIRED));
112
+ }
109
113
  return expired.length;
110
114
  }
111
115
  /**
@@ -118,17 +122,19 @@ let AutomationScanJob = class AutomationScanJob {
118
122
  const [task] = await this.store.lockDue(t, now, 1);
119
123
  if (!task)
120
124
  return false;
121
- let s = settings.get(task.orgId);
122
- if (s === undefined) {
123
- s = await readAutomationSettings(t, this.config, task.orgId);
124
- settings.set(task.orgId, s);
125
- }
126
- const fired = await this.advance(t, task, now, s.catchUpWindowMinutes);
127
- if (fired !== null) {
128
- await oweAutomationFire(this.outbox, fired.id, task.orgId);
129
- await oweAutomationSettleUnfired(this.outbox, fired.id, task.orgId, fired.scheduledFor, s.catchUpWindowMinutes);
130
- }
131
- return true;
125
+ return withOrgScope(task.orgId, async () => {
126
+ let s = settings.get(task.orgId);
127
+ if (s === undefined) {
128
+ s = await readAutomationSettings(t, this.config, task.orgId);
129
+ settings.set(task.orgId, s);
130
+ }
131
+ const fired = await this.advance(t, task, now, s.catchUpWindowMinutes);
132
+ if (fired !== null) {
133
+ await oweAutomationFire(this.outbox, fired.id, task.orgId);
134
+ await oweAutomationSettleUnfired(this.outbox, fired.id, task.orgId, fired.scheduledFor, s.catchUpWindowMinutes);
135
+ }
136
+ return true;
137
+ });
132
138
  }
133
139
  /** A task the scan cannot advance stops being due: paused with `invalid_schedule`. */
134
140
  async quarantine(taskId) {
@@ -147,7 +153,7 @@ let AutomationScanJob = class AutomationScanJob {
147
153
  }, now, catchUpWindowMinutes);
148
154
  }
149
155
  catch (err) {
150
- throw new TaskScanFailed(task.id, err);
156
+ throw new TaskScanFailed(task.id, task.orgId, err);
151
157
  }
152
158
  if (step.missed !== null) {
153
159
  await this.store.insertRun(t, {
@@ -3,13 +3,10 @@ export { CatalogImportModule };
3
3
  /**
4
4
  * The plugin catalog (spec §4, §10): {@link CatalogImportModule}, catalog requests, org installs
5
5
  * with their dependencies, the platform plugin update (`PlatformPluginUpdater`) and the update to a
6
- * staged version (`PlatformImportUpdate`), the admin's scope
7
- * and disable
8
- * (`CatalogScopeService`), org admins' plugin uploads (`OrgPluginUploads`) and their own plugins (`OwnedItems`), the startup
9
- * reconciliation of template connectors (`TemplateConnectorReconciler`) and the ensure it shares
10
- * with the queued job (`TemplateConnectorEnsurer`), and the producer of the plugin scope sync
11
- * (`PluginScopeSync`; its consumer is the worker role's `PluginScopeWorkersModule`). The catalog's periodic jobs (`CatalogJobs`) are
12
- * the worker role's (`WorkerModule`).
6
+ * staged version (`PlatformImportUpdate`), scope and disable controls (`CatalogScopeService`),
7
+ * org plugin uploads (`OrgPluginUploads`), org-owned plugins (`OwnedItems`), template connector
8
+ * convergence (`TemplateConnectorEnsurer`), and the plugin scope sync producer
9
+ * (`PluginScopeSync`). The scope consumer and periodic catalog jobs run in the worker role.
13
10
  */
14
11
  export declare class CatalogModule {
15
12
  }
@@ -28,7 +28,6 @@ import { CatalogRequestsService } from "./requests.service.js";
28
28
  import { PLUGIN_SCOPE_QUEUE, PluginScopeSync } from "./scope-sync.js";
29
29
  import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
30
30
  import { TemplateConnectorsQueueModule } from "./template-connector-jobs.js";
31
- import { TemplateConnectorReconciler } from "./template-connector-reconcile.js";
32
31
  export { CatalogImportModule };
33
32
  /** The plugin scope sync's queue registration (re-exported: the admin health reads its counts). */
34
33
  const PLUGIN_SCOPE_QUEUE_MODULE = QueueModule.registerQueue(PLUGIN_SCOPE_QUEUE);
@@ -37,13 +36,10 @@ const MAINTENANCE_QUEUE_MODULE = QueueModule.registerQueue(MAINTENANCE_QUEUE_NAM
37
36
  /**
38
37
  * The plugin catalog (spec §4, §10): {@link CatalogImportModule}, catalog requests, org installs
39
38
  * with their dependencies, the platform plugin update (`PlatformPluginUpdater`) and the update to a
40
- * staged version (`PlatformImportUpdate`), the admin's scope
41
- * and disable
42
- * (`CatalogScopeService`), org admins' plugin uploads (`OrgPluginUploads`) and their own plugins (`OwnedItems`), the startup
43
- * reconciliation of template connectors (`TemplateConnectorReconciler`) and the ensure it shares
44
- * with the queued job (`TemplateConnectorEnsurer`), and the producer of the plugin scope sync
45
- * (`PluginScopeSync`; its consumer is the worker role's `PluginScopeWorkersModule`). The catalog's periodic jobs (`CatalogJobs`) are
46
- * the worker role's (`WorkerModule`).
39
+ * staged version (`PlatformImportUpdate`), scope and disable controls (`CatalogScopeService`),
40
+ * org plugin uploads (`OrgPluginUploads`), org-owned plugins (`OwnedItems`), template connector
41
+ * convergence (`TemplateConnectorEnsurer`), and the plugin scope sync producer
42
+ * (`PluginScopeSync`). The scope consumer and periodic catalog jobs run in the worker role.
47
43
  */
48
44
  let CatalogModule = class CatalogModule {
49
45
  };
@@ -82,7 +78,6 @@ CatalogModule = __decorate([
82
78
  OwnedItems,
83
79
  PlatformImportUpdate,
84
80
  TemplateConnectorEnsurer,
85
- TemplateConnectorReconciler,
86
81
  ],
87
82
  exports: [
88
83
  PLUGIN_SCOPE_QUEUE_MODULE,
@@ -101,7 +96,6 @@ CatalogModule = __decorate([
101
96
  OwnedItems,
102
97
  PlatformImportUpdate,
103
98
  TemplateConnectorEnsurer,
104
- TemplateConnectorReconciler,
105
99
  ],
106
100
  })
107
101
  ], CatalogModule);