@capybara-hq/kernel 0.1.0-rc.141 → 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 (129) 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 +4 -0
  48. package/dist/config/schema.js +40 -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/http/api.module.js +6 -0
  60. package/dist/inbox/inbox-items.service.d.ts +6 -1
  61. package/dist/inbox/inbox-items.service.js +29 -10
  62. package/dist/inbox/inbox.module.js +3 -0
  63. package/dist/inbox/inbox.service.d.ts +3 -1
  64. package/dist/inbox/inbox.service.js +9 -2
  65. package/dist/inbox/org-notices.d.ts +4 -3
  66. package/dist/inbox/org-notices.js +9 -6
  67. package/dist/inbox/platform-inbox.service.d.ts +3 -1
  68. package/dist/inbox/platform-inbox.service.js +11 -3
  69. package/dist/inbox/platform-notices.d.ts +3 -2
  70. package/dist/inbox/platform-notices.js +10 -4
  71. package/dist/infra/config/kernel-config.service.js +5 -0
  72. package/dist/invalidation/audiences.d.ts +32 -0
  73. package/dist/invalidation/audiences.js +43 -0
  74. package/dist/invalidation/hints.d.ts +62 -0
  75. package/dist/invalidation/hints.js +73 -0
  76. package/dist/invalidation/invalidation-hints.d.ts +35 -0
  77. package/dist/invalidation/invalidation-hints.js +100 -0
  78. package/dist/invalidation/invalidation-hints.module.d.ts +10 -0
  79. package/dist/invalidation/invalidation-hints.module.js +26 -0
  80. package/dist/invalidation/me-stream.controller.d.ts +30 -0
  81. package/dist/invalidation/me-stream.controller.js +100 -0
  82. package/dist/invalidation/me-stream.d.ts +57 -0
  83. package/dist/invalidation/me-stream.js +322 -0
  84. package/dist/invalidation/me-stream.module.d.ts +7 -0
  85. package/dist/invalidation/me-stream.module.js +22 -0
  86. package/dist/invalidation/org-intent-bridge.d.ts +18 -0
  87. package/dist/invalidation/org-intent-bridge.js +46 -0
  88. package/dist/kernel.module.js +4 -0
  89. package/dist/models/enablement.d.ts +3 -1
  90. package/dist/models/enablement.js +25 -5
  91. package/dist/orgs/offboarding.d.ts +3 -1
  92. package/dist/orgs/offboarding.js +7 -3
  93. package/dist/orgs/orgs.module.js +3 -0
  94. package/dist/orgs/orgs.service.d.ts +3 -1
  95. package/dist/orgs/orgs.service.js +7 -3
  96. package/dist/platform/exclusions.js +5 -0
  97. package/dist/push/delivery.d.ts +3 -1
  98. package/dist/push/delivery.js +7 -3
  99. package/dist/push/push-processor.js +8 -1
  100. package/dist/runtime/stream-limit.d.ts +13 -0
  101. package/dist/runtime/stream-limit.js +40 -0
  102. package/dist/runtime/stream.controller.d.ts +2 -0
  103. package/dist/runtime/stream.controller.js +2 -0
  104. package/dist/runtime/stream.d.ts +1 -0
  105. package/dist/runtime/stream.js +15 -6
  106. package/dist/sandbox/permission-authority.module.js +6 -1
  107. package/dist/sandbox/permission-transitions.d.ts +3 -1
  108. package/dist/sandbox/permission-transitions.js +17 -2
  109. package/dist/skills/agent-skills.service.d.ts +6 -1
  110. package/dist/skills/agent-skills.service.js +12 -3
  111. package/dist/skills/changes.service.d.ts +6 -1
  112. package/dist/skills/changes.service.js +11 -3
  113. package/dist/skills/conversation-catalog.d.ts +3 -0
  114. package/dist/skills/conversation-catalog.js +2 -0
  115. package/dist/skills/skills.module.js +3 -0
  116. package/dist/skills/skills.service.d.ts +3 -1
  117. package/dist/skills/skills.service.js +8 -4
  118. package/dist/tools/approvals.service.d.ts +12 -1
  119. package/dist/tools/approvals.service.js +36 -9
  120. package/dist/tools/connectors.service.d.ts +3 -1
  121. package/dist/tools/connectors.service.js +29 -7
  122. package/dist/tools/tools.module.js +3 -0
  123. package/dist/ui/admin-ui.controller.d.ts +3 -1
  124. package/dist/ui/admin-ui.controller.js +3 -1
  125. package/dist/ui/ui-stream.d.ts +2 -0
  126. package/dist/ui/ui-stream.js +20 -6
  127. package/dist/ui/views.controller.d.ts +4 -2
  128. package/dist/ui/views.controller.js +4 -2
  129. 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
+ }
@@ -0,0 +1,62 @@
1
+ import { z } from "zod";
2
+ import { type OrgRole } from "../orgs/roles.js";
3
+ /**
4
+ * Account invalidation hints (account invalidation stream spec §3): a content-free "refetch now"
5
+ * nudge. A hint is its kind only: no ids, counts, names or org ids, so it can reveal nothing about
6
+ * an entry or another org. The org is implied by the bus topic and by the stream's own `:orgId`.
7
+ * Extra fields are rejected when the kernel publishes and when a frame is parsed.
8
+ */
9
+ export declare const HINT_KINDS: readonly ["inbox", "requests", "capabilities", "platform-inbox"];
10
+ export type HintKind = (typeof HINT_KINDS)[number];
11
+ export declare const Hint: z.ZodObject<{
12
+ kind: z.ZodEnum<{
13
+ capabilities: "capabilities";
14
+ inbox: "inbox";
15
+ "platform-inbox": "platform-inbox";
16
+ requests: "requests";
17
+ }>;
18
+ }, z.core.$strict>;
19
+ export type Hint = z.infer<typeof Hint>;
20
+ /** The hint `value` is, or undefined when it is anything else (an extra field, a wrong kind). */
21
+ export declare function parseHint(value: unknown): Hint | undefined;
22
+ /** The roles that have a role topic: guests have none (spec §3). */
23
+ export declare const TOPIC_ROLES: readonly ["member", "admin", "owner"];
24
+ export type TopicRole = (typeof TOPIC_ROLES)[number];
25
+ /** A topic of the account invalidation stream, as built by the builders below. */
26
+ export type InvalidationTopic = string & {
27
+ readonly __invalidationTopic: unique symbol;
28
+ };
29
+ /** The topic of one account's streams: every org stream of that account listens to it. */
30
+ export declare function acctTopic(accountId: string): InvalidationTopic;
31
+ /**
32
+ * The topic of the members of `orgId` at or above `role`: a stream subscribes to every role topic
33
+ * at or below its member's role, so a writer publishes once per role value.
34
+ */
35
+ export declare function orgRoleTopic(orgId: string, role: TopicRole): InvalidationTopic;
36
+ /** The topic of committed org intent changes (capabilities): every member stream (not guests). */
37
+ export declare function orgCapsTopic(orgId: string): InvalidationTopic;
38
+ /** The topic of super admin streams. */
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;
46
+ /** The role topics a member with `role` listens to: every one at or below it (guest: none). */
47
+ export declare function roleTopicRoles(role: OrgRole): TopicRole[];
48
+ /**
49
+ * The identity a stream's topics come from, all of it verified by the kernel: the principal's
50
+ * account id, its membership role in the stream's org (read from PG after the org guard) and its
51
+ * super admin flag. Nothing from the request (query, headers, body, `Last-Event-ID`) goes here.
52
+ */
53
+ export interface StreamIdentity {
54
+ accountId: string;
55
+ orgId: string;
56
+ role: OrgRole;
57
+ superAdmin: boolean;
58
+ }
59
+ /** The topics a stream of `id` subscribes to (spec §5 "Subscriptions"). */
60
+ export declare function streamTopics(id: StreamIdentity): InvalidationTopic[];
61
+ /** The SSE frame of a hint: `event: hint`, data the hint's JSON (its kind only). */
62
+ export declare const hintFrame: (h: Hint) => string;
@@ -0,0 +1,73 @@
1
+ import { z } from "zod";
2
+ import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
3
+ /**
4
+ * Account invalidation hints (account invalidation stream spec §3): a content-free "refetch now"
5
+ * nudge. A hint is its kind only: no ids, counts, names or org ids, so it can reveal nothing about
6
+ * an entry or another org. The org is implied by the bus topic and by the stream's own `:orgId`.
7
+ * Extra fields are rejected when the kernel publishes and when a frame is parsed.
8
+ */
9
+ export const HINT_KINDS = ["inbox", "requests", "capabilities", "platform-inbox"];
10
+ export const Hint = z.strictObject({ kind: z.enum(HINT_KINDS) });
11
+ /** The hint `value` is, or undefined when it is anything else (an extra field, a wrong kind). */
12
+ export function parseHint(value) {
13
+ const r = Hint.safeParse(value);
14
+ return r.success ? { kind: r.data.kind } : undefined;
15
+ }
16
+ /** The roles that have a role topic: guests have none (spec §3). */
17
+ export const TOPIC_ROLES = ["member", "admin", "owner"];
18
+ /**
19
+ * Ids that go into a topic name: kernel-generated ids, never containing the `.` that separates
20
+ * topic segments, so one id cannot spell another topic.
21
+ */
22
+ const ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
23
+ function assertId(what, id) {
24
+ if (typeof id !== "string" || !ID_RE.test(id))
25
+ throw new Error(`invalid ${what} for a topic`);
26
+ }
27
+ /** The topic of one account's streams: every org stream of that account listens to it. */
28
+ export function acctTopic(accountId) {
29
+ assertId("account id", accountId);
30
+ return `acct.${accountId}`;
31
+ }
32
+ /**
33
+ * The topic of the members of `orgId` at or above `role`: a stream subscribes to every role topic
34
+ * at or below its member's role, so a writer publishes once per role value.
35
+ */
36
+ export function orgRoleTopic(orgId, role) {
37
+ assertId("org id", orgId);
38
+ if (!TOPIC_ROLES.includes(role))
39
+ throw new Error("invalid topic role");
40
+ return `org-role.${orgId}.${role}`;
41
+ }
42
+ /** The topic of committed org intent changes (capabilities): every member stream (not guests). */
43
+ export function orgCapsTopic(orgId) {
44
+ assertId("org id", orgId);
45
+ return `org-caps.${orgId}`;
46
+ }
47
+ /** The topic of super admin streams. */
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";
55
+ /** The role topics a member with `role` listens to: every one at or below it (guest: none). */
56
+ export function roleTopicRoles(role) {
57
+ return TOPIC_ROLES.filter((r) => roleAtLeast(role, r));
58
+ }
59
+ /** The topics a stream of `id` subscribes to (spec §5 "Subscriptions"). */
60
+ export function streamTopics(id) {
61
+ if (!ORG_ROLES.includes(id.role))
62
+ throw new Error("invalid org role");
63
+ const topics = [acctTopic(id.accountId)];
64
+ for (const r of roleTopicRoles(id.role))
65
+ topics.push(orgRoleTopic(id.orgId, r));
66
+ if (roleAtLeast(id.role, "member"))
67
+ topics.push(orgCapsTopic(id.orgId), PLATFORM_CAPS_TOPIC);
68
+ if (id.superAdmin)
69
+ topics.push(PLATFORM_ADMINS_TOPIC);
70
+ return topics;
71
+ }
72
+ /** The SSE frame of a hint: `event: hint`, data the hint's JSON (its kind only). */
73
+ export const hintFrame = (h) => `event: hint\ndata: ${JSON.stringify({ kind: h.kind })}\n\n`;
@@ -0,0 +1,35 @@
1
+ import type { ExtensionContext, Logger } from "@capybara-hq/plugin-sdk";
2
+ import { Hint, type InvalidationTopic } from "./hints.js";
3
+ /**
4
+ * Publishes account invalidation hints on the kernel bus (account invalidation stream spec §4).
5
+ * A hint is harmless to lose (the web's `live` freshness converges anyway), so it is an
6
+ * after-commit side effect, never an outbox row: {@link publishAfterCommit} is what a writer calls
7
+ * inside its transaction; a rollback publishes nothing. Topics come from the builders in
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.
11
+ */
12
+ export declare class InvalidationHints {
13
+ private readonly bus;
14
+ private readonly log;
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">);
23
+ /**
24
+ * Publishes `hint` on every topic now. The hint is validated first (kind only: an extra field
25
+ * throws, a programming error); bus failures are logged and never thrown.
26
+ */
27
+ publish(topics: readonly InvalidationTopic[], hint: Hint): Promise<void>;
28
+ /**
29
+ * Publishes `hint` after the root transaction commits (at once outside a transaction); a
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.
33
+ */
34
+ publishAfterCommit(topics: readonly InvalidationTopic[], hint: Hint): void;
35
+ }
@@ -0,0 +1,100 @@
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, Optional } from "@nestjs/common";
11
+ import { afterCommit } from "../infra/database/after-commit.js";
12
+ import { currentStore } from "../infra/database/transaction-host.js";
13
+ import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
14
+ import { Hint } from "./hints.js";
15
+ /**
16
+ * Publishes account invalidation hints on the kernel bus (account invalidation stream spec §4).
17
+ * A hint is harmless to lose (the web's `live` freshness converges anyway), so it is an
18
+ * after-commit side effect, never an outbox row: {@link publishAfterCommit} is what a writer calls
19
+ * inside its transaction; a rollback publishes nothing. Topics come from the builders in
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.
23
+ */
24
+ let InvalidationHints = class InvalidationHints {
25
+ bus;
26
+ 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) {
37
+ this.bus = bus;
38
+ this.log = log;
39
+ }
40
+ /**
41
+ * Publishes `hint` on every topic now. The hint is validated first (kind only: an extra field
42
+ * throws, a programming error); bus failures are logged and never thrown.
43
+ */
44
+ async publish(topics, hint) {
45
+ const h = Hint.parse(hint);
46
+ const bus = this.bus;
47
+ if (bus === undefined)
48
+ return;
49
+ const unique = [...new Set(topics)];
50
+ await Promise.all(unique.map(async (topic) => {
51
+ try {
52
+ await bus.publish(topic, { kind: h.kind });
53
+ }
54
+ catch (err) {
55
+ this.log.warn("invalidation hint publish failed", { topic, kind: h.kind, err });
56
+ }
57
+ }));
58
+ }
59
+ /**
60
+ * Publishes `hint` after the root transaction commits (at once outside a transaction); a
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.
64
+ */
65
+ publishAfterCommit(topics, hint) {
66
+ const h = Hint.parse(hint);
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);
92
+ }
93
+ };
94
+ InvalidationHints = __decorate([
95
+ Injectable(),
96
+ __param(0, Optional()),
97
+ __param(0, Inject(KERNEL_BUS)),
98
+ __param(1, Inject(KERNEL_LOGGER))
99
+ ], InvalidationHints);
100
+ export { InvalidationHints };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Account invalidation hints (account invalidation stream spec §4): {@link InvalidationHints}, which
3
+ * writers call after their commit. It needs only the global kernel bus and logger, so any module
4
+ * may import it, whatever role runs it (api requests, worker jobs, the gateway). The topic builders
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.
8
+ */
9
+ export declare class InvalidationHintsModule {
10
+ }
@@ -0,0 +1,26 @@
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
+ import { Module } from "@nestjs/common";
8
+ import { InvalidationHints } from "./invalidation-hints.js";
9
+ import { OrgIntentHintsBridge } from "./org-intent-bridge.js";
10
+ /**
11
+ * Account invalidation hints (account invalidation stream spec §4): {@link InvalidationHints}, which
12
+ * writers call after their commit. It needs only the global kernel bus and logger, so any module
13
+ * may import it, whatever role runs it (api requests, worker jobs, the gateway). The topic builders
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.
17
+ */
18
+ let InvalidationHintsModule = class InvalidationHintsModule {
19
+ };
20
+ InvalidationHintsModule = __decorate([
21
+ Module({
22
+ providers: [InvalidationHints, OrgIntentHintsBridge],
23
+ exports: [InvalidationHints],
24
+ })
25
+ ], InvalidationHintsModule);
26
+ export { InvalidationHintsModule };
@@ -0,0 +1,30 @@
1
+ import type { FastifyReply, FastifyRequest } from "fastify";
2
+ import { ApiTokenService } from "../identity/api-tokens.js";
3
+ import { type Principal } from "../identity/principal.js";
4
+ import { SessionService } from "../identity/sessions.js";
5
+ import { type OrgContext } from "../orgs/org.guard.js";
6
+ import { MeStreams } from "./me-stream.js";
7
+ /**
8
+ * The account invalidation stream (account invalidation stream spec §5):
9
+ * - `GET /api/v1/orgs/:orgId/me/stream`: SSE of content-free hints (`event: hint`,
10
+ * `data: {"kind"}` with kind `inbox` | `requests` | `capabilities` | `platform-inbox`) addressed
11
+ * to the caller in this org; any member, a guest included (a guest gets only its account's
12
+ * hints); user principals only (session cookie or personal token). Heartbeat and recheck follow
13
+ * `runtime.sseHeartbeatMs` / `runtime.sseRecheckMs`; a lost membership, a disabled account or a
14
+ * revoked credential ends it with `event: error` (`data: {"code"}`); over
15
+ * `runtime.meStreamMaxPerAccount` on one replica the account's oldest stream ends with
16
+ * `event: closed` (`data: {"reason":"superseded"}`). No replay (`Last-Event-ID` is ignored).
17
+ * A client treats any `event: error` as terminal, whatever its code. A removed or downgraded
18
+ * member may still get kind-only org-topic hints until the next recheck (accepted: hints carry
19
+ * nothing but their kind).
20
+ *
21
+ * The stream's topics come only from the principal, the org guard's verified membership and the
22
+ * recheck's PG read: no query, header or body value is read here.
23
+ */
24
+ export declare class MeStreamController {
25
+ private readonly streams;
26
+ private readonly sessions;
27
+ private readonly tokens;
28
+ constructor(streams: MeStreams, sessions: SessionService, tokens: ApiTokenService);
29
+ stream(principal: Principal, org: OrgContext, req: FastifyRequest, reply: FastifyReply): Promise<void>;
30
+ }
@@ -0,0 +1,100 @@
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 { Controller, Get, Inject, Req, Res } from "@nestjs/common";
11
+ import { ApiTokenService } from "../identity/api-tokens.js";
12
+ import { credentialCheck } from "../identity/credential-check.js";
13
+ import { CurrentPrincipal, requireUser } from "../identity/principal.js";
14
+ import { SessionService } from "../identity/sessions.js";
15
+ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
16
+ import { BEARER_RE } from "../ui/views.controller.js";
17
+ import { MeStreams } from "./me-stream.js";
18
+ /**
19
+ * The account invalidation stream (account invalidation stream spec §5):
20
+ * - `GET /api/v1/orgs/:orgId/me/stream`: SSE of content-free hints (`event: hint`,
21
+ * `data: {"kind"}` with kind `inbox` | `requests` | `capabilities` | `platform-inbox`) addressed
22
+ * to the caller in this org; any member, a guest included (a guest gets only its account's
23
+ * hints); user principals only (session cookie or personal token). Heartbeat and recheck follow
24
+ * `runtime.sseHeartbeatMs` / `runtime.sseRecheckMs`; a lost membership, a disabled account or a
25
+ * revoked credential ends it with `event: error` (`data: {"code"}`); over
26
+ * `runtime.meStreamMaxPerAccount` on one replica the account's oldest stream ends with
27
+ * `event: closed` (`data: {"reason":"superseded"}`). No replay (`Last-Event-ID` is ignored).
28
+ * A client treats any `event: error` as terminal, whatever its code. A removed or downgraded
29
+ * member may still get kind-only org-topic hints until the next recheck (accepted: hints carry
30
+ * nothing but their kind).
31
+ *
32
+ * The stream's topics come only from the principal, the org guard's verified membership and the
33
+ * recheck's PG read: no query, header or body value is read here.
34
+ */
35
+ let MeStreamController = class MeStreamController {
36
+ streams;
37
+ sessions;
38
+ tokens;
39
+ constructor(streams, sessions, tokens) {
40
+ this.streams = streams;
41
+ this.sessions = sessions;
42
+ this.tokens = tokens;
43
+ }
44
+ async stream(principal, org, req, reply) {
45
+ const p = requireUser(principal);
46
+ const res = reply.raw;
47
+ const handle = await this.streams.open({
48
+ orgId: org.orgId,
49
+ accountId: p.account.id,
50
+ // the bearer re-authenticates the same token the auth guard accepted (never a topic input)
51
+ credential: credentialCheck(p, BEARER_RE.exec(req.headers.authorization ?? "")?.[1], {
52
+ sessions: this.sessions,
53
+ tokens: this.tokens,
54
+ }),
55
+ }, {
56
+ write: (chunk) => {
57
+ res.write(chunk);
58
+ },
59
+ backlog: () => res.writableLength,
60
+ end: () => {
61
+ res.end();
62
+ },
63
+ abort: () => {
64
+ res.destroy();
65
+ },
66
+ });
67
+ reply.hijack();
68
+ res.on("close", () => handle.close());
69
+ if (res.destroyed || !res.socket || res.socket.destroyed) {
70
+ handle.close();
71
+ res.destroy();
72
+ return;
73
+ }
74
+ res.writeHead(200, {
75
+ "content-type": "text/event-stream; charset=utf-8",
76
+ "cache-control": "no-cache",
77
+ "x-accel-buffering": "no",
78
+ connection: "keep-alive",
79
+ });
80
+ res.flushHeaders();
81
+ handle.begin();
82
+ }
83
+ };
84
+ __decorate([
85
+ Get("stream")
86
+ // the person's own hints: any member, a guest included; requireUser refuses service tokens
87
+ ,
88
+ OrgAction("org.read"),
89
+ __param(0, CurrentPrincipal()),
90
+ __param(1, CurrentOrg()),
91
+ __param(2, Req()),
92
+ __param(3, Res())
93
+ ], MeStreamController.prototype, "stream", null);
94
+ MeStreamController = __decorate([
95
+ Controller("api/v1/orgs/:orgId/me"),
96
+ __param(0, Inject(MeStreams)),
97
+ __param(1, Inject(SessionService)),
98
+ __param(2, Inject(ApiTokenService))
99
+ ], MeStreamController);
100
+ export { MeStreamController };
@@ -0,0 +1,57 @@
1
+ import type { Logger } from "@capybara-hq/plugin-sdk";
2
+ import type { CredentialCheck } from "../identity/credential-check.js";
3
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
6
+ import { type OrgRole } from "../orgs/roles.js";
7
+ import { type SseOutput, type StreamBus, type StreamHandle } from "../runtime/stream.js";
8
+ /** What the recheck reads about the stream's account in its org (one query). */
9
+ export interface MeStreamAccessState {
10
+ /** The account's status; undefined when the account no longer exists. */
11
+ status: "active" | "disabled" | undefined;
12
+ superAdmin: boolean;
13
+ /** The membership role in the org; undefined when not a member or the org is deleted. */
14
+ role: OrgRole | undefined;
15
+ }
16
+ /** Reads the membership, role, account status and super admin flag in one query. */
17
+ export declare class MeStreamAccess {
18
+ private readonly db;
19
+ constructor(db: KernelDb);
20
+ state(orgId: string, accountId: string): Promise<MeStreamAccessState>;
21
+ }
22
+ /**
23
+ * One stream's parameters, all from the authenticated principal and the org guard: the stream's
24
+ * topics are derived from these and the recheck's PG read, never from the request.
25
+ */
26
+ export interface MeStreamParams {
27
+ orgId: string;
28
+ accountId: string;
29
+ credential: CredentialCheck;
30
+ }
31
+ /** The slow client cap: hints are tiny, so a client this far behind has stopped reading. */
32
+ export declare const ME_STREAM_MAX_BACKLOG_BYTES: number;
33
+ /**
34
+ * The account invalidation streams of this replica (`GET /api/v1/orgs/:orgId/me/stream`, account
35
+ * invalidation stream spec §5): each forwards the hints of its topics as `event: hint` frames.
36
+ * Topics are recomputed on every `runtime.sseRecheckMs` recheck (credential first, then the
37
+ * membership, role, account status and super admin flag); a lost membership, a disabled account or
38
+ * a revoked credential ends the stream with `event: error` (`data: {"code"}`). At most
39
+ * `runtime.meStreamMaxPerAccount` streams per account on this replica: a new one over the cap
40
+ * supersedes the account's oldest (`event: closed`, `data: {"reason":"superseded"}`). No replay:
41
+ * the client refetches on open. Across replicas only through the Redis bus; this process holds
42
+ * only its connections' subscriptions and timers, closed at shutdown.
43
+ */
44
+ export declare class MeStreams {
45
+ private readonly active;
46
+ private readonly limit;
47
+ private closing;
48
+ private readonly d;
49
+ constructor(bus: StreamBus, access: Pick<MeStreamAccess, "state">, config: Pick<KernelConfigService, "get">, log: Pick<Logger, "warn">, shutdown?: Pick<GracefulShutdown, "signal">);
50
+ /** Checks access and subscribes; a refusal throws before anything was written. */
51
+ open(p: MeStreamParams, out: SseOutput): Promise<StreamHandle>;
52
+ /** Closes every stream of this process (at shutdown) and latches. */
53
+ closeAll(): void;
54
+ get size(): number;
55
+ /** How many streams `accountId` holds on this replica. */
56
+ countOf(accountId: string): number;
57
+ }