@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
@@ -1,8 +1,10 @@
1
1
  import type { LocalizedName } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
+ import { type RequestableFields } from "../catalog/enable-requests.js";
3
4
  import { ExtensionDisplayNames } from "../extensions/display-name.js";
4
5
  import { PluginIcons } from "../extensions/plugin-icons.js";
5
6
  import { type Principal } from "../identity/principal.js";
7
+ import { ModelEnablement } from "../models/enablement.js";
6
8
  import { type OrgContext } from "../orgs/org.guard.js";
7
9
  import { type KernelModelInfo, type OrgProviderState, ProviderRegistry, type ProviderStatus } from "../runtime/providers.js";
8
10
  export declare const ModelsQuery: z.ZodObject<{
@@ -22,19 +24,24 @@ export declare const ModelsQuery: z.ZodObject<{
22
24
  * carries its extension's display name (null when it has none). Listed for the org (its effective
23
25
  * provider config: a provider needing configuration there is absent); only enabled models (neither
24
26
  * the platform nor the org disabled them, spec B §5.3), optionally of one `?kind=`; every model
25
- * carries its normalised `kind` (`other` for a kind this kernel does not know).
27
+ * carries its normalised `kind` (`other` for a kind this kernel does not know). Each provider also
28
+ * lists `requestableModels`: the models of that kind the org disabled whose owning switch the
29
+ * reader may ask an org admin to turn on ("Ask to turn on", org-usable spec), each with
30
+ * `requestable: true` and the org's pending request (`pendingRequestId`); never selectable.
26
31
  */
27
32
  export declare class ModelsController {
28
33
  private readonly registry;
29
34
  private readonly displayNames;
30
35
  private readonly icons;
31
- constructor(registry: ProviderRegistry, displayNames: ExtensionDisplayNames, icons: PluginIcons);
36
+ private readonly enablement;
37
+ constructor(registry: ProviderRegistry, displayNames: ExtensionDisplayNames, icons: PluginIcons, enablement: ModelEnablement);
32
38
  list(org: OrgContext, q: z.infer<typeof ModelsQuery>): Promise<{
33
39
  providers: {
34
40
  provider: string;
35
41
  displayName: LocalizedName | null;
36
42
  icon: string | null;
37
43
  models: KernelModelInfo[];
44
+ requestableModels: (KernelModelInfo & RequestableFields)[];
38
45
  }[];
39
46
  }>;
40
47
  /**
@@ -9,12 +9,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Controller, Get, Inject } from "@nestjs/common";
11
11
  import { z } from "zod";
12
+ import { modelListingOf } from "../catalog/enable-requests.js";
12
13
  import { ExtensionDisplayNames } from "../extensions/display-name.js";
13
14
  import { orgIconScope, PluginIcons } from "../extensions/plugin-icons.js";
14
15
  import { CurrentPrincipal, requireUser } from "../identity/principal.js";
15
16
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
16
17
  import { ZQuery } from "../infra/validation/zod-params.js";
18
+ import { ModelEnablement, modelKey } from "../models/enablement.js";
17
19
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
20
+ import { can } from "../orgs/roles.js";
18
21
  import { ProviderRegistry, } from "../runtime/providers.js";
19
22
  export const ModelsQuery = z.object({
20
23
  kind: z
@@ -37,19 +40,42 @@ class ModelsQueryDto extends createZodDto(ModelsQuery, "ModelsQuery") {
37
40
  * carries its extension's display name (null when it has none). Listed for the org (its effective
38
41
  * provider config: a provider needing configuration there is absent); only enabled models (neither
39
42
  * the platform nor the org disabled them, spec B §5.3), optionally of one `?kind=`; every model
40
- * carries its normalised `kind` (`other` for a kind this kernel does not know).
43
+ * carries its normalised `kind` (`other` for a kind this kernel does not know). Each provider also
44
+ * lists `requestableModels`: the models of that kind the org disabled whose owning switch the
45
+ * reader may ask an org admin to turn on ("Ask to turn on", org-usable spec), each with
46
+ * `requestable: true` and the org's pending request (`pendingRequestId`); never selectable.
41
47
  */
42
48
  let ModelsController = class ModelsController {
43
49
  registry;
44
50
  displayNames;
45
51
  icons;
46
- constructor(registry, displayNames, icons) {
52
+ enablement;
53
+ constructor(registry, displayNames, icons, enablement) {
47
54
  this.registry = registry;
48
55
  this.displayNames = displayNames;
49
56
  this.icons = icons;
57
+ this.enablement = enablement;
50
58
  }
51
59
  async list(org, q) {
52
- const providers = await this.registry.list(org.orgId, q.kind === undefined ? {} : { kind: q.kind });
60
+ // One catalog read (the providers' cached lists): the enabled models are the selectable set
61
+ // (what `ProviderRegistry.list` returns), the ones the org disabled the picker's request
62
+ // entries (only for a reader who may request: guests never see them)
63
+ const catalog = await this.registry.catalog(org.orgId);
64
+ const ofKind = (m) => q.kind === undefined || m.kind === q.kind;
65
+ const providers = catalog
66
+ .filter((p) => p.status === "ok")
67
+ .map((p) => ({
68
+ provider: p.provider,
69
+ models: p.models
70
+ .filter((m) => m.disabled !== true && ofKind(m))
71
+ .map(({ disabled: _d, ...m }) => m),
72
+ off: p.models
73
+ .filter((m) => m.disabled === true && ofKind(m))
74
+ .map(({ disabled: _d, ...m }) => m),
75
+ }));
76
+ const fields = can(org.role, "catalog.request")
77
+ ? await this.enablement.requestable(org.orgId, org.role, providers.flatMap((p) => p.off.map((m) => ({ provider: p.provider, model: m.id }))), modelListingOf(catalog))
78
+ : new Map();
53
79
  const plugins = providers.map((p) => p.provider);
54
80
  const [names, icons] = await Promise.all([
55
81
  this.displayNames.many(plugins),
@@ -61,6 +87,10 @@ let ModelsController = class ModelsController {
61
87
  displayName: names.get(p.provider) ?? null,
62
88
  icon: icons.get(p.provider) ?? null,
63
89
  models: p.models,
90
+ requestableModels: p.off.flatMap((m) => {
91
+ const f = fields.get(modelKey(p.provider, m.id));
92
+ return f === undefined ? [] : [{ ...m, ...f }];
93
+ }),
64
94
  })),
65
95
  };
66
96
  }
@@ -102,6 +132,7 @@ ModelsController = __decorate([
102
132
  Controller("api/v1/orgs/:orgId/models"),
103
133
  __param(0, Inject(ProviderRegistry)),
104
134
  __param(1, Inject(ExtensionDisplayNames)),
105
- __param(2, Inject(PluginIcons))
135
+ __param(2, Inject(PluginIcons)),
136
+ __param(3, Inject(ModelEnablement))
106
137
  ], ModelsController);
107
138
  export { ModelsController };
@@ -24,6 +24,7 @@ import { CatalogService } from "./catalog.service.js";
24
24
  import { assertOrgsExist } from "./catalog-items.js";
25
25
  import { nameConflictError } from "./component-scope.service.js";
26
26
  import { agentsUsing, COMPONENT_KINDS, componentOffered, componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, skillNameClashes, switchOf, themeIdClashes, } from "./component-state.js";
27
+ import { reconcileEnableRequestsOf } from "./enable-requests.js";
27
28
  import { orgUsable } from "./org-intent.js";
28
29
  import { assertOwnerListed, assertShareable, assertShareableTarget, newlySharedWith, } from "./ownership.js";
29
30
  import { PluginImport } from "./plugin-import.js";
@@ -367,6 +368,8 @@ let CatalogScopeService = class CatalogScopeService {
367
368
  await narrowComponentOnUnshare(this.db, actor, c);
368
369
  }
369
370
  }
371
+ // other orgs' pending enable requests for it (the share gate hides it from them now)
372
+ await reconcileEnableRequestsOf(this.db, { kind: "plugin", id: itemId }, actor);
370
373
  if (narrowed)
371
374
  await this.enqueue(itemId);
372
375
  this.scopeWriter.refreshIsolatedOrgIntent();
@@ -6,11 +6,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
6
6
  };
7
7
  import { Module } from "@nestjs/common";
8
8
  import { ExtensionsModule } from "../extensions/extensions.module.js";
9
+ import { ExtensionRegistryModule } from "../extensions/registry.js";
9
10
  import { SuperAdminLockModule } from "../identity/super-admin.js";
10
11
  import { QueueModule } from "../infra/queue/queue.module.js";
12
+ import { ModelEnablementModule } from "../models/enablement.js";
11
13
  import { OrgLockModule } from "../orgs/org-lock.js";
12
14
  import { OrgSettingsModule } from "../orgs/settings.service.js";
13
15
  import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
16
+ import { ProvidersModule } from "../runtime/providers.js";
14
17
  import { SkillsModule } from "../skills/skills.module.js";
15
18
  import { StorageModule } from "../storage/storage.module.js";
16
19
  import { ToolsModule } from "../tools/tools.module.js";
@@ -56,6 +59,11 @@ CatalogModule = __decorate([
56
59
  StorageModule,
57
60
  SkillsModule,
58
61
  ToolsModule,
62
+ // an approved point-of-use enable request writes an org's model list; a request for a model
63
+ // is checked against the provider's list, one for an extension against the loaded ones
64
+ ModelEnablementModule,
65
+ ProvidersModule,
66
+ ExtensionRegistryModule,
59
67
  // the plugin scope sync's queue: the outbox dispatcher adds the owed jobs through it
60
68
  // (`PluginScopeWorkersModule` consumes it)
61
69
  PLUGIN_EFFECT_QUEUE_MODULE,
@@ -355,9 +355,9 @@ export declare class CatalogService {
355
355
  * them), its themes are soft-deleted (nothing refers to their rows), organizations no longer see
356
356
  * it; the same name can later be imported again as a new item. Deleted / missing -> `catalog.item_not_found`. A platform plugin whose extension is
357
357
  * still enabled on the deployment -> 409 `catalog.extension_enabled` (details
358
- * `[{ extension, displayName }]`): disable it on the Extensions page first, as an uninstall
358
+ * `[{ extension, displayName }]`): turn it off on the plugin's Extension tab first, as an uninstall
359
359
  * requires. A disabled extension keeps its install record (the super admin uninstalls it on the
360
- * Extensions page); an org-owned item's extension is taken out by `OwnedPluginCleanup`, the job
360
+ * Extension tab); an org-owned item's extension is taken out by `OwnedPluginCleanup`, the job
361
361
  * the removal owes ({@link removeIn}).
362
362
  */
363
363
  remove(actor: string, itemId: string, opts?: ActorOpts): Promise<void>;
@@ -517,9 +517,9 @@ let CatalogService = class CatalogService {
517
517
  * them), its themes are soft-deleted (nothing refers to their rows), organizations no longer see
518
518
  * it; the same name can later be imported again as a new item. Deleted / missing -> `catalog.item_not_found`. A platform plugin whose extension is
519
519
  * still enabled on the deployment -> 409 `catalog.extension_enabled` (details
520
- * `[{ extension, displayName }]`): disable it on the Extensions page first, as an uninstall
520
+ * `[{ extension, displayName }]`): turn it off on the plugin's Extension tab first, as an uninstall
521
521
  * requires. A disabled extension keeps its install record (the super admin uninstalls it on the
522
- * Extensions page); an org-owned item's extension is taken out by `OwnedPluginCleanup`, the job
522
+ * Extension tab); an org-owned item's extension is taken out by `OwnedPluginCleanup`, the job
523
523
  * the removal owes ({@link removeIn}).
524
524
  */
525
525
  async remove(actor, itemId, opts = {}) {
@@ -605,7 +605,7 @@ let CatalogService = class CatalogService {
605
605
  return;
606
606
  if (item.package_name !== null && install.package_name !== item.package_name)
607
607
  return;
608
- throw new ApiError("catalog.extension_enabled", `The extension "${item.name}" of this plugin is enabled on the deployment; disable it on the Extensions page first, then delete the plugin`, [{ extension: item.name, displayName: item.display_name ?? null }]);
608
+ throw new ApiError("catalog.extension_enabled", `The extension "${item.name}" of this plugin is enabled on the deployment; turn it off on the plugin's Extension tab first, then delete the plugin`, [{ extension: item.name, displayName: item.display_name ?? null }]);
609
609
  }
610
610
  /**
611
611
  * The soft delete of {@link remove} in the caller's transaction, without its super admin check
@@ -81,7 +81,8 @@ export declare class OrgComponentsController {
81
81
  * admin may switch it. Members read it (the workspace pages are read-only for them). Each has
82
82
  * its display name and `icon`, a connector template's own icon, else its plugin's, on the org's
83
83
  * routes (null without one, or when the org's catalog does not show the plugin to the reader:
84
- * the share gate holds).
84
+ * the share gate holds). An entry that is off and that the reader may ask an org admin to turn on
85
+ * carries `requestable: true` and `pendingRequestId` (`withRequestable`).
85
86
  */
86
87
  list(org: OrgContext, q: z.infer<typeof OrgComponentListQuery>): Promise<{
87
88
  components: (OrgOfferedComponentView & {
@@ -223,14 +223,17 @@ let OrgComponentsController = class OrgComponentsController {
223
223
  * admin may switch it. Members read it (the workspace pages are read-only for them). Each has
224
224
  * its display name and `icon`, a connector template's own icon, else its plugin's, on the org's
225
225
  * routes (null without one, or when the org's catalog does not show the plugin to the reader:
226
- * the share gate holds).
226
+ * the share gate holds). An entry that is off and that the reader may ask an org admin to turn on
227
+ * carries `requestable: true` and `pendingRequestId` (`withRequestable`).
227
228
  */
228
229
  async list(org, q) {
229
230
  const rows = await this.scope.orgList(org.orgId, {
230
231
  ...(q.kind !== undefined && { kind: q.kind }),
231
232
  ...(q.itemId !== undefined && { itemId: q.itemId }),
232
233
  });
233
- return { components: await withIcons(this.icons, rows, orgIconScope(org)) };
234
+ // the agent-template picker's "Ask to turn on" entries (org-usable spec)
235
+ const projected = await this.scope.withRequestable(org.orgId, org.role, rows);
236
+ return { components: await withIcons(this.icons, projected, orgIconScope(org)) };
234
237
  }
235
238
  async setSwitch(principal, org, p, body) {
236
239
  const actor = requireUser(principal);
@@ -5,6 +5,7 @@ import { SuperAdminLock } from "../identity/super-admin.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
7
  import { OrgLock } from "../orgs/org-lock.js";
8
+ import type { OrgRole } from "../orgs/roles.js";
8
9
  import { type ThemeSwatch } from "../themes/theme-state.js";
9
10
  import { type ThemePreview } from "../themes/theme-usage.js";
10
11
  import type { ActorOpts } from "./catalog.service.js";
@@ -187,6 +188,13 @@ export interface OrgOfferedComponentView extends OrgComponentView {
187
188
  itemId: string;
188
189
  guideId: string;
189
190
  } | null;
191
+ /**
192
+ * Off in the org, and the reader may ask an org admin to turn it on ("Ask to turn on", org-usable
193
+ * spec): set only then, with the org's pending request for its owning switch (the component's
194
+ * switch or its plugin) or null. Absent for an entry that is on, locked, or not requestable.
195
+ */
196
+ requestable?: true;
197
+ pendingRequestId?: string | null;
190
198
  }
191
199
  /** The result of an org switch: the component, or (switching off without `confirm`) the preview. */
192
200
  export type ComponentSwitchResult = {
@@ -282,6 +290,14 @@ export declare class ComponentScopeService {
282
290
  kind?: ComponentKind;
283
291
  itemId?: string;
284
292
  }): Promise<OrgOfferedComponentView[]>;
293
+ /**
294
+ * The picker projection of {@link orgList}'s rows for a reader of `role` (org-usable spec
295
+ * "Members and guests"): each skill, agent template or connector template that is off, not
296
+ * locked, and whose owning switch the reader may ask an org admin to turn on gets
297
+ * `requestable: true` and the org's pending request for that switch. The selectable set (`on`)
298
+ * is unchanged.
299
+ */
300
+ withRequestable<T extends OrgOfferedComponentView>(orgId: string, role: OrgRole, rows: T[]): Promise<T[]>;
285
301
  /**
286
302
  * The org's copies of platform skills or agent templates linked without a pin (ruling B2), by
287
303
  * platform id: they resolve to it, so agents that select them use it (none for connector
@@ -25,6 +25,8 @@ import { assertNotPlatformDefault, platformDefaultThemeId, themesPreview, } from
25
25
  import { assertOrgsExist } from "./catalog-items.js";
26
26
  import { ComponentPromotion, notOwnedError, PROMOTION_ATTEMPTS, PromotionStale, promotionStaleError, } from "./component-promotion.js";
27
27
  import { agentsUsing, COMPONENT_KINDS, componentLocked, componentOffered, componentOn, componentPluginOn, connectorsMadeFrom, listedIn, loadComponents, loadScopeState, pluginFactsOf, skillNameClashes, switchOf, themeIdClashes, } from "./component-state.js";
28
+ import { requestableSubjects } from "./enable-requests.js";
29
+ import { targetKey } from "./enable-targets.js";
28
30
  import { assertOwnerListed, assertShareable, assertShareableTarget, newlySharedWith, ownerOf, ownersOf, } from "./ownership.js";
29
31
  import { PluginInstaller } from "./plugin-install.js";
30
32
  import { assertScopePreview, COMPONENT_SCOPE_TABLE, ScopeWriter } from "./scope-writer.js";
@@ -298,6 +300,21 @@ let ComponentScopeService = class ComponentScopeService {
298
300
  }
299
301
  return out;
300
302
  }
303
+ /**
304
+ * The picker projection of {@link orgList}'s rows for a reader of `role` (org-usable spec
305
+ * "Members and guests"): each skill, agent template or connector template that is off, not
306
+ * locked, and whose owning switch the reader may ask an org admin to turn on gets
307
+ * `requestable: true` and the org's pending request for that switch. The selectable set (`on`)
308
+ * is unchanged.
309
+ */
310
+ async withRequestable(orgId, role, rows) {
311
+ const subjects = rows.flatMap((r) => !r.on && !r.locked && r.kind !== "theme" ? [{ kind: r.kind, id: r.id }] : []);
312
+ const fields = await requestableSubjects(this.db, orgId, role, subjects);
313
+ return rows.map((r) => {
314
+ const f = r.kind === "theme" ? undefined : fields.get(targetKey({ kind: r.kind, id: r.id }));
315
+ return f === undefined ? r : { ...r, ...f };
316
+ });
317
+ }
301
318
  /**
302
319
  * The org's copies of platform skills or agent templates linked without a pin (ruling B2), by
303
320
  * platform id: they resolve to it, so agents that select them use it (none for connector
@@ -564,7 +581,10 @@ let ComponentScopeService = class ComponentScopeService {
564
581
  }
565
582
  }
566
583
  if (sw !== body.enabled) {
567
- await this.scopeWriter.setOrgSwitch({ kind, id: c.id }, orgId, body.enabled, actor);
584
+ await this.scopeWriter.setOrgSwitch({ kind, id: c.id }, orgId, body.enabled, actor, {
585
+ ...(actorTokenId !== undefined && { actorTokenId }),
586
+ ...(auditDetail !== undefined && { auditDetail }),
587
+ });
568
588
  await audit(this.db, {
569
589
  actorAccountId: actor,
570
590
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -0,0 +1,34 @@
1
+ import type { EnableTarget } from "./enable-targets.js";
2
+ /**
3
+ * The org admin's approval of one enable request while it calls the target's switch writer
4
+ * (org-usable spec "Members and guests": the decision commits with the switch write). The writer
5
+ * settles the org's pending requests for the target in its own transaction
6
+ * (`settleEnableRequests`); with a decision in scope that settlement re-checks the decided
7
+ * request is still pending under a row lock and decides it there, so a concurrent reject or a
8
+ * second approval can never leave the target on with another outcome recorded. The caller reads
9
+ * the committed row afterwards (a rolled-back write leaves it pending). Scoped to one call chain
10
+ * (AsyncLocalStorage), never shared between requests or replicas; job and bus boundaries clear it
11
+ * ({@link withoutEnableDecision}).
12
+ */
13
+ export interface EnableDecision {
14
+ orgId: string;
15
+ requestId: string;
16
+ target: EnableTarget;
17
+ actor: string;
18
+ actorTokenId?: string | undefined;
19
+ auditDetail?: Record<string, unknown> | undefined;
20
+ /**
21
+ * Set when a settlement decided the request in the writer's transaction. Only meaningful with
22
+ * the committed row: a rolled-back transaction leaves the row pending whatever this says.
23
+ */
24
+ settled?: boolean;
25
+ }
26
+ /** Runs `fn` (the switch writer call) with `decision` in scope. */
27
+ export declare function withEnableDecision<T>(decision: EnableDecision, fn: () => Promise<T>): Promise<T>;
28
+ /** The approval in scope, if any. */
29
+ export declare function currentEnableDecision(): EnableDecision | undefined;
30
+ /**
31
+ * Runs `fn` with no approval in scope: work that outlives or is detached from the call that
32
+ * started it (a queue job, a bus delivery) never settles a request as an admin's decision.
33
+ */
34
+ export declare function withoutEnableDecision<T>(fn: () => T): T;
@@ -0,0 +1,17 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const storage = new AsyncLocalStorage();
3
+ /** Runs `fn` (the switch writer call) with `decision` in scope. */
4
+ export function withEnableDecision(decision, fn) {
5
+ return storage.run(decision, fn);
6
+ }
7
+ /** The approval in scope, if any. */
8
+ export function currentEnableDecision() {
9
+ return storage.getStore();
10
+ }
11
+ /**
12
+ * Runs `fn` with no approval in scope: work that outlives or is detached from the call that
13
+ * started it (a queue job, a bus delivery) never settles a request as an admin's decision.
14
+ */
15
+ export function withoutEnableDecision(fn) {
16
+ return storage.exit(fn);
17
+ }
@@ -0,0 +1,186 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import { ApiError } from "../errors.js";
3
+ import { type OrgRole } from "../orgs/roles.js";
4
+ import { type ComponentKind } from "./component-state.js";
5
+ import { type EnableTarget } from "./enable-targets.js";
6
+ import type { RequestActorOpts } from "./request-rules.js";
7
+ /**
8
+ * Point-of-use enable requests (org-usable spec 2026-12-02, "Members and guests"): the owning
9
+ * switch of picker subjects in one org (set-based, one round of queries per kind), the pending
10
+ * request for a target, and the settlement of pending requests when a switch writer changes their
11
+ * target. Database reads only (no Nest service), so the picker projections of other modules
12
+ * (connectors, models, components) resolve subjects the same way the request service does; what a
13
+ * model provider lists comes in as a {@link ModelListing} read once by the caller.
14
+ */
15
+ /**
16
+ * A subject resolved to the switch that turns it on (the target, and the plugin it needs on), or
17
+ * refused. `on`: refused because the subject is usable already (or is coming on with its plugin).
18
+ */
19
+ export type EnableResolution = {
20
+ ok: true;
21
+ target: EnableTarget;
22
+ bundle: string | null;
23
+ /**
24
+ * The subject to record when it differs from what was asked: a model of a provider that is
25
+ * off and whose list cannot be read is recorded as the provider extension, so no notice
26
+ * claims that model.
27
+ */
28
+ subject?: EnableTarget;
29
+ } | {
30
+ ok: false;
31
+ error: ApiError;
32
+ on?: true;
33
+ };
34
+ /**
35
+ * The org's model catalog as its providers list it (`ProviderRegistry.catalog`): per provider the
36
+ * status and the models the platform left on, with the ones the org disabled.
37
+ */
38
+ export type ModelListing = ReadonlyMap<string, {
39
+ status: string;
40
+ listed: ReadonlySet<string>;
41
+ disabled: ReadonlySet<string>;
42
+ }>;
43
+ /**
44
+ * The deployment's live state a resolution may use, read once by the caller: what the providers
45
+ * list for the org (`models`) and on the platform (`platformModels`, a provider off in the org),
46
+ * and the extensions loaded here (`loaded`: a config-declared extension has no install row).
47
+ */
48
+ export interface EnableLive {
49
+ models?: ModelListing;
50
+ platformModels?: ModelListing;
51
+ loaded?: ReadonlySet<string>;
52
+ }
53
+ /** Builds a {@link ModelListing} from `ProviderRegistry.catalog(orgId)`. */
54
+ export declare function modelListingOf(catalog: readonly {
55
+ provider: string;
56
+ status: string;
57
+ models: readonly {
58
+ id: string;
59
+ disabled?: boolean;
60
+ }[];
61
+ }[]): ModelListing;
62
+ /**
63
+ * The owning switch of plugins in the org: refused when the org cannot see one (hidden by scope,
64
+ * an unshared plugin of another org, or disabled for a member), disabled by the super admin, not
65
+ * offered to the org (an org admin asks the super admin for access instead), builtin, already
66
+ * usable, or switched on with a dependency the org lacks. Two queries for any number of ids.
67
+ */
68
+ export declare function resolvePlugins(db: KernelSchemaDb, orgId: string, ids: readonly string[], isAdmin: boolean): Promise<Map<string, EnableResolution>>;
69
+ /**
70
+ * The owning switch of picker subjects in the org, by {@link targetKey}: one round of queries per
71
+ * kind present, whatever the number of subjects (see the per-kind resolvers).
72
+ */
73
+ export declare function resolveSubjects(db: KernelSchemaDb, orgId: string, subjects: readonly EnableTarget[], isAdmin: boolean, live?: EnableLive): Promise<Map<string, EnableResolution>>;
74
+ /** The owning switch of one picker subject (see {@link resolveSubjects}). */
75
+ export declare function resolveSubject(db: KernelSchemaDb, orgId: string, subject: EnableTarget, isAdmin: boolean, live?: EnableLive): Promise<EnableResolution>;
76
+ /** The org's pending enable requests for `targets`, by {@link targetKey}. */
77
+ export declare function pendingEnableRequests(db: KernelSchemaDb, orgId: string, targets: readonly EnableTarget[]): Promise<Map<string, string>>;
78
+ /** What a picker entry carries when the caller can ask an org admin to turn it on. */
79
+ export interface RequestableFields {
80
+ requestable: true;
81
+ /** The org's pending request for the entry's owning switch (anyone's), else null. */
82
+ pendingRequestId: string | null;
83
+ }
84
+ /**
85
+ * The picker projection (org-usable spec "Members and guests"): for each subject the caller may
86
+ * ask an org admin to turn on (the role has `catalog.request` and the subject resolves to a
87
+ * switch), its {@link RequestableFields}, by {@link targetKey} of the subject. Subjects that are
88
+ * hidden, blocked, unshared, built in or already on are absent, so nothing reveals them. Set-based:
89
+ * one round of queries per kind and one pending lookup.
90
+ */
91
+ export declare function requestableSubjects(db: KernelSchemaDb, orgId: string, role: OrgRole, subjects: readonly EnableTarget[], live?: EnableLive): Promise<Map<string, RequestableFields>>;
92
+ /** One settled outcome: approved, or cancelled because another switch is needed now. */
93
+ export type EnableOutcome = "approved" | "target_changed";
94
+ /**
95
+ * How {@link settleRequestRows} judges each subject (the requester's and every follower's):
96
+ * `on` (`target` was just turned on: a subject that is the target, or usable now, is approved);
97
+ * `final` (an admin's decision with nothing written: usable now is approved); `reconcile` (a
98
+ * platform change: a request whose owning switch is still its target stays pending).
99
+ */
100
+ type SettleMode = {
101
+ kind: "on";
102
+ target: EnableTarget;
103
+ } | {
104
+ kind: "final";
105
+ } | {
106
+ kind: "reconcile";
107
+ };
108
+ /** Who settles a row and what its audit carries. */
109
+ interface Settler {
110
+ actor: string | null;
111
+ actorTokenId?: string | undefined;
112
+ /** Merged into the row's audit (never another request's id). */
113
+ auditDetail?: Record<string, unknown> | undefined;
114
+ }
115
+ /**
116
+ * Settles locked pending enable rows of one org, in the caller's transaction: each subject (the
117
+ * requester's, and each follower's own) is resolved again in one batch; the row is approved when
118
+ * the requester's subject is usable (a `cancelReason: "target_changed"` cancellation otherwise),
119
+ * and each follower's own outcome is recorded in `detail.followers` for their notice. Audits
120
+ * each row under its own id. Returns the outcome of every row it settled (rows kept pending under
121
+ * `reconcile` are absent).
122
+ */
123
+ export declare function settleRequestRows(db: KernelSchemaDb, orgId: string, rows: readonly {
124
+ id: string;
125
+ detail: unknown;
126
+ item_id?: string | null;
127
+ }[], mode: SettleMode, settlerOf: (id: string) => Settler): Promise<Map<string, EnableOutcome>>;
128
+ /**
129
+ * A switch writer turned `target` on in the org, in its transaction: the org's pending enable
130
+ * requests for that target are settled (rows locked FOR UPDATE, {@link settleRequestRows}). With
131
+ * an org admin's approval in scope ({@link currentEnableDecision}) for this target, that request
132
+ * must still be pending (else `catalog.request_decided`, which rolls the write back) unless this
133
+ * transaction settled it already, and is settled as the admin's decision: approved when its
134
+ * subject is usable now, else cancelled (`target_changed`) and the admin is told another switch
135
+ * is needed. The caller reads the committed row: a rolled-back write leaves it pending.
136
+ * `opts.settle: false` (an install failure recording the switch) settles nothing.
137
+ *
138
+ * Called by: `ScopeWriter.setOrgSwitch` (plugin and component switches), `resolveRequestsByInstall`
139
+ * (installs), `OrgExtensionConfigs` (the extension switch), `ModelEnablement.setOrg` (org models
140
+ * switched back on) and `ConnectorsService` (a connector set active, by an org admin, the platform
141
+ * or a plugin switch-on).
142
+ */
143
+ export declare function settleEnableRequests(db: KernelSchemaDb, orgId: string, target: EnableTarget, actor: string | null, opts?: RequestActorOpts & {
144
+ settle?: boolean;
145
+ }): Promise<string[]>;
146
+ /**
147
+ * A plugin was switched off in the org, in the writer's transaction: pending enable requests for
148
+ * an extension, a component, a connector or a model that needed that plugin on (`detail.bundle`)
149
+ * are stale (the plugin is their owning switch now) and are cancelled with
150
+ * `cancelReason: "target_changed"`. Called by `ScopeWriter.setOrgSwitch` (plugin off).
151
+ */
152
+ export declare function cancelEnableRequestsOfBundle(db: KernelSchemaDb, orgId: string, itemId: string, actor: string | null): Promise<void>;
153
+ /**
154
+ * A model provider extension was switched off in the org, in the writer's transaction: pending
155
+ * requests for its models are stale (the extension is their owning switch now). Called by
156
+ * `OrgExtensionConfigs` (extension off).
157
+ */
158
+ export declare function cancelEnableRequestsOfProvider(db: KernelSchemaDb, orgId: string, provider: string, actor: string | null): Promise<void>;
159
+ /**
160
+ * A connector was disabled by its plugin's switch-off (`target_changed`: the plugin is its owning
161
+ * switch now) or removed (`connector_removed`, no notice), in the writer's transaction: pending
162
+ * requests for it are cancelled. Called by `ConnectorsService.disableWithPluginIn` and `removeIn`.
163
+ */
164
+ export declare function cancelEnableRequestsOfConnector(db: KernelSchemaDb, orgId: string, connectorId: string, actor: string | null, reason: "target_changed" | "connector_removed"): Promise<void>;
165
+ /**
166
+ * The platform disabled models of a provider, in its transaction: every org's pending requests
167
+ * for them (as target or subject) are cancelled; the model is hidden from the orgs, so no "ask
168
+ * again" notice. Called by `ModelEnablement.setPlatform`.
169
+ */
170
+ export declare function cancelEnableRequestsOfPlatformModels(db: KernelSchemaDb, provider: string, models: readonly string[], actor: string | null): Promise<void>;
171
+ /**
172
+ * The platform changed a plugin's or a component's scope, share or disabled flag, in its
173
+ * transaction: the pending enable requests of every org that target it, or that need the plugin
174
+ * on (`detail.bundle`), are checked against their subjects again ({@link settleRequestRows},
175
+ * `reconcile`): a subject usable now approves the request, one whose owning switch is still the
176
+ * stored target keeps it pending, any other outcome (hidden, blocked, another switch first)
177
+ * cancels it with `cancelReason: "target_changed"`. Called by `writeScope` (every scope write),
178
+ * `ScopeWriter.setDisabled` and the unshare paths.
179
+ */
180
+ export declare function reconcileEnableRequestsOf(db: KernelSchemaDb, subject: {
181
+ kind: "plugin" | ComponentKind;
182
+ id: string;
183
+ }, actor: string | null): Promise<void>;
184
+ /** Whether the request's subject is its target (a legacy row without a subject counts as one). */
185
+ export declare function subjectIsTarget(detail: unknown): boolean;
186
+ export {};