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

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 (82) hide show
  1. package/dist/agents/models.controller.d.ts +9 -2
  2. package/dist/agents/models.controller.js +35 -4
  3. package/dist/catalog/catalog-scope.service.js +3 -0
  4. package/dist/catalog/catalog.module.js +8 -0
  5. package/dist/catalog/catalog.service.d.ts +2 -2
  6. package/dist/catalog/catalog.service.js +3 -3
  7. package/dist/catalog/component-scope.controller.d.ts +2 -1
  8. package/dist/catalog/component-scope.controller.js +5 -2
  9. package/dist/catalog/component-scope.service.d.ts +16 -0
  10. package/dist/catalog/component-scope.service.js +21 -1
  11. package/dist/catalog/enable-decision.d.ts +34 -0
  12. package/dist/catalog/enable-decision.js +17 -0
  13. package/dist/catalog/enable-requests.d.ts +186 -0
  14. package/dist/catalog/enable-requests.js +767 -0
  15. package/dist/catalog/enable-targets.d.ts +63 -0
  16. package/dist/catalog/enable-targets.js +94 -0
  17. package/dist/catalog/org-catalog.controller.d.ts +11 -3
  18. package/dist/catalog/org-catalog.controller.js +28 -5
  19. package/dist/catalog/org-catalog.schemas.d.ts +38 -0
  20. package/dist/catalog/org-catalog.schemas.js +31 -0
  21. package/dist/catalog/org-catalog.service.js +1 -1
  22. package/dist/catalog/org-extension.controller.d.ts +1 -1
  23. package/dist/catalog/owned-items.js +6 -1
  24. package/dist/catalog/plugin-install.js +7 -2
  25. package/dist/catalog/plugin-upgrade.js +3 -0
  26. package/dist/catalog/request-rules.d.ts +7 -5
  27. package/dist/catalog/request-rules.js +53 -14
  28. package/dist/catalog/requests.service.d.ts +137 -4
  29. package/dist/catalog/requests.service.js +574 -28
  30. package/dist/catalog/scope-writer.d.ts +20 -3
  31. package/dist/catalog/scope-writer.js +32 -3
  32. package/dist/config/schema.d.ts +1 -0
  33. package/dist/config/schema.js +10 -0
  34. package/dist/ctx/bus.js +3 -2
  35. package/dist/db/kernel-schema.d.ts +3 -2
  36. package/dist/errors.d.ts +7 -0
  37. package/dist/errors.js +7 -0
  38. package/dist/extensions/admin-ops.js +2 -0
  39. package/dist/extensions/admin-view.js +2 -1
  40. package/dist/extensions/host.js +1 -1
  41. package/dist/extensions/org-config.d.ts +8 -0
  42. package/dist/extensions/org-config.js +20 -5
  43. package/dist/extensions/permission-view.d.ts +7 -0
  44. package/dist/extensions/plugin-guides.d.ts +1 -1
  45. package/dist/extensions/plugin-guides.js +1 -1
  46. package/dist/extensions/plugin-items.d.ts +8 -0
  47. package/dist/extensions/plugin-items.js +8 -0
  48. package/dist/http/api.module.js +6 -0
  49. package/dist/infra/config/kernel-config.service.js +2 -0
  50. package/dist/infra/queue/run-job.js +3 -1
  51. package/dist/invalidation/hints.d.ts +56 -0
  52. package/dist/invalidation/hints.js +67 -0
  53. package/dist/invalidation/invalidation-hints.d.ts +24 -0
  54. package/dist/invalidation/invalidation-hints.js +59 -0
  55. package/dist/invalidation/invalidation-hints.module.d.ts +8 -0
  56. package/dist/invalidation/invalidation-hints.module.js +23 -0
  57. package/dist/invalidation/me-stream.controller.d.ts +30 -0
  58. package/dist/invalidation/me-stream.controller.js +100 -0
  59. package/dist/invalidation/me-stream.d.ts +67 -0
  60. package/dist/invalidation/me-stream.js +351 -0
  61. package/dist/invalidation/me-stream.module.d.ts +7 -0
  62. package/dist/invalidation/me-stream.module.js +22 -0
  63. package/dist/kernel.module.js +4 -0
  64. package/dist/models/enablement.d.ts +12 -0
  65. package/dist/models/enablement.js +32 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +2 -2
  68. package/dist/platform/ops/catalog-admin.ops.js +1 -1
  69. package/dist/platform/ops/extensions-admin.ops.js +17 -9
  70. package/dist/platform/ops/extensions.ops.js +6 -3
  71. package/dist/platform/ops/org-plugins.ops.js +1 -1
  72. package/dist/platform/ops/plugins.ops.js +1 -1
  73. package/dist/platform/ops/requests.ops.js +55 -1
  74. package/dist/platform/ops/unavailable.js +2 -2
  75. package/dist/tools/builtins/sandbox/common.d.ts +3 -3
  76. package/dist/tools/builtins/sandbox/common.js +3 -3
  77. package/dist/tools/connectors.controller.d.ts +8 -1
  78. package/dist/tools/connectors.controller.js +14 -1
  79. package/dist/tools/connectors.service.d.ts +7 -0
  80. package/dist/tools/connectors.service.js +30 -0
  81. package/package.json +1 -1
  82. package/src/migrations/0233_enable_request_targets.sql +64 -0
@@ -8,6 +8,7 @@ import { XactLock } from "../infra/database/xact-lock.js";
8
8
  import { KernelEvents } from "../infra/events/kernel-events.js";
9
9
  import { OutboxService } from "../infra/outbox/outbox.service.js";
10
10
  import type { ComponentKind } from "./component-state.js";
11
+ import type { RequestActorOpts } from "./request-rules.js";
11
12
  import type { PluginScope } from "./scope.js";
12
13
  export declare const COMPONENT_SCOPE_TABLE: {
13
14
  readonly skill: "platform_skills";
@@ -40,7 +41,11 @@ type ScopeListChange = {
40
41
  scopeMode: "follow";
41
42
  scope?: never;
42
43
  }));
43
- /** Apply a typed scope change in the caller's transaction and under its target lock. */
44
+ /**
45
+ * Apply a typed scope change in the caller's transaction and under its target lock. Every scope
46
+ * write re-checks the pending enable requests of the subject in every org
47
+ * ({@link reconcileEnableRequestsOf}), so no caller can narrow a scope and leave a stale request.
48
+ */
44
49
  export declare function writeScope(db: KernelSchemaDb, change: ScopeListChange): Promise<void>;
45
50
  /** Extend a named plugin scope under its item lock. */
46
51
  export declare function addNamedPluginOrg(db: KernelSchemaDb, itemId: string, orgId: string): Promise<boolean>;
@@ -78,8 +83,20 @@ export declare class ScopeWriter {
78
83
  replaceScope(change: ScopeListChange): Promise<void>;
79
84
  /** Persist deployment enablement after platform confirmation. */
80
85
  setDisabled(subject: ScopeSubject, disabled: boolean): Promise<void>;
81
- /** Store local intent under the caller's transaction and org lock. */
82
- setOrgSwitch(subject: ScopeSubject, orgId: string, enabled: boolean, actor: string | null): Promise<void>;
86
+ /**
87
+ * Store local intent under the caller's transaction and org lock. The org's pending enable
88
+ * requests follow in the same transaction: switching a plugin or component on settles the
89
+ * requests that target it ({@link settleEnableRequests}); switching a plugin off cancels the
90
+ * requests for an extension or component that needed it on ({@link cancelEnableRequestsOfBundle}).
91
+ */
92
+ setOrgSwitch(subject: ScopeSubject, orgId: string, enabled: boolean, actor: string | null,
93
+ /**
94
+ * The token and audit detail of the write, for the settled requests' audit; `settle: false`
95
+ * (an install failure recording the switch) leaves pending requests pending.
96
+ */
97
+ opts?: RequestActorOpts & {
98
+ settle?: boolean;
99
+ }): Promise<void>;
83
100
  private oweConnectorTemplate;
84
101
  /** Catalog switches can change the intent of extensions brought in through a dependency. */
85
102
  refreshIsolatedOrgIntent(orgId?: string): void;
@@ -21,6 +21,7 @@ import { XactLock } from "../infra/database/xact-lock.js";
21
21
  import { KernelEvents } from "../infra/events/kernel-events.js";
22
22
  import { OutboxService } from "../infra/outbox/outbox.service.js";
23
23
  import { EFFECT_CANDIDATES_LOCK, oweEffectWork } from "./effect-work.js";
24
+ import { cancelEnableRequestsOfBundle, reconcileEnableRequestsOf, settleEnableRequests, } from "./enable-requests.js";
24
25
  export const COMPONENT_SCOPE_TABLE = {
25
26
  skill: "platform_skills",
26
27
  agent_template: "platform_agent_templates",
@@ -45,8 +46,16 @@ export async function writeComponentSwitch(db, subject, orgId, enabled, actor) {
45
46
  }))
46
47
  .execute();
47
48
  }
48
- /** Apply a typed scope change in the caller's transaction and under its target lock. */
49
+ /**
50
+ * Apply a typed scope change in the caller's transaction and under its target lock. Every scope
51
+ * write re-checks the pending enable requests of the subject in every org
52
+ * ({@link reconcileEnableRequestsOf}), so no caller can narrow a scope and leave a stale request.
53
+ */
49
54
  export async function writeScope(db, change) {
55
+ await writeScopeRows(db, change);
56
+ await reconcileEnableRequestsOf(db, { kind: change.kind, id: change.id }, null);
57
+ }
58
+ async function writeScopeRows(db, change) {
50
59
  const { kind, id, scope, orgs } = change;
51
60
  const updated_at = sql `now()`;
52
61
  if (kind === "plugin") {
@@ -135,6 +144,7 @@ let ScopeWriter = class ScopeWriter {
135
144
  .where("component_id", "=", change.id)
136
145
  .execute()).map((row) => row.org_id)
137
146
  : [];
147
+ // (writeScope re-checks the pending enable requests of the subject)
138
148
  await writeScope(db, change);
139
149
  if (change.kind === "connector_template") {
140
150
  await this.oweConnectorTemplate(change.id, { previousOrgs });
@@ -153,12 +163,23 @@ let ScopeWriter = class ScopeWriter {
153
163
  .execute();
154
164
  if (subject.kind === "connector_template")
155
165
  await this.oweConnectorTemplate(subject.id, {});
166
+ await reconcileEnableRequestsOf(this.kdb.db, subject, null);
156
167
  if ((subject.kind === "plugin" && disabled) || subject.kind === "connector_template") {
157
168
  this.refreshIsolatedOrgIntent();
158
169
  }
159
170
  }
160
- /** Store local intent under the caller's transaction and org lock. */
161
- async setOrgSwitch(subject, orgId, enabled, actor) {
171
+ /**
172
+ * Store local intent under the caller's transaction and org lock. The org's pending enable
173
+ * requests follow in the same transaction: switching a plugin or component on settles the
174
+ * requests that target it ({@link settleEnableRequests}); switching a plugin off cancels the
175
+ * requests for an extension or component that needed it on ({@link cancelEnableRequestsOfBundle}).
176
+ */
177
+ async setOrgSwitch(subject, orgId, enabled, actor,
178
+ /**
179
+ * The token and audit detail of the write, for the settled requests' audit; `settle: false`
180
+ * (an install failure recording the switch) leaves pending requests pending.
181
+ */
182
+ opts = {}) {
162
183
  const db = this.kdb.db;
163
184
  const values = { org_id: orgId, enabled, updated_by: actor };
164
185
  const update = { enabled, updated_by: actor, updated_at: sql `now()` };
@@ -187,12 +208,20 @@ let ScopeWriter = class ScopeWriter {
187
208
  .execute();
188
209
  }
189
210
  await oweEffectWork(this.outbox, db, { itemIds: [subject.id], orgId, previousOrgs: [orgId] });
211
+ if (enabled) {
212
+ await settleEnableRequests(db, orgId, { kind: "plugin", id: subject.id }, actor, opts);
213
+ }
214
+ else
215
+ await cancelEnableRequestsOfBundle(db, orgId, subject.id, actor);
190
216
  }
191
217
  else {
192
218
  await writeComponentSwitch(db, { kind: subject.kind, id: subject.id }, orgId, enabled, actor);
193
219
  if (subject.kind === "connector_template") {
194
220
  await this.oweConnectorTemplate(subject.id, { orgId, previousOrgs: [orgId] });
195
221
  }
222
+ if (enabled && subject.kind !== "theme") {
223
+ await settleEnableRequests(db, orgId, { kind: subject.kind, id: subject.id }, actor, opts);
224
+ }
196
225
  }
197
226
  if ((subject.kind === "plugin" && !enabled) || subject.kind === "connector_template") {
198
227
  this.refreshIsolatedOrgIntent(orgId);
@@ -175,6 +175,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
175
175
  stalledIntervalMs: z.ZodDefault<z.ZodNumber>;
176
176
  sseHeartbeatMs: z.ZodDefault<z.ZodNumber>;
177
177
  sseRecheckMs: z.ZodDefault<z.ZodNumber>;
178
+ meStreamMaxPerAccount: z.ZodDefault<z.ZodNumber>;
178
179
  }, z.core.$strict>>;
179
180
  tools: z.ZodDefault<z.ZodObject<{
180
181
  timeoutMs: z.ZodDefault<z.ZodNumber>;
@@ -984,6 +984,15 @@ export const KernelConfigSchema = z.strictObject({
984
984
  .meta(meta({
985
985
  description: "How often an open conversation event stream (SSE) re-checks that the viewer may still access the conversation, in milliseconds; the stream closes when access is lost",
986
986
  })),
987
+ meStreamMaxPerAccount: z
988
+ .number()
989
+ .int()
990
+ .positive()
991
+ .default(8)
992
+ .meta(meta({
993
+ hot: true,
994
+ description: "Maximum concurrent account invalidation streams (GET /api/v1/orgs/:orgId/me/stream) per account on one replica; a new stream over the limit closes that account's oldest stream on the replica",
995
+ })),
987
996
  })
988
997
  .default({
989
998
  maxSteps: 0,
@@ -998,6 +1007,7 @@ export const KernelConfigSchema = z.strictObject({
998
1007
  stalledIntervalMs: 30000,
999
1008
  sseHeartbeatMs: 15000,
1000
1009
  sseRecheckMs: 60000,
1010
+ meStreamMaxPerAccount: 8,
1001
1011
  }),
1002
1012
  tools: z
1003
1013
  .strictObject({
package/dist/ctx/bus.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { withoutEnableDecision } from "../catalog/enable-decision.js";
1
2
  import { withoutOrgScope } from "../infra/database/org-scope.js";
2
3
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
3
4
  import { withoutLogContext } from "../log-context.js";
@@ -25,11 +26,11 @@ export function createBusSubscriber(subFactory, log = consoleLog) {
25
26
  // the connection's callbacks carry the async context of the first subscribe (a request's
26
27
  // log fields and org scope, possibly an open transaction): every handler starts from an
27
28
  // empty one
28
- runOutsideTransaction(() => withoutOrgScope(() => withoutLogContext(() => {
29
+ runOutsideTransaction(() => withoutOrgScope(() => withoutEnableDecision(() => withoutLogContext(() => {
29
30
  for (const h of [...(channels.get(channel)?.handlers ?? [])]) {
30
31
  invokeIsolated(log, channel, () => h(message));
31
32
  }
32
- })));
33
+ }))));
33
34
  });
34
35
  c.on("error", (err) => log.error("bus subscriber connection error", { err }));
35
36
  conn = c;
@@ -2681,8 +2681,9 @@ export interface CatalogRequestsTable {
2681
2681
  /** 0077: what the request asks for (spec §5.1). */
2682
2682
  kind: ColumnType<CatalogRequestKindCol, CatalogRequestKindCol | undefined, CatalogRequestKindCol>;
2683
2683
  /**
2684
- * 0115: what a `network_allowlist` request asks for (`{ hosts, conversationId, agentId }`); null
2685
- * for other kinds.
2684
+ * 0115: what a `network_allowlist` request asks for (`{ hosts, conversationId, agentId }`); 0233:
2685
+ * an `enable` request's `{ target, subject, bundle?, cancelReason? }` (`EnableRequestDetail`);
2686
+ * null for other kinds.
2686
2687
  */
2687
2688
  detail: ColumnType<unknown | null, string | null | undefined, string | null>;
2688
2689
  /** 0085: the agent of a `connector_setup` request (cascades with the agent). */
package/dist/errors.d.ts CHANGED
@@ -298,6 +298,11 @@ export declare const ERROR_CODES: {
298
298
  readonly "catalog.request_pending": 409;
299
299
  /** The item is not in the state the request kind asks to change (already offered, on, ...). */
300
300
  readonly "catalog.request_invalid": 409;
301
+ /**
302
+ * An enable request's switch is no longer what its subject needs (on by another path, hidden,
303
+ * or another switch comes first): approving it cancelled it; the member asks again.
304
+ */
305
+ readonly "catalog.request_stale": 409;
301
306
  /** The deployment setting `orgMarketplaceBrowse` is off: no marketplace requests. */
302
307
  readonly "catalog.marketplace_browse_disabled": 409;
303
308
  readonly "catalog.custom_disabled": 403;
@@ -777,6 +782,8 @@ export declare const ERROR_CODES: {
777
782
  readonly "model.unconfigured": 409;
778
783
  readonly "model.purpose_unknown": 404;
779
784
  readonly "model.provider_not_found": 404;
785
+ /** No such model the org sees (unknown, not listed by its provider, or disabled by the platform). */
786
+ readonly "model.not_found": 404;
780
787
  /** An extension's `ctx.models.embed` call was denied by a `model.request` policy hook. */
781
788
  readonly "model.hook_denied": 403;
782
789
  readonly "model.budget_exceeded": 429;
package/dist/errors.js CHANGED
@@ -298,6 +298,11 @@ export const ERROR_CODES = {
298
298
  "catalog.request_pending": 409,
299
299
  /** The item is not in the state the request kind asks to change (already offered, on, ...). */
300
300
  "catalog.request_invalid": 409,
301
+ /**
302
+ * An enable request's switch is no longer what its subject needs (on by another path, hidden,
303
+ * or another switch comes first): approving it cancelled it; the member asks again.
304
+ */
305
+ "catalog.request_stale": 409,
301
306
  /** The deployment setting `orgMarketplaceBrowse` is off: no marketplace requests. */
302
307
  "catalog.marketplace_browse_disabled": 409,
303
308
  "catalog.custom_disabled": 403,
@@ -777,6 +782,8 @@ export const ERROR_CODES = {
777
782
  "model.unconfigured": 409,
778
783
  "model.purpose_unknown": 404,
779
784
  "model.provider_not_found": 404,
785
+ /** No such model the org sees (unknown, not listed by its provider, or disabled by the platform). */
786
+ "model.not_found": 404,
780
787
  /** An extension's `ctx.models.embed` call was denied by a `model.request` policy hook. */
781
788
  "model.hook_denied": 403,
782
789
  "model.budget_exceeded": 429,
@@ -610,6 +610,8 @@ function fallbackView(name, known, err) {
610
610
  scope: null,
611
611
  enabledOrgs: 0,
612
612
  builtin: false,
613
+ canonicalItemId: null,
614
+ sourceItemIds: [],
613
615
  installSource: null,
614
616
  uiDropped: [],
615
617
  client: null,
@@ -34,7 +34,7 @@ import { ExtensionPackageError, permissionSetOfPackage, readExtensionPackage } f
34
34
  import { buildPermissionSet, diffPermissions } from "./permission-set.js";
35
35
  import { deriveExtensionStatus, migrationWarnings, permissionGroups, permissionKeyItems, reviewHash, } from "./permission-view.js";
36
36
  import { PluginIcons } from "./plugin-icons.js";
37
- import { pluginItemsOf } from "./plugin-items.js";
37
+ import { pluginItemsOf, sourceFields } from "./plugin-items.js";
38
38
  import { parseProviderConflict } from "./resolve.js";
39
39
  import { SingleProviderGuard } from "./single-provider.js";
40
40
  export { PLUGINS_CHANGED_TOPIC };
@@ -424,6 +424,7 @@ let ExtensionAdmin = class ExtensionAdmin {
424
424
  : of[0].scope
425
425
  : null,
426
426
  builtin,
427
+ ...sourceFields(of ?? []),
427
428
  };
428
429
  const replicas = rows.filter((r) => r.plugin === s.name);
429
430
  const snap = snapshots.get(s.name);
@@ -1625,7 +1625,7 @@ let ExtensionHost = class ExtensionHost {
1625
1625
  const report = `${level}:${detail}`;
1626
1626
  if (this.configReported.get(name) !== report) {
1627
1627
  this.configReported.set(name, report);
1628
- const next = "set it in Admin → Extensions or the startup config; it loads without a restart";
1628
+ const next = "set it on its Extension tab in Admin → Plugins or in the startup config; it loads without a restart";
1629
1629
  this.log[level](unconfigured
1630
1630
  ? `optional preinstalled extension is waiting for deployment config (${next})`
1631
1631
  : `extension not loaded: its deployment config is missing or invalid (${next})`, { plugin: name, source: a.source, detail });
@@ -58,6 +58,14 @@ export interface OrgExtensionView {
58
58
  switchable: boolean;
59
59
  /** Effective intent of the plugin whose switch this extension follows, or null without one. */
60
60
  pluginUsable: boolean | null;
61
+ /**
62
+ * The catalog item whose detail owns the extension's tab on the org's Plugins surface: its one
63
+ * live source item the org can see (builtin included). Null without one (declared in the startup
64
+ * config) or with several (the extension then has its own page, which each source links to).
65
+ */
66
+ canonicalItemId: string | null;
67
+ /** The live source items of the extension the org can see (`extension_catalog_sources`), by id. */
68
+ sourceItemIds: string[];
61
69
  /**
62
70
  * The two-level deployment config (spec A §5.3, §5.4): `following` the platform, a `copy` of the
63
71
  * overridable fields, or `none` (the extension has no overridable field, or is unavailable).
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { EXTENSION_POINTS, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
+ import { cancelEnableRequestsOfProvider, settleEnableRequests, } from "../catalog/enable-requests.js";
12
13
  import { orgUsable } from "../catalog/org-intent.js";
13
14
  import { assertItemInstallable, assertPluginSourcesInstallable, disabledPluginItems, pluginItemDisabled, } from "../catalog/request-rules.js";
14
15
  import { itemsSeenBy, pluginUsable } from "../catalog/scope-state.js";
@@ -32,7 +33,7 @@ import { ExtensionInstalls } from "./installs.js";
32
33
  import { PluginInstallLock } from "./locks.js";
33
34
  import { fieldLevels } from "./org-levels.js";
34
35
  import { permissionGroups, } from "./permission-view.js";
35
- import { itemLocked, pluginItemsOf, pluginPathItem, } from "./plugin-items.js";
36
+ import { itemLocked, pluginItemsOf, pluginPathItem, sourceFields, } from "./plugin-items.js";
36
37
  import { ExtensionAvailability } from "./unavailable.js";
37
38
  /** The management list shows extensions whose bundle is usable or that are independently enabled. */
38
39
  export function listedInOrg(view) {
@@ -48,13 +49,16 @@ export function providesOf(view) {
48
49
  * not (layering spec §4).
49
50
  */
50
51
  function scopeFields(items, required, seen) {
51
- const primary = items?.find((item) => seen === undefined || seen.has(item.id));
52
+ const visible = (items ?? []).filter((item) => seen === undefined || seen.has(item.id));
53
+ const primary = visible[0];
52
54
  const locked = required || items?.some(itemLocked) === true;
55
+ const sources = sourceFields(visible);
53
56
  if (!primary)
54
- return { catalogItem: null, switchable: !locked };
57
+ return { catalogItem: null, switchable: !locked, ...sources };
55
58
  return {
56
59
  catalogItem: { itemId: primary.id, scope: locked ? "all" : primary.scope },
57
60
  switchable: !locked,
61
+ ...sources,
58
62
  };
59
63
  }
60
64
  /**
@@ -268,6 +272,10 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
268
272
  const required = (await requiredExtensions(t)).has(plugin);
269
273
  const locked = required || (await alwaysOnExtensions(t)).has(plugin);
270
274
  const item = (await pluginItemsOf(t, [plugin])).get(plugin);
275
+ // The answer's source fields follow the org's view, as the list's do
276
+ const seen = item === undefined
277
+ ? undefined
278
+ : await itemsSeenBy(t, orgId, item.map((i) => i.id), "offered");
271
279
  const before = await isExtensionEnabled(t, orgId, plugin);
272
280
  if (required && input.enabled === false)
273
281
  throw requiredError(plugin);
@@ -275,7 +283,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
275
283
  throw scopeLockedError();
276
284
  const pathItem = pluginPathItem(item, required);
277
285
  const bundleUsable = pathItem === null ? null : await pluginUsable(t, orgId, pathItem);
278
- const snapshot = () => this.view(manifest, before, required, item, bundleUsable);
286
+ const snapshot = () => this.view(manifest, before, required, item, bundleUsable, seen);
279
287
  if (opts.viaItem !== undefined) {
280
288
  // A bundle applies effects. The org's extension choice belongs to its own switch.
281
289
  if (locked || pathItem !== opts.viaItem || row?.enabled === false) {
@@ -302,6 +310,9 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
302
310
  const enabled = await isExtensionEnabled(t, orgId, plugin);
303
311
  if (!enabled) {
304
312
  await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
313
+ // a model provider switched off: requests for its models need the extension first now
314
+ if (before)
315
+ await cancelEnableRequestsOfProvider(t, orgId, plugin, actorAccountId);
305
316
  // its host services on the org's machines stop (local agents spec, call 5)
306
317
  await oweHostServicesStop(t, this.outbox, { orgId, extension: plugin });
307
318
  }
@@ -310,6 +321,10 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
310
321
  // extension is loaded there (ruling R27)
311
322
  if (enabled && !before) {
312
323
  await oweTemplateConnectors(this.outbox, t, orgId);
324
+ // the org's pending enable requests for this extension are settled with the write
325
+ await settleEnableRequests(t, orgId, { kind: "extension", id: plugin }, actorAccountId, {
326
+ ...(actorTokenId !== undefined && { actorTokenId }),
327
+ });
313
328
  }
314
329
  await audit(t, {
315
330
  actorAccountId,
@@ -323,7 +338,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
323
338
  ...opts.auditDetail,
324
339
  },
325
340
  });
326
- const view = this.view(manifest, enabled, required, item, bundleUsable);
341
+ const view = this.view(manifest, enabled, required, item, bundleUsable, seen);
327
342
  // Only once the root transaction committed (an outer caller's too): a rolled-back write
328
343
  // disconnects nothing
329
344
  afterCommit(async () => {
@@ -152,6 +152,13 @@ export interface AdminExtensionView {
152
152
  enabledOrgs?: number;
153
153
  /** Shipped with the deployment (a builtin plugin or a required bootstrap plugin). */
154
154
  builtin: boolean;
155
+ /**
156
+ * The catalog item whose detail owns the extension's tab on the platform's Plugins surface: its
157
+ * one live source item; null without one (declared in the startup config) or with several.
158
+ */
159
+ canonicalItemId: string | null;
160
+ /** Every live source item of the extension (`extension_catalog_sources`), by id. */
161
+ sourceItemIds: string[];
155
162
  /** Where the install record came from (`bootstrap` for the bootstrap step); null for config-declared. */
156
163
  installSource: "npm" | "file" | "catalog" | "bootstrap" | null;
157
164
  /**
@@ -289,7 +289,7 @@ export declare class PluginGuides {
289
289
  }): Promise<RenderedSetupGuide>;
290
290
  /**
291
291
  * The `extension-deployment` guides of an extension, rendered for the platform (the super
292
- * admin's extension page, `GET /admin/extensions/:name/guides`): the guides of that place in the
292
+ * admin's Extension tab, `GET /admin/extensions/:name/guides`): the guides of that place in the
293
293
  * latest version of the catalog item of the same name, admin audience, no org and no target.
294
294
  * None when the extension has no catalog item; a guide that cannot be rendered is left out and
295
295
  * logged.
@@ -491,7 +491,7 @@ let PluginGuides = PluginGuides_1 = class PluginGuides {
491
491
  }
492
492
  /**
493
493
  * The `extension-deployment` guides of an extension, rendered for the platform (the super
494
- * admin's extension page, `GET /admin/extensions/:name/guides`): the guides of that place in the
494
+ * admin's Extension tab, `GET /admin/extensions/:name/guides`): the guides of that place in the
495
495
  * latest version of the catalog item of the same name, admin audience, no org and no target.
496
496
  * None when the extension has no catalog item; a guide that cannot be rendered is left out and
497
497
  * logged.
@@ -35,3 +35,11 @@ export declare const itemLocked: (i: ExtensionPluginItem) => boolean;
35
35
  * org (extension switch spec 2026-12-02 §3.1).
36
36
  */
37
37
  export declare function pluginPathItem(items: readonly ExtensionPluginItem[] | undefined, required: boolean): string | null;
38
+ /**
39
+ * The source fields of an extension view from its live source items the viewer can see: the
40
+ * canonical item when there is exactly one, and every source id (sorted).
41
+ */
42
+ export declare function sourceFields(visible: readonly Pick<ExtensionPluginItem, "id">[]): {
43
+ canonicalItemId: string | null;
44
+ sourceItemIds: string[];
45
+ };
@@ -62,3 +62,11 @@ export function pluginPathItem(items, required) {
62
62
  const [only] = items;
63
63
  return only === undefined || itemLocked(only) ? null : only.id;
64
64
  }
65
+ /**
66
+ * The source fields of an extension view from its live source items the viewer can see: the
67
+ * canonical item when there is exactly one, and every source id (sorted).
68
+ */
69
+ export function sourceFields(visible) {
70
+ const ids = [...new Set(visible.map((item) => item.id))].sort();
71
+ return { canonicalItemId: ids.length === 1 ? (ids[0] ?? null) : null, sourceItemIds: ids };
72
+ }
@@ -78,6 +78,8 @@ import { InboxModule } from "../inbox/inbox.module.js";
78
78
  import { InboxItemsController } from "../inbox/inbox-items.controller.js";
79
79
  import { PlatformInboxController } from "../inbox/platform-inbox.controller.js";
80
80
  import { PrincipalThrottlerGuard } from "../infra/throttler/principal-throttler.guard.js";
81
+ import { MeStreamController } from "../invalidation/me-stream.controller.js";
82
+ import { MeStreamModule } from "../invalidation/me-stream.module.js";
81
83
  import { ModelEnablementController } from "../models/enablement.controller.js";
82
84
  import { ModelsModule } from "../models/models.module.js";
83
85
  import { ModelPurposesController } from "../models/purposes.controller.js";
@@ -177,6 +179,8 @@ const CONTROLLERS = [
177
179
  InboxController,
178
180
  InboxItemsController,
179
181
  PlatformInboxController,
182
+ // the account invalidation stream (inbox, request and capability hints)
183
+ MeStreamController,
180
184
  ConversationStreamController,
181
185
  ConnectorContentController,
182
186
  ConnectorsController,
@@ -265,6 +269,8 @@ ApiModule = __decorate([
265
269
  LibraryReadModule,
266
270
  UiModule,
267
271
  InboxModule,
272
+ // the account invalidation streams (me/stream): api role only
273
+ MeStreamModule,
268
274
  ThemesModule,
269
275
  ClientModule,
270
276
  SetupModule,
@@ -25,6 +25,8 @@ const HOT_APPLIERS = {
25
25
  "log.level": (k, v) => k.log.setLevel(String(v)),
26
26
  // The runtime reads the concurrency cap through the config service on every quota request.
27
27
  "runtime.orgConcurrency": () => { },
28
+ // MeStreams reads the per-account stream cap at every stream open.
29
+ "runtime.meStreamMaxPerAccount": () => { },
28
30
  // Eval org concurrency is read the same way at every quota request.
29
31
  "evals.orgConcurrency": () => { },
30
32
  // The git gateway reads tools.git.enabled through the config service on every request.
@@ -1,3 +1,4 @@
1
+ import { withoutEnableDecision } from "../../catalog/enable-decision.js";
1
2
  import { withJobContext } from "../../log-context.js";
2
3
  import { asPlatform, withOrgScope, withoutOrgScope } from "../database/org-scope.js";
3
4
  import { runOutsideTransaction } from "../database/transaction-host.js";
@@ -21,7 +22,8 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
21
22
  * ```
22
23
  */
23
24
  export function runJob(queue, job, fn, opts = {}) {
24
- const run = () => withJobContext(queue, job, fn);
25
+ // a job never inherits an admin's in-flight request decision (catalog/enable-decision.ts)
26
+ const run = () => withoutEnableDecision(() => withJobContext(queue, job, fn));
25
27
  return runOutsideTransaction(() => {
26
28
  if (opts.scope !== undefined) {
27
29
  if (opts.scope?.kind === "org")
@@ -0,0 +1,56 @@
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
+ /** The role topics a member with `role` listens to: every one at or below it (guest: none). */
41
+ export declare function roleTopicRoles(role: OrgRole): TopicRole[];
42
+ /**
43
+ * The identity a stream's topics come from, all of it verified by the kernel: the principal's
44
+ * account id, its membership role in the stream's org (read from PG after the org guard) and its
45
+ * super admin flag. Nothing from the request (query, headers, body, `Last-Event-ID`) goes here.
46
+ */
47
+ export interface StreamIdentity {
48
+ accountId: string;
49
+ orgId: string;
50
+ role: OrgRole;
51
+ superAdmin: boolean;
52
+ }
53
+ /** The topics a stream of `id` subscribes to (spec §5 "Subscriptions"). */
54
+ export declare function streamTopics(id: StreamIdentity): InvalidationTopic[];
55
+ /** The SSE frame of a hint: `event: hint`, data the hint's JSON (its kind only). */
56
+ export declare const hintFrame: (h: Hint) => string;
@@ -0,0 +1,67 @@
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
+ /** The role topics a member with `role` listens to: every one at or below it (guest: none). */
50
+ export function roleTopicRoles(role) {
51
+ return TOPIC_ROLES.filter((r) => roleAtLeast(role, r));
52
+ }
53
+ /** The topics a stream of `id` subscribes to (spec §5 "Subscriptions"). */
54
+ export function streamTopics(id) {
55
+ if (!ORG_ROLES.includes(id.role))
56
+ throw new Error("invalid org role");
57
+ const topics = [acctTopic(id.accountId)];
58
+ for (const r of roleTopicRoles(id.role))
59
+ topics.push(orgRoleTopic(id.orgId, r));
60
+ if (roleAtLeast(id.role, "member"))
61
+ topics.push(orgCapsTopic(id.orgId));
62
+ if (id.superAdmin)
63
+ topics.push(PLATFORM_ADMINS_TOPIC);
64
+ return topics;
65
+ }
66
+ /** The SSE frame of a hint: `event: hint`, data the hint's JSON (its kind only). */
67
+ export const hintFrame = (h) => `event: hint\ndata: ${JSON.stringify({ kind: h.kind })}\n\n`;
@@ -0,0 +1,24 @@
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
+ */
10
+ export declare class InvalidationHints {
11
+ private readonly bus;
12
+ private readonly log;
13
+ constructor(bus: Pick<ExtensionContext["bus"], "publish">, log: Pick<Logger, "warn">);
14
+ /**
15
+ * Publishes `hint` on every topic now. The hint is validated first (kind only: an extra field
16
+ * throws, a programming error); bus failures are logged and never thrown.
17
+ */
18
+ publish(topics: readonly InvalidationTopic[], hint: Hint): Promise<void>;
19
+ /**
20
+ * Publishes `hint` after the root transaction commits (at once outside a transaction); a
21
+ * rollback drops it. The hint is validated now, so a bad hint fails the caller, not the hook.
22
+ */
23
+ publishAfterCommit(topics: readonly InvalidationTopic[], hint: Hint): void;
24
+ }