@capybara-hq/kernel 0.1.0-rc.142 → 0.1.0-rc.143

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 (122) hide show
  1. package/dist/agents/agents.module.js +3 -0
  2. package/dist/agents/agents.service.js +1 -1
  3. package/dist/agents/org-templates.d.ts +3 -1
  4. package/dist/agents/org-templates.js +7 -3
  5. package/dist/agents/pending-connector-requests.d.ts +10 -4
  6. package/dist/agents/pending-connector-requests.js +29 -7
  7. package/dist/automations/events/acceptance.d.ts +6 -1
  8. package/dist/automations/events/acceptance.js +30 -11
  9. package/dist/catalog/catalog-import.module.js +3 -0
  10. package/dist/catalog/catalog-scope.service.d.ts +3 -1
  11. package/dist/catalog/catalog-scope.service.js +11 -7
  12. package/dist/catalog/catalog.module.js +3 -0
  13. package/dist/catalog/catalog.service.d.ts +3 -1
  14. package/dist/catalog/catalog.service.js +8 -4
  15. package/dist/catalog/component-promotion.d.ts +3 -1
  16. package/dist/catalog/component-promotion.js +7 -3
  17. package/dist/catalog/component-scope.service.d.ts +3 -1
  18. package/dist/catalog/component-scope.service.js +7 -3
  19. package/dist/catalog/enable-requests.d.ts +10 -8
  20. package/dist/catalog/enable-requests.js +40 -21
  21. package/dist/catalog/owned-items.d.ts +3 -1
  22. package/dist/catalog/owned-items.js +13 -9
  23. package/dist/catalog/platform-components.d.ts +6 -1
  24. package/dist/catalog/platform-components.js +9 -3
  25. package/dist/catalog/plugin-connectors.d.ts +8 -4
  26. package/dist/catalog/plugin-connectors.js +12 -6
  27. package/dist/catalog/plugin-import.d.ts +3 -1
  28. package/dist/catalog/plugin-import.js +14 -5
  29. package/dist/catalog/plugin-install.d.ts +3 -1
  30. package/dist/catalog/plugin-install.js +8 -4
  31. package/dist/catalog/plugin-upgrade.d.ts +3 -1
  32. package/dist/catalog/plugin-upgrade.js +8 -4
  33. package/dist/catalog/request-hints.d.ts +19 -0
  34. package/dist/catalog/request-hints.js +34 -0
  35. package/dist/catalog/request-rules.d.ts +9 -5
  36. package/dist/catalog/request-rules.js +16 -9
  37. package/dist/catalog/requests.service.d.ts +3 -1
  38. package/dist/catalog/requests.service.js +28 -9
  39. package/dist/catalog/scope-orgs.d.ts +2 -1
  40. package/dist/catalog/scope-orgs.js +2 -2
  41. package/dist/catalog/scope-sync.d.ts +3 -1
  42. package/dist/catalog/scope-sync.js +12 -2
  43. package/dist/catalog/scope-writer.d.ts +6 -3
  44. package/dist/catalog/scope-writer.js +28 -10
  45. package/dist/catalog/unshare.d.ts +3 -2
  46. package/dist/catalog/unshare.js +4 -4
  47. package/dist/config/schema.d.ts +3 -0
  48. package/dist/config/schema.js +30 -0
  49. package/dist/db/migrator.js +36 -0
  50. package/dist/extensions/admin-ops.d.ts +6 -1
  51. package/dist/extensions/admin-ops.js +17 -4
  52. package/dist/extensions/deployment-config.d.ts +6 -1
  53. package/dist/extensions/deployment-config.js +13 -2
  54. package/dist/extensions/extensions.module.js +3 -0
  55. package/dist/extensions/org-config.d.ts +3 -1
  56. package/dist/extensions/org-config.js +13 -4
  57. package/dist/extensions/org-overrides.d.ts +6 -1
  58. package/dist/extensions/org-overrides.js +13 -2
  59. package/dist/inbox/inbox-items.service.d.ts +6 -1
  60. package/dist/inbox/inbox-items.service.js +29 -10
  61. package/dist/inbox/inbox.module.js +3 -0
  62. package/dist/inbox/inbox.service.d.ts +3 -1
  63. package/dist/inbox/inbox.service.js +9 -2
  64. package/dist/inbox/org-notices.d.ts +4 -3
  65. package/dist/inbox/org-notices.js +9 -6
  66. package/dist/inbox/platform-inbox.service.d.ts +3 -1
  67. package/dist/inbox/platform-inbox.service.js +11 -3
  68. package/dist/inbox/platform-notices.d.ts +3 -2
  69. package/dist/inbox/platform-notices.js +10 -4
  70. package/dist/infra/config/kernel-config.service.js +4 -1
  71. package/dist/invalidation/audiences.d.ts +32 -0
  72. package/dist/invalidation/audiences.js +43 -0
  73. package/dist/invalidation/hints.d.ts +6 -0
  74. package/dist/invalidation/hints.js +7 -1
  75. package/dist/invalidation/invalidation-hints.d.ts +12 -1
  76. package/dist/invalidation/invalidation-hints.js +46 -5
  77. package/dist/invalidation/invalidation-hints.module.d.ts +2 -0
  78. package/dist/invalidation/invalidation-hints.module.js +4 -1
  79. package/dist/invalidation/me-stream.d.ts +1 -11
  80. package/dist/invalidation/me-stream.js +12 -41
  81. package/dist/invalidation/org-intent-bridge.d.ts +18 -0
  82. package/dist/invalidation/org-intent-bridge.js +46 -0
  83. package/dist/models/enablement.d.ts +3 -1
  84. package/dist/models/enablement.js +25 -5
  85. package/dist/orgs/offboarding.d.ts +3 -1
  86. package/dist/orgs/offboarding.js +7 -3
  87. package/dist/orgs/orgs.module.js +3 -0
  88. package/dist/orgs/orgs.service.d.ts +3 -1
  89. package/dist/orgs/orgs.service.js +7 -3
  90. package/dist/push/delivery.d.ts +3 -1
  91. package/dist/push/delivery.js +7 -3
  92. package/dist/push/push-processor.js +8 -1
  93. package/dist/runtime/stream-limit.d.ts +13 -0
  94. package/dist/runtime/stream-limit.js +40 -0
  95. package/dist/runtime/stream.controller.d.ts +2 -0
  96. package/dist/runtime/stream.controller.js +2 -0
  97. package/dist/runtime/stream.d.ts +1 -0
  98. package/dist/runtime/stream.js +15 -6
  99. package/dist/sandbox/permission-authority.module.js +6 -1
  100. package/dist/sandbox/permission-transitions.d.ts +3 -1
  101. package/dist/sandbox/permission-transitions.js +17 -2
  102. package/dist/skills/agent-skills.service.d.ts +6 -1
  103. package/dist/skills/agent-skills.service.js +12 -3
  104. package/dist/skills/changes.service.d.ts +6 -1
  105. package/dist/skills/changes.service.js +11 -3
  106. package/dist/skills/conversation-catalog.d.ts +3 -0
  107. package/dist/skills/conversation-catalog.js +2 -0
  108. package/dist/skills/skills.module.js +3 -0
  109. package/dist/skills/skills.service.d.ts +3 -1
  110. package/dist/skills/skills.service.js +8 -4
  111. package/dist/tools/approvals.service.d.ts +12 -1
  112. package/dist/tools/approvals.service.js +36 -9
  113. package/dist/tools/connectors.service.d.ts +3 -1
  114. package/dist/tools/connectors.service.js +29 -7
  115. package/dist/tools/tools.module.js +3 -0
  116. package/dist/ui/admin-ui.controller.d.ts +3 -1
  117. package/dist/ui/admin-ui.controller.js +3 -1
  118. package/dist/ui/ui-stream.d.ts +2 -0
  119. package/dist/ui/ui-stream.js +20 -6
  120. package/dist/ui/views.controller.d.ts +4 -2
  121. package/dist/ui/views.controller.js +4 -2
  122. package/package.json +1 -1
@@ -0,0 +1,32 @@
1
+ import type { OrgRole } from "../orgs/roles.js";
2
+ import { type InvalidationTopic } from "./hints.js";
3
+ import type { InvalidationHints } from "./invalidation-hints.js";
4
+ /**
5
+ * What a writer needs to publish hints (account invalidation stream spec §4): the after-commit
6
+ * publish only. Plain database functions (the request settlement, org notices) take it as a
7
+ * parameter from the Nest service that calls them, as `oweEffectWork` takes the outbox.
8
+ */
9
+ export type HintPublisher = Pick<InvalidationHints, "publishAfterCommit">;
10
+ /**
11
+ * The role topic that reaches every member at or above `role`. A guest has no role topic: an
12
+ * entry addressed to guests and up reaches members and up (guests converge on freshness).
13
+ */
14
+ export declare function roleTopicFor(orgId: string, role: OrgRole): InvalidationTopic;
15
+ /** The `inbox` audience of an approval: its `requested_for` person, else its approver role. */
16
+ export declare function approvalTopics(a: {
17
+ orgId: string;
18
+ requestedFor: string | null;
19
+ approverRole: OrgRole | null;
20
+ }): InvalidationTopic[];
21
+ /** Publishes `capabilities` to the member streams of each org in `orgIds` (one call). */
22
+ export declare function publishCapabilities(hints: HintPublisher, orgIds: Iterable<string>): void;
23
+ /**
24
+ * Publishes `capabilities` to every member stream of every org (`platform-caps`): a
25
+ * deployment-wide change whose writer computes no affected-org set. Kind only, so nothing leaks;
26
+ * such writes are rare, and the web coalesces refetches.
27
+ */
28
+ export declare function publishPlatformCapabilities(hints: HintPublisher): void;
29
+ /** Publishes `inbox` to the streams of each account in `accountIds` (one call). */
30
+ export declare function publishAccountInbox(hints: HintPublisher, accountIds: Iterable<string>): void;
31
+ /** Publishes `inbox` to the admins and owners of each org in `orgIds` (one call). */
32
+ export declare function publishOrgAdminsInbox(hints: HintPublisher, orgIds: Iterable<string>): void;
@@ -0,0 +1,43 @@
1
+ import { acctTopic, orgCapsTopic, orgRoleTopic, PLATFORM_CAPS_TOPIC, } from "./hints.js";
2
+ /**
3
+ * The role topic that reaches every member at or above `role`. A guest has no role topic: an
4
+ * entry addressed to guests and up reaches members and up (guests converge on freshness).
5
+ */
6
+ export function roleTopicFor(orgId, role) {
7
+ const r = role === "guest" ? "member" : role;
8
+ return orgRoleTopic(orgId, r);
9
+ }
10
+ /** The `inbox` audience of an approval: its `requested_for` person, else its approver role. */
11
+ export function approvalTopics(a) {
12
+ if (a.requestedFor !== null)
13
+ return [acctTopic(a.requestedFor)];
14
+ if (a.approverRole !== null)
15
+ return [roleTopicFor(a.orgId, a.approverRole)];
16
+ return [];
17
+ }
18
+ /** Publishes `capabilities` to the member streams of each org in `orgIds` (one call). */
19
+ export function publishCapabilities(hints, orgIds) {
20
+ const topics = [...new Set(orgIds)].map((o) => orgCapsTopic(o));
21
+ if (topics.length > 0)
22
+ hints.publishAfterCommit(topics, { kind: "capabilities" });
23
+ }
24
+ /**
25
+ * Publishes `capabilities` to every member stream of every org (`platform-caps`): a
26
+ * deployment-wide change whose writer computes no affected-org set. Kind only, so nothing leaks;
27
+ * such writes are rare, and the web coalesces refetches.
28
+ */
29
+ export function publishPlatformCapabilities(hints) {
30
+ hints.publishAfterCommit([PLATFORM_CAPS_TOPIC], { kind: "capabilities" });
31
+ }
32
+ /** Publishes `inbox` to the streams of each account in `accountIds` (one call). */
33
+ export function publishAccountInbox(hints, accountIds) {
34
+ const topics = [...new Set(accountIds)].map((a) => acctTopic(a));
35
+ if (topics.length > 0)
36
+ hints.publishAfterCommit(topics, { kind: "inbox" });
37
+ }
38
+ /** Publishes `inbox` to the admins and owners of each org in `orgIds` (one call). */
39
+ export function publishOrgAdminsInbox(hints, orgIds) {
40
+ const topics = [...new Set(orgIds)].map((o) => orgRoleTopic(o, "admin"));
41
+ if (topics.length > 0)
42
+ hints.publishAfterCommit(topics, { kind: "inbox" });
43
+ }
@@ -37,6 +37,12 @@ export declare function orgRoleTopic(orgId: string, role: TopicRole): Invalidati
37
37
  export declare function orgCapsTopic(orgId: string): InvalidationTopic;
38
38
  /** The topic of super admin streams. */
39
39
  export declare const PLATFORM_ADMINS_TOPIC: InvalidationTopic;
40
+ /**
41
+ * The topic of deployment-wide capability changes with no affected-org set (a platform model
42
+ * disable, a platform skill or agent template scope change, a platform extension switch): every
43
+ * member-and-up stream of every org listens, as to its org's caps topic; guests do not.
44
+ */
45
+ export declare const PLATFORM_CAPS_TOPIC: InvalidationTopic;
40
46
  /** The role topics a member with `role` listens to: every one at or below it (guest: none). */
41
47
  export declare function roleTopicRoles(role: OrgRole): TopicRole[];
42
48
  /**
@@ -46,6 +46,12 @@ export function orgCapsTopic(orgId) {
46
46
  }
47
47
  /** The topic of super admin streams. */
48
48
  export const PLATFORM_ADMINS_TOPIC = "platform-admins";
49
+ /**
50
+ * The topic of deployment-wide capability changes with no affected-org set (a platform model
51
+ * disable, a platform skill or agent template scope change, a platform extension switch): every
52
+ * member-and-up stream of every org listens, as to its org's caps topic; guests do not.
53
+ */
54
+ export const PLATFORM_CAPS_TOPIC = "platform-caps";
49
55
  /** The role topics a member with `role` listens to: every one at or below it (guest: none). */
50
56
  export function roleTopicRoles(role) {
51
57
  return TOPIC_ROLES.filter((r) => roleAtLeast(role, r));
@@ -58,7 +64,7 @@ export function streamTopics(id) {
58
64
  for (const r of roleTopicRoles(id.role))
59
65
  topics.push(orgRoleTopic(id.orgId, r));
60
66
  if (roleAtLeast(id.role, "member"))
61
- topics.push(orgCapsTopic(id.orgId));
67
+ topics.push(orgCapsTopic(id.orgId), PLATFORM_CAPS_TOPIC);
62
68
  if (id.superAdmin)
63
69
  topics.push(PLATFORM_ADMINS_TOPIC);
64
70
  return topics;
@@ -6,11 +6,20 @@ import { Hint, type InvalidationTopic } from "./hints.js";
6
6
  * after-commit side effect, never an outbox row: {@link publishAfterCommit} is what a writer calls
7
7
  * inside its transaction; a rollback publishes nothing. Topics come from the builders in
8
8
  * `hints.ts` and the row the writer already holds. A publish failure is logged and swallowed.
9
+ * Without a bus (the Redis-free CLI contexts: `openKernelCli` with `redis: false`,
10
+ * `KernelCliModule.overPool`) publishing is a no-op: nobody there holds a stream.
9
11
  */
10
12
  export declare class InvalidationHints {
11
13
  private readonly bus;
12
14
  private readonly log;
13
- constructor(bus: Pick<ExtensionContext["bus"], "publish">, log: Pick<Logger, "warn">);
15
+ /**
16
+ * The hints a live transaction owes, by kind (the topics a union): the first
17
+ * {@link publishAfterCommit} in a transaction queues the one after-commit hook that publishes
18
+ * them. Keyed weakly by the transaction's store, so an entry lives exactly as long as its
19
+ * transaction; never shared between transactions, requests or replicas.
20
+ */
21
+ private readonly owed;
22
+ constructor(bus: Pick<ExtensionContext["bus"], "publish"> | undefined, log: Pick<Logger, "warn">);
14
23
  /**
15
24
  * Publishes `hint` on every topic now. The hint is validated first (kind only: an extra field
16
25
  * throws, a programming error); bus failures are logged and never thrown.
@@ -19,6 +28,8 @@ export declare class InvalidationHints {
19
28
  /**
20
29
  * Publishes `hint` after the root transaction commits (at once outside a transaction); a
21
30
  * rollback drops it. The hint is validated now, so a bad hint fails the caller, not the hook.
31
+ * Calls in one transaction coalesce: after the commit each kind is published once on the union
32
+ * of its topics, so a bulk writer (a loop of rows) sends one hint per topic, not one per row.
22
33
  */
23
34
  publishAfterCommit(topics: readonly InvalidationTopic[], hint: Hint): void;
24
35
  }
@@ -7,8 +7,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Inject, Injectable } from "@nestjs/common";
10
+ import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { afterCommit } from "../infra/database/after-commit.js";
12
+ import { currentStore } from "../infra/database/transaction-host.js";
12
13
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
13
14
  import { Hint } from "./hints.js";
14
15
  /**
@@ -17,11 +18,22 @@ import { Hint } from "./hints.js";
17
18
  * after-commit side effect, never an outbox row: {@link publishAfterCommit} is what a writer calls
18
19
  * inside its transaction; a rollback publishes nothing. Topics come from the builders in
19
20
  * `hints.ts` and the row the writer already holds. A publish failure is logged and swallowed.
21
+ * Without a bus (the Redis-free CLI contexts: `openKernelCli` with `redis: false`,
22
+ * `KernelCliModule.overPool`) publishing is a no-op: nobody there holds a stream.
20
23
  */
21
24
  let InvalidationHints = class InvalidationHints {
22
25
  bus;
23
26
  log;
24
- constructor(bus, log) {
27
+ /**
28
+ * The hints a live transaction owes, by kind (the topics a union): the first
29
+ * {@link publishAfterCommit} in a transaction queues the one after-commit hook that publishes
30
+ * them. Keyed weakly by the transaction's store, so an entry lives exactly as long as its
31
+ * transaction; never shared between transactions, requests or replicas.
32
+ */
33
+ owed = new WeakMap();
34
+ constructor(
35
+ // Optional: the Redis-free CLI has no bus; a hint is harmless to lose, so there it is skipped
36
+ bus, log) {
25
37
  this.bus = bus;
26
38
  this.log = log;
27
39
  }
@@ -31,10 +43,13 @@ let InvalidationHints = class InvalidationHints {
31
43
  */
32
44
  async publish(topics, hint) {
33
45
  const h = Hint.parse(hint);
46
+ const bus = this.bus;
47
+ if (bus === undefined)
48
+ return;
34
49
  const unique = [...new Set(topics)];
35
50
  await Promise.all(unique.map(async (topic) => {
36
51
  try {
37
- await this.bus.publish(topic, { kind: h.kind });
52
+ await bus.publish(topic, { kind: h.kind });
38
53
  }
39
54
  catch (err) {
40
55
  this.log.warn("invalidation hint publish failed", { topic, kind: h.kind, err });
@@ -44,15 +59,41 @@ let InvalidationHints = class InvalidationHints {
44
59
  /**
45
60
  * Publishes `hint` after the root transaction commits (at once outside a transaction); a
46
61
  * rollback drops it. The hint is validated now, so a bad hint fails the caller, not the hook.
62
+ * Calls in one transaction coalesce: after the commit each kind is published once on the union
63
+ * of its topics, so a bulk writer (a loop of rows) sends one hint per topic, not one per row.
47
64
  */
48
65
  publishAfterCommit(topics, hint) {
49
66
  const h = Hint.parse(hint);
50
- const list = [...topics];
51
- afterCommit(() => this.publish(list, h));
67
+ const store = currentStore();
68
+ if (store === undefined) {
69
+ const list = [...topics];
70
+ afterCommit(() => this.publish(list, h));
71
+ return;
72
+ }
73
+ let byKind = this.owed.get(store);
74
+ if (byKind === undefined) {
75
+ const owed = new Map();
76
+ byKind = owed;
77
+ this.owed.set(store, owed);
78
+ afterCommit(async () => {
79
+ this.owed.delete(store);
80
+ // kinds in the order the transaction first owed them
81
+ for (const [kind, set] of owed)
82
+ await this.publish([...set], { kind });
83
+ });
84
+ }
85
+ let set = byKind.get(h.kind);
86
+ if (set === undefined) {
87
+ set = new Set();
88
+ byKind.set(h.kind, set);
89
+ }
90
+ for (const t of topics)
91
+ set.add(t);
52
92
  }
53
93
  };
54
94
  InvalidationHints = __decorate([
55
95
  Injectable(),
96
+ __param(0, Optional()),
56
97
  __param(0, Inject(KERNEL_BUS)),
57
98
  __param(1, Inject(KERNEL_LOGGER))
58
99
  ], InvalidationHints);
@@ -3,6 +3,8 @@
3
3
  * writers call after their commit. It needs only the global kernel bus and logger, so any module
4
4
  * may import it, whatever role runs it (api requests, worker jobs, the gateway). The topic builders
5
5
  * are plain functions in `hints.ts`. The streams that deliver hints are `MeStreamModule`'s.
6
+ * {@link OrgIntentHintsBridge} turns the in-process `catalog.org-intent-changed` event into an
7
+ * org's `capabilities` hint.
6
8
  */
7
9
  export declare class InvalidationHintsModule {
8
10
  }
@@ -6,17 +6,20 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
6
6
  };
7
7
  import { Module } from "@nestjs/common";
8
8
  import { InvalidationHints } from "./invalidation-hints.js";
9
+ import { OrgIntentHintsBridge } from "./org-intent-bridge.js";
9
10
  /**
10
11
  * Account invalidation hints (account invalidation stream spec §4): {@link InvalidationHints}, which
11
12
  * writers call after their commit. It needs only the global kernel bus and logger, so any module
12
13
  * may import it, whatever role runs it (api requests, worker jobs, the gateway). The topic builders
13
14
  * are plain functions in `hints.ts`. The streams that deliver hints are `MeStreamModule`'s.
15
+ * {@link OrgIntentHintsBridge} turns the in-process `catalog.org-intent-changed` event into an
16
+ * org's `capabilities` hint.
14
17
  */
15
18
  let InvalidationHintsModule = class InvalidationHintsModule {
16
19
  };
17
20
  InvalidationHintsModule = __decorate([
18
21
  Module({
19
- providers: [InvalidationHints],
22
+ providers: [InvalidationHints, OrgIntentHintsBridge],
20
23
  exports: [InvalidationHints],
21
24
  })
22
25
  ], InvalidationHintsModule);
@@ -30,8 +30,6 @@ export interface MeStreamParams {
30
30
  }
31
31
  /** The slow client cap: hints are tiny, so a client this far behind has stopped reading. */
32
32
  export declare const ME_STREAM_MAX_BACKLOG_BYTES: number;
33
- /** The final frame sent to the oldest stream of an account over the per-account cap. */
34
- export declare const SUPERSEDED_FRAME: string;
35
33
  /**
36
34
  * The account invalidation streams of this replica (`GET /api/v1/orgs/:orgId/me/stream`, account
37
35
  * invalidation stream spec §5): each forwards the hints of its topics as `event: hint` frames.
@@ -45,8 +43,7 @@ export declare const SUPERSEDED_FRAME: string;
45
43
  */
46
44
  export declare class MeStreams {
47
45
  private readonly active;
48
- /** Each account's streams on this replica, oldest first (replica-local resource accounting). */
49
- private readonly byAccount;
46
+ private readonly limit;
50
47
  private closing;
51
48
  private readonly d;
52
49
  constructor(bus: StreamBus, access: Pick<MeStreamAccess, "state">, config: Pick<KernelConfigService, "get">, log: Pick<Logger, "warn">, shutdown?: Pick<GracefulShutdown, "signal">);
@@ -57,11 +54,4 @@ export declare class MeStreams {
57
54
  get size(): number;
58
55
  /** How many streams `accountId` holds on this replica. */
59
56
  countOf(accountId: string): number;
60
- /**
61
- * Registers `conn` under its account as it begins, superseding the oldest streams over the cap
62
- * (read now, so a lowered limit applies at the next stream). The list is complete before any victim closes: a
63
- * victim's close finds itself already gone and never drops the account's entry.
64
- */
65
- private admit;
66
- private forget;
67
57
  }
@@ -16,6 +16,7 @@ import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.j
16
16
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
17
17
  import { ORG_ROLES } from "../orgs/roles.js";
18
18
  import { endedStream, } from "../runtime/stream.js";
19
+ import { PerAccountStreamLimit, SUPERSEDED_FRAME } from "../runtime/stream-limit.js";
19
20
  import { hintFrame, parseHint, streamTopics } from "./hints.js";
20
21
  /** Reads the membership, role, account status and super admin flag in one query. */
21
22
  let MeStreamAccess = class MeStreamAccess {
@@ -52,8 +53,6 @@ MeStreamAccess = __decorate([
52
53
  export { MeStreamAccess };
53
54
  /** The slow client cap: hints are tiny, so a client this far behind has stopped reading. */
54
55
  export const ME_STREAM_MAX_BACKLOG_BYTES = 64 * 1024;
55
- /** The final frame sent to the oldest stream of an account over the per-account cap. */
56
- export const SUPERSEDED_FRAME = `event: closed\ndata: ${JSON.stringify({ reason: "superseded" })}\n\n`;
57
56
  const roleRank = (r) => ORG_ROLES.indexOf(r);
58
57
  async function verdict(d, p) {
59
58
  const denied = await p.credential();
@@ -81,8 +80,7 @@ async function verdict(d, p) {
81
80
  */
82
81
  let MeStreams = class MeStreams {
83
82
  active = new Set();
84
- /** Each account's streams on this replica, oldest first (replica-local resource accounting). */
85
- byAccount = new Map();
83
+ limit = new PerAccountStreamLimit();
86
84
  closing = false;
87
85
  d;
88
86
  constructor(bus, access, config, log, shutdown) {
@@ -99,7 +97,7 @@ let MeStreams = class MeStreams {
99
97
  throw new ApiError(v.code, "Access denied");
100
98
  if (this.closing)
101
99
  return endedStream(out);
102
- const conn = new MeConnection(this.d, p, out, () => this.admit(conn), () => this.forget(conn));
100
+ const conn = new MeConnection(this.d, p, out, this.limit, () => this.active.delete(conn));
103
101
  this.active.add(conn);
104
102
  try {
105
103
  await conn.apply(v.role, v.superAdmin, false);
@@ -127,32 +125,7 @@ let MeStreams = class MeStreams {
127
125
  }
128
126
  /** How many streams `accountId` holds on this replica. */
129
127
  countOf(accountId) {
130
- return this.byAccount.get(accountId)?.length ?? 0;
131
- }
132
- /**
133
- * Registers `conn` under its account as it begins, superseding the oldest streams over the cap
134
- * (read now, so a lowered limit applies at the next stream). The list is complete before any victim closes: a
135
- * victim's close finds itself already gone and never drops the account's entry.
136
- */
137
- admit(conn) {
138
- const list = this.byAccount.get(conn.accountId) ?? [];
139
- const max = this.d.config.get().runtime.meStreamMaxPerAccount;
140
- const victims = list.splice(0, Math.max(0, list.length - max + 1));
141
- list.push(conn);
142
- this.byAccount.set(conn.accountId, list);
143
- for (const v of victims)
144
- v.close("end", SUPERSEDED_FRAME);
145
- }
146
- forget(conn) {
147
- this.active.delete(conn);
148
- const list = this.byAccount.get(conn.accountId);
149
- if (!list)
150
- return;
151
- const i = list.indexOf(conn);
152
- if (i >= 0)
153
- list.splice(i, 1);
154
- if (list.length === 0)
155
- this.byAccount.delete(conn.accountId);
128
+ return this.limit.countOf(accountId);
156
129
  }
157
130
  };
158
131
  MeStreams = __decorate([
@@ -169,7 +142,6 @@ class MeConnection {
169
142
  d;
170
143
  p;
171
144
  out;
172
- onBegin;
173
145
  onClosed;
174
146
  closed = false;
175
147
  begun = false;
@@ -183,17 +155,13 @@ class MeConnection {
183
155
  */
184
156
  subs = new Map();
185
157
  timers = [];
186
- constructor(d, p, out,
187
- /** Counts the stream against the per-account cap; called by `begin()`. */
188
- onBegin, onClosed) {
158
+ slot;
159
+ constructor(d, p, out, limit, onClosed) {
189
160
  this.d = d;
190
161
  this.p = p;
191
162
  this.out = out;
192
- this.onBegin = onBegin;
193
163
  this.onClosed = onClosed;
194
- }
195
- get accountId() {
196
- return this.p.accountId;
164
+ this.slot = limit.register(p.accountId, () => this.close("end", SUPERSEDED_FRAME));
197
165
  }
198
166
  get isClosed() {
199
167
  return this.closed;
@@ -261,6 +229,8 @@ class MeConnection {
261
229
  }
262
230
  }
263
231
  begin() {
232
+ if (this.begun)
233
+ return;
264
234
  if (this.closed) {
265
235
  // closed before the headers went out (shutdown): end the empty stream
266
236
  try {
@@ -272,14 +242,15 @@ class MeConnection {
272
242
  return;
273
243
  }
274
244
  this.begun = true;
275
- this.onBegin();
276
- const { sseHeartbeatMs, sseRecheckMs } = this.d.config.get().runtime;
245
+ const { sseHeartbeatMs, sseRecheckMs, meStreamMaxPerAccount } = this.d.config.get().runtime;
246
+ this.slot.begin(meStreamMaxPerAccount);
277
247
  this.timers.push(setInterval(() => this.write(": ping\n\n"), sseHeartbeatMs), setInterval(() => void this.recheck(), sseRecheckMs));
278
248
  }
279
249
  close(mode = "end", finalFrame) {
280
250
  if (this.closed)
281
251
  return;
282
252
  this.closed = true;
253
+ this.slot.close();
283
254
  for (const t of this.timers)
284
255
  clearInterval(t);
285
256
  this.timers = [];
@@ -0,0 +1,18 @@
1
+ import { type OnModuleDestroy, type OnModuleInit } from "@nestjs/common";
2
+ import { KernelEvents } from "../infra/events/kernel-events.js";
3
+ import { InvalidationHints } from "./invalidation-hints.js";
4
+ /**
5
+ * Bridges the in-process `catalog.org-intent-changed` event (emitted after the commit of a catalog
6
+ * write) to the account invalidation stream (spec §4 "Org intent"): an event naming an org
7
+ * publishes `capabilities` on that org's caps topic. A deployment-wide event (no org) publishes
8
+ * nothing here: its orgs are the plugin effect pairs the writer owed, and each pair's job
9
+ * publishes for its org when it settles (`PluginScopeSync`), so no writer reads every org.
10
+ */
11
+ export declare class OrgIntentHintsBridge implements OnModuleInit, OnModuleDestroy {
12
+ private readonly events;
13
+ private readonly hints;
14
+ private off;
15
+ constructor(events: Pick<KernelEvents, "on">, hints: Pick<InvalidationHints, "publish">);
16
+ onModuleInit(): void;
17
+ onModuleDestroy(): void;
18
+ }
@@ -0,0 +1,46 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { KernelEvents } from "../infra/events/kernel-events.js";
12
+ import { orgCapsTopic } from "./hints.js";
13
+ import { InvalidationHints } from "./invalidation-hints.js";
14
+ /**
15
+ * Bridges the in-process `catalog.org-intent-changed` event (emitted after the commit of a catalog
16
+ * write) to the account invalidation stream (spec §4 "Org intent"): an event naming an org
17
+ * publishes `capabilities` on that org's caps topic. A deployment-wide event (no org) publishes
18
+ * nothing here: its orgs are the plugin effect pairs the writer owed, and each pair's job
19
+ * publishes for its org when it settles (`PluginScopeSync`), so no writer reads every org.
20
+ */
21
+ let OrgIntentHintsBridge = class OrgIntentHintsBridge {
22
+ events;
23
+ hints;
24
+ off;
25
+ constructor(events, hints) {
26
+ this.events = events;
27
+ this.hints = hints;
28
+ }
29
+ onModuleInit() {
30
+ this.off = this.events.on("catalog.org-intent-changed", async ({ orgId }) => {
31
+ // already after the commit (the emitter's afterCommit)
32
+ if (typeof orgId === "string") {
33
+ await this.hints.publish([orgCapsTopic(orgId)], { kind: "capabilities" });
34
+ }
35
+ });
36
+ }
37
+ onModuleDestroy() {
38
+ this.off?.();
39
+ }
40
+ };
41
+ OrgIntentHintsBridge = __decorate([
42
+ Injectable(),
43
+ __param(0, Inject(KernelEvents)),
44
+ __param(1, Inject(InvalidationHints))
45
+ ], OrgIntentHintsBridge);
46
+ export { OrgIntentHintsBridge };
@@ -4,6 +4,7 @@ import { SuperAdminLock } from "../identity/super-admin.js";
4
4
  import { CacheService } from "../infra/cache/cache.service.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
+ import { type HintPublisher } from "../invalidation/audiences.js";
7
8
  import { OrgLock } from "../orgs/org-lock.js";
8
9
  import type { OrgRole } from "../orgs/roles.js";
9
10
  /** The key of a model in a disabled set: `provider\u0000model`. */
@@ -59,7 +60,8 @@ export declare class ModelEnablement {
59
60
  private readonly extensions;
60
61
  private readonly adminLock;
61
62
  private readonly orgLock;
62
- constructor(kdb: KernelDb, txHost: TransactionHost, cacheService: CacheService, extensions: Pick<ExtensionRegistry, "list">, adminLock: Pick<SuperAdminLock, "lockAndAuthorize">, orgLock: Pick<OrgLock, "lockAndAuthorize">);
63
+ private readonly hints;
64
+ constructor(kdb: KernelDb, txHost: TransactionHost, cacheService: CacheService, extensions: Pick<ExtensionRegistry, "list">, adminLock: Pick<SuperAdminLock, "lockAndAuthorize">, orgLock: Pick<OrgLock, "lockAndAuthorize">, hints: HintPublisher);
63
65
  private get db();
64
66
  /** One layer's disabled models (keys {@link modelKey}): the platform's (`null`) or the org's own. */
65
67
  disabled(orgId: string | null): Promise<Set<string>>;
@@ -20,6 +20,9 @@ import { Cacheable, CacheEvict } from "../infra/cache/cacheable.decorator.js";
20
20
  import { KernelDb } from "../infra/database/kernel-db.js";
21
21
  import { TransactionHost } from "../infra/database/transaction-host.js";
22
22
  import { Transactional } from "../infra/database/transactional.decorator.js";
23
+ import { publishCapabilities, publishPlatformCapabilities, } from "../invalidation/audiences.js";
24
+ import { InvalidationHints } from "../invalidation/invalidation-hints.js";
25
+ import { InvalidationHintsModule } from "../invalidation/invalidation-hints.module.js";
23
26
  import { OrgLock, OrgLockModule } from "../orgs/org-lock.js";
24
27
  /** The key of a model in a disabled set: `provider\u0000model`. */
25
28
  export const modelKey = (provider, model) => `${provider}\u0000${model}`;
@@ -46,13 +49,15 @@ let ModelEnablement = class ModelEnablement {
46
49
  extensions;
47
50
  adminLock;
48
51
  orgLock;
49
- constructor(kdb, txHost, cacheService, extensions, adminLock, orgLock) {
52
+ hints;
53
+ constructor(kdb, txHost, cacheService, extensions, adminLock, orgLock, hints) {
50
54
  this.kdb = kdb;
51
55
  this.txHost = txHost;
52
56
  this.cacheService = cacheService;
53
57
  this.extensions = extensions;
54
58
  this.adminLock = adminLock;
55
59
  this.orgLock = orgLock;
60
+ this.hints = hints;
56
61
  }
57
62
  get db() {
58
63
  return this.kdb.db;
@@ -163,14 +168,22 @@ let ModelEnablement = class ModelEnablement {
163
168
  }
164
169
  // models the platform disabled: every org's pending requests for them are cancelled
165
170
  if (orgId === null) {
166
- await cancelEnableRequestsOfPlatformModels(this.db, provider, added, actor.accountId);
171
+ await cancelEnableRequestsOfPlatformModels(this.db, this.hints, provider, added, actor.accountId);
167
172
  }
168
173
  // models an org admin switched back on settle the org's pending enable requests for them
169
174
  if (orgId !== null) {
170
175
  for (const model of removed) {
171
- await settleEnableRequests(this.db, orgId, { kind: "model", id: encodeModelId(provider, model) }, actor.accountId, { ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }) });
176
+ await settleEnableRequests(this.db, this.hints, orgId, { kind: "model", id: encodeModelId(provider, model) }, actor.accountId, { ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }) });
172
177
  }
173
178
  }
179
+ // a model list changed: the org's members refetch, or every org's for the platform's list
180
+ // (`platform-caps`: the writer holds no org set and never reads every org)
181
+ if (added.length > 0 || removed.length > 0) {
182
+ if (orgId !== null)
183
+ publishCapabilities(this.hints, [orgId]);
184
+ else
185
+ publishPlatformCapabilities(this.hints);
186
+ }
174
187
  if (added.length > 0 || removed.length > 0) {
175
188
  await audit(this.db, {
176
189
  actorAccountId: actor.accountId,
@@ -273,7 +286,8 @@ ModelEnablement = __decorate([
273
286
  __param(2, Inject(CacheService)),
274
287
  __param(3, Inject(ExtensionRegistry)),
275
288
  __param(4, Inject(SuperAdminLock)),
276
- __param(5, Inject(OrgLock))
289
+ __param(5, Inject(OrgLock)),
290
+ __param(6, Inject(InvalidationHints))
277
291
  ], ModelEnablement);
278
292
  export { ModelEnablement };
279
293
  /** The one {@link ModelEnablement}: the provider registry, purposes and the controllers read it. */
@@ -281,7 +295,13 @@ let ModelEnablementModule = class ModelEnablementModule {
281
295
  };
282
296
  ModelEnablementModule = __decorate([
283
297
  Module({
284
- imports: [ExtensionRegistryModule, SuperAdminLockModule, OrgLockModule],
298
+ imports: [
299
+ // invalidation hints its writers publish after their commit
300
+ InvalidationHintsModule,
301
+ ExtensionRegistryModule,
302
+ SuperAdminLockModule,
303
+ OrgLockModule,
304
+ ],
285
305
  providers: [ModelEnablement],
286
306
  exports: [ModelEnablement],
287
307
  })
@@ -5,6 +5,7 @@ import { SessionService } from "../identity/sessions.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
7
  import { OutboxService } from "../infra/outbox/outbox.service.js";
8
+ import type { HintPublisher } from "../invalidation/audiences.js";
8
9
  import type { KernelLogger } from "../log.js";
9
10
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
10
11
  import { ApprovalsService } from "../tools/approvals.service.js";
@@ -87,13 +88,14 @@ export declare class Offboarding {
87
88
  readonly log: KernelLogger;
88
89
  private readonly ceilings;
89
90
  private readonly orgLock;
91
+ private readonly hints;
90
92
  constructor(db: KernelDb, txHost: TransactionHost, sessions: Pick<SessionService, "markRevoked">, registry: Pick<ExtensionRegistry, "list">, eventLog: Pick<EventLog, "notify" | "publishChanged">,
91
93
  /** Owes the run stops and device destroys in the offboard transaction. */
92
94
  outbox: Pick<OutboxService, "add">,
93
95
  /** Stops the departed member's runs (`by: null`, a system action) in the `run-stop` job. */
94
96
  runs: OffboardingRunControl, credentials: Pick<Credentials, "clearAccount">, approvals: Pick<ApprovalsService, "pendingConversationsFor" | "cancelPendingFor">, questions: Pick<QuestionsService, "pendingConversationsFor" | "cancelPendingFor">,
95
97
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
96
- lifecycle: Pick<LifecycleHooks, "recordIn">, log: KernelLogger, ceilings: PermissionCeilingWrites, orgLock: Pick<OrgLock, "lockForRemoval">);
98
+ lifecycle: Pick<LifecycleHooks, "recordIn">, log: KernelLogger, ceilings: PermissionCeilingWrites, orgLock: Pick<OrgLock, "lockForRemoval">, hints: HintPublisher);
97
99
  /**
98
100
  * In the caller's transaction (`mandatory`: the caller holds the org row lock, order org row →
99
101
  * membership, and did the "last owner" checks):