@capybara-hq/kernel 0.1.0-rc.136 → 0.1.0-rc.137

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 (158) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/agents/templates.js +3 -10
  10. package/dist/app.d.ts +3 -1
  11. package/dist/app.js +1 -0
  12. package/dist/automations/automations.service.js +4 -5
  13. package/dist/catalog/catalog-content.d.ts +1 -1
  14. package/dist/catalog/catalog-content.js +17 -22
  15. package/dist/catalog/catalog-items.d.ts +5 -10
  16. package/dist/catalog/catalog-items.js +27 -51
  17. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  18. package/dist/catalog/catalog-scope.service.js +105 -141
  19. package/dist/catalog/catalog.module.js +2 -0
  20. package/dist/catalog/catalog.service.d.ts +3 -3
  21. package/dist/catalog/catalog.service.js +33 -8
  22. package/dist/catalog/cli.js +17 -0
  23. package/dist/catalog/component-promotion.js +8 -4
  24. package/dist/catalog/component-scope.service.d.ts +3 -1
  25. package/dist/catalog/component-scope.service.js +101 -140
  26. package/dist/catalog/component-state.d.ts +10 -8
  27. package/dist/catalog/component-state.js +42 -30
  28. package/dist/catalog/dependency-edges.d.ts +25 -0
  29. package/dist/catalog/dependency-edges.js +125 -0
  30. package/dist/catalog/install-status.d.ts +2 -3
  31. package/dist/catalog/install-status.js +2 -3
  32. package/dist/catalog/org-catalog.service.d.ts +3 -1
  33. package/dist/catalog/org-catalog.service.js +33 -94
  34. package/dist/catalog/org-intent.d.ts +43 -0
  35. package/dist/catalog/org-intent.js +184 -0
  36. package/dist/catalog/owned-items.d.ts +1 -1
  37. package/dist/catalog/owned-items.js +9 -29
  38. package/dist/catalog/ownership.d.ts +2 -3
  39. package/dist/catalog/ownership.js +10 -28
  40. package/dist/catalog/platform-components.d.ts +3 -1
  41. package/dist/catalog/platform-components.js +9 -1
  42. package/dist/catalog/plugin-import.js +12 -16
  43. package/dist/catalog/plugin-install.d.ts +3 -4
  44. package/dist/catalog/plugin-install.js +25 -49
  45. package/dist/catalog/plugin-upgrade.d.ts +2 -2
  46. package/dist/catalog/plugin-upgrade.js +18 -34
  47. package/dist/catalog/request-rules.js +20 -8
  48. package/dist/catalog/scope-orgs.js +2 -7
  49. package/dist/catalog/scope-state.d.ts +6 -6
  50. package/dist/catalog/scope-state.js +24 -43
  51. package/dist/catalog/scope-sync.d.ts +0 -2
  52. package/dist/catalog/scope-sync.js +11 -39
  53. package/dist/catalog/scope-writer.d.ts +78 -0
  54. package/dist/catalog/scope-writer.js +181 -0
  55. package/dist/catalog/unshare.js +8 -41
  56. package/dist/channels/connections.service.js +6 -6
  57. package/dist/channels/supervisor.js +3 -7
  58. package/dist/client/client-access.service.js +2 -12
  59. package/dist/config/schema.d.ts +6 -0
  60. package/dist/config/schema.js +29 -1
  61. package/dist/ctx/create-ctx.d.ts +2 -2
  62. package/dist/ctx/create-ctx.js +2 -60
  63. package/dist/ctx/guard-db.d.ts +6 -0
  64. package/dist/ctx/guard-db.js +55 -0
  65. package/dist/db/extension-handoff-schema.d.ts +1 -1
  66. package/dist/db/extension-handoff-schema.js +48 -10
  67. package/dist/db/extension-schema-transfer.js +5 -2
  68. package/dist/db/kernel-schema.d.ts +11 -1
  69. package/dist/device-access/host-services.d.ts +2 -2
  70. package/dist/device-access/host-services.js +5 -6
  71. package/dist/erasure/org-catalog.js +2 -2
  72. package/dist/erasure/org-rules.js +5 -0
  73. package/dist/extensions/admin-ops.d.ts +9 -5
  74. package/dist/extensions/admin-ops.js +52 -8
  75. package/dist/extensions/admin-view.js +1 -4
  76. package/dist/extensions/bootstrap.js +4 -1
  77. package/dist/extensions/cli.js +1 -0
  78. package/dist/extensions/effective-config.js +1 -4
  79. package/dist/extensions/enabled.d.ts +23 -29
  80. package/dist/extensions/enabled.js +141 -62
  81. package/dist/extensions/host.d.ts +64 -45
  82. package/dist/extensions/host.js +443 -128
  83. package/dist/extensions/installs.d.ts +9 -0
  84. package/dist/extensions/installs.js +23 -0
  85. package/dist/extensions/isolated/admission.d.ts +10 -0
  86. package/dist/extensions/isolated/admission.js +206 -0
  87. package/dist/extensions/isolated/authorization.d.ts +37 -0
  88. package/dist/extensions/isolated/authorization.js +146 -0
  89. package/dist/extensions/isolated/broker.d.ts +15 -0
  90. package/dist/extensions/isolated/broker.js +452 -0
  91. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  92. package/dist/extensions/isolated/child-protocol.js +21 -0
  93. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  94. package/dist/extensions/isolated/child-registration.js +152 -0
  95. package/dist/extensions/isolated/child-session.d.ts +6 -0
  96. package/dist/extensions/isolated/child-session.js +343 -0
  97. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  98. package/dist/extensions/isolated/child-streams.js +142 -0
  99. package/dist/extensions/isolated/child.d.ts +1 -0
  100. package/dist/extensions/isolated/child.js +10 -0
  101. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  102. package/dist/extensions/isolated/configured-package.js +73 -0
  103. package/dist/extensions/isolated/lanes.d.ts +100 -0
  104. package/dist/extensions/isolated/lanes.js +699 -0
  105. package/dist/extensions/isolated/postgres-gate.d.ts +14 -0
  106. package/dist/extensions/isolated/postgres-gate.js +255 -0
  107. package/dist/extensions/isolated/revision.d.ts +32 -0
  108. package/dist/extensions/isolated/revision.js +358 -0
  109. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  110. package/dist/extensions/isolated/rpc-frame.js +193 -0
  111. package/dist/extensions/isolated/rpc.d.ts +66 -0
  112. package/dist/extensions/isolated/rpc.js +314 -0
  113. package/dist/extensions/isolated/sandbox.d.ts +35 -0
  114. package/dist/extensions/isolated/sandbox.js +372 -0
  115. package/dist/extensions/isolated/tier.d.ts +6 -0
  116. package/dist/extensions/isolated/tier.js +45 -0
  117. package/dist/extensions/ledger.d.ts +1 -1
  118. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  119. package/dist/extensions/lifecycle-topics.js +1 -0
  120. package/dist/extensions/lifecycle.d.ts +3 -1
  121. package/dist/extensions/lifecycle.js +32 -5
  122. package/dist/extensions/locks.d.ts +2 -0
  123. package/dist/extensions/locks.js +7 -0
  124. package/dist/extensions/org-config.d.ts +17 -27
  125. package/dist/extensions/org-config.js +114 -129
  126. package/dist/extensions/plugin-guides.d.ts +5 -10
  127. package/dist/extensions/plugin-guides.js +18 -37
  128. package/dist/extensions/plugin-icons.d.ts +3 -21
  129. package/dist/extensions/plugin-icons.js +9 -44
  130. package/dist/extensions/plugin-items.d.ts +10 -30
  131. package/dist/extensions/plugin-items.js +32 -73
  132. package/dist/extensions/source-intent.d.ts +14 -0
  133. package/dist/extensions/source-intent.js +77 -0
  134. package/dist/index.d.ts +2 -1
  135. package/dist/index.js +2 -1
  136. package/dist/infra/database/database.module.js +6 -1
  137. package/dist/infra/database/kernel-db.d.ts +3 -1
  138. package/dist/infra/database/kernel-db.js +4 -0
  139. package/dist/infra/paging/paged-read.d.ts +56 -0
  140. package/dist/infra/paging/paged-read.js +78 -0
  141. package/dist/kernel.d.ts +3 -2
  142. package/dist/kernel.js +21 -2
  143. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  144. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  145. package/dist/lifecycle/tokens.d.ts +8 -0
  146. package/dist/lifecycle/tokens.js +2 -0
  147. package/dist/orgs/directory-sync.js +1 -4
  148. package/dist/platform/ops/admin.ops.js +14 -3
  149. package/dist/platform/ops/orgs.ops.js +13 -3
  150. package/dist/setup/setup-checks.service.js +3 -2
  151. package/dist/skills/usable.js +41 -30
  152. package/dist/themes/theme-state.js +3 -3
  153. package/dist/tools/registry.d.ts +1 -1
  154. package/dist/tools/registry.js +1 -1
  155. package/package.json +2 -2
  156. package/src/migrations/0228_extension_org_switches.sql +56 -0
  157. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  158. package/src/migrations/0230_audit_filter_idx.sql +18 -0
@@ -14,6 +14,8 @@ import { ApiError } from "../errors.js";
14
14
  import { ExtensionAdmin } from "../extensions/admin-view.js";
15
15
  import { ExtensionInstalls } from "../extensions/installs.js";
16
16
  import { PluginInstallLock } from "../extensions/locks.js";
17
+ import { extensionSourcesQuery } from "../extensions/plugin-items.js";
18
+ import { captureSourceIntent, restoreSourceIntent } from "../extensions/source-intent.js";
17
19
  import { audit } from "../identity/audit.js";
18
20
  import { SuperAdminLock } from "../identity/super-admin.js";
19
21
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -24,6 +26,7 @@ import { OrgLock } from "../orgs/org-lock.js";
24
26
  import { sameRepository } from "../packages/provenance.js";
25
27
  import { assertNotPlatformDefault } from "../themes/theme-usage.js";
26
28
  import { countInstalls, inAuthorOrder, itemConfirmations, itemScopeFacts, itemView, marketplaceLatest, versionUsable, } from "./catalog-items.js";
29
+ import { retireCatalogDependencyEdges } from "./dependency-edges.js";
27
30
  import { expandGitUrl, GitSourceError, gitErrorDetails, normalGitPath, readGitTreeAndOids, resolveGitCommit, } from "./git-source.js";
28
31
  import { fetchMarketplaceArchive, marketplaceNetPolicy, marketplaceUrlProblem, requireMarketplacePublisher, } from "./marketplace-fetch.js";
29
32
  import { assertEntryNotDeprecated, entryCompatible, entrySourceHost, HOST_VERSIONS, hostAllowed, loadMarketplaceEntry, MarketplacesService, pluginNameFrom, } from "./marketplaces.service.js";
@@ -441,7 +444,7 @@ let CatalogService = class CatalogService {
441
444
  list.push(v);
442
445
  byItem.set(v.item_id, list);
443
446
  }
444
- const installs = await countInstalls(this.db, items, byItem);
447
+ const installs = await countInstalls(this.db, items.map((item) => item.id));
445
448
  const latest = await marketplaceLatest(this.db, this.config.get(), items, byItem);
446
449
  const facts = await itemScopeFacts(this.db, items, await itemConfirmations(this.admin, items, byItem));
447
450
  return {
@@ -467,7 +470,7 @@ let CatalogService = class CatalogService {
467
470
  .execute()).filter((v) => item.owner_org_id !== null || versionUsable(v));
468
471
  rows.sort((a, b) => newestFirst({ version: a.version, importedAt: a.imported_at }, { version: b.version, importedAt: b.imported_at }));
469
472
  const byItem = new Map([[item.id, rows]]);
470
- const installs = await countInstalls(this.db, [item], byItem);
473
+ const installs = await countInstalls(this.db, [item.id]);
471
474
  const latest = await marketplaceLatest(this.db, this.config.get(), [item], byItem);
472
475
  const facts = await itemScopeFacts(this.db, [item], await itemConfirmations(this.admin, [item], byItem));
473
476
  return {
@@ -535,7 +538,16 @@ let CatalogService = class CatalogService {
535
538
  .where("id", "=", itemId)
536
539
  .forUpdate()
537
540
  .execute();
538
- await this.assertExtensionDisabled(this.db, itemId, true);
541
+ const names = await this.db
542
+ .selectFrom(extensionSourcesQuery(this.db).as("source"))
543
+ .select("source.plugin")
544
+ .where("source.item_id", "=", itemId)
545
+ .union(this.db.selectFrom("catalog_items").select("name as plugin").where("id", "=", itemId))
546
+ .orderBy("plugin")
547
+ .execute();
548
+ for (const { plugin } of names)
549
+ await this.installLock.lock(plugin);
550
+ await this.assertExtensionDisabled(this.db, itemId);
539
551
  if ((await this.removeIn(actor, itemId, opts)) === null)
540
552
  throw notFound();
541
553
  }
@@ -559,10 +571,10 @@ let CatalogService = class CatalogService {
559
571
  }
560
572
  /**
561
573
  * A live platform item whose extension (the install of the item's name from its package) is
562
- * enabled -> 409 `catalog.extension_enabled`. With `lock`, under the per-name install lock an
563
- * enable takes too (the caller's transaction), so no enable slips in between.
574
+ * enabled -> 409 `catalog.extension_enabled`. The removal holds the extension install locks
575
+ * while checking and retiring the item.
564
576
  */
565
- async assertExtensionDisabled(db, itemId, lock = false) {
577
+ async assertExtensionDisabled(db, itemId) {
566
578
  const item = await db
567
579
  .selectFrom("catalog_items")
568
580
  .select(["name", "package_name", "owner_org_id", "display_name"])
@@ -571,8 +583,6 @@ let CatalogService = class CatalogService {
571
583
  .executeTakeFirst();
572
584
  if (!item || item.owner_org_id !== null)
573
585
  return;
574
- if (lock)
575
- await this.installLock.lock(item.name);
576
586
  const install = await db
577
587
  .selectFrom("extension_installs as x")
578
588
  .innerJoin("extension_packages as p", "p.sha256", "x.sha256")
@@ -607,6 +617,17 @@ let CatalogService = class CatalogService {
607
617
  .forUpdate()
608
618
  .execute();
609
619
  await assertNotPlatformDefault(t, themes.map((r) => r.id), () => "gone");
620
+ const sources = await t
621
+ .selectFrom(extensionSourcesQuery(t).as("source"))
622
+ .select("plugin")
623
+ .where("item_id", "=", itemId)
624
+ .orderBy("plugin")
625
+ .execute();
626
+ const sourceIntent = new Map();
627
+ for (const { plugin } of sources) {
628
+ await this.installLock.lock(plugin);
629
+ sourceIntent.set(plugin, await captureSourceIntent(t, plugin, "retire"));
630
+ }
610
631
  const row = await t
611
632
  .updateTable("catalog_items")
612
633
  .set({
@@ -649,6 +670,10 @@ let CatalogService = class CatalogService {
649
670
  ...opts.auditDetail,
650
671
  },
651
672
  });
673
+ for (const [plugin, before] of sourceIntent) {
674
+ await restoreSourceIntent(t, plugin, before, actor);
675
+ }
676
+ await retireCatalogDependencyEdges(t, itemId);
652
677
  return { name: row.name };
653
678
  }
654
679
  };
@@ -5,9 +5,11 @@ import { OBJECT_STORE_EXTENSION_POINT, } from "@capybara-hq/plugin-sdk";
5
5
  import { ClientBuilds } from "../client/client-builds.service.js";
6
6
  import { ApiError } from "../errors.js";
7
7
  import { planApprovals, snapshotCovers } from "../extensions/approvals.js";
8
+ import { loadBootstrapManifest } from "../extensions/bootstrap-extra.js";
8
9
  import { openExtensionCli } from "../extensions/cli.js";
9
10
  import { assertSecretsReachable } from "../extensions/host.js";
10
11
  import { importExtensionModule, matchesSection } from "../extensions/instance.js";
12
+ import { installedExtensionTier } from "../extensions/isolated/tier.js";
11
13
  import { packageRootOf, syncPackage } from "../extensions/sync.js";
12
14
  import { packagePath } from "../packages/tgz.js";
13
15
  import { PrefixedStorage } from "../storage/storage.service.js";
@@ -73,6 +75,10 @@ export async function loadCliObjectStore(cli, log, syncDir) {
73
75
  };
74
76
  for (const provider of providers) {
75
77
  const name = provider.manifest.name;
78
+ if (provider.isolated) {
79
+ reasons.push(`${name} requires isolated execution`);
80
+ continue;
81
+ }
76
82
  const decision = decisions.find((d) => d.plugin === name);
77
83
  if (decision?.action === "pending") {
78
84
  reasons.push(`${name} awaits permission approval`);
@@ -88,6 +94,17 @@ export async function loadCliObjectStore(cli, log, syncDir) {
88
94
  return { store };
89
95
  }
90
96
  for (const d of installed) {
97
+ try {
98
+ const tier = await installedExtensionTier(d, () => loadBootstrapManifest({}), { get: (sha) => cli.readPackage(sha) }, true);
99
+ if (tier !== "trusted") {
100
+ reasons.push(`${d.name} did not pass trusted admission`);
101
+ continue;
102
+ }
103
+ }
104
+ catch {
105
+ reasons.push(`${d.name} could not be verified for trusted execution`);
106
+ continue;
107
+ }
91
108
  // Replicas set it up only after its migrations ran (ensureMigrated records migrated_sha); the
92
109
  // CLI never migrates, so a package whose migrations have not run for this sha is skipped
93
110
  if (d.section.migrations !== undefined && d.migratedSha !== d.sha256) {
@@ -27,6 +27,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
27
27
  import { StorageService } from "../storage/storage.service.js";
28
28
  import { putCatalogFiles } from "./catalog-items.js";
29
29
  import { platformSkillPrefix, uniqueVersionPrefix } from "./platform-components.js";
30
+ import { writeScope } from "./scope-writer.js";
30
31
  /** The org row changed between {@link ComponentPromotion.prepare} and its transaction: prepare again. */
31
32
  export class PromotionStale extends Error {
32
33
  }
@@ -249,10 +250,13 @@ let ComponentPromotion = class ComponentPromotion {
249
250
  .where("org_id", "=", row.orgId)
250
251
  .execute();
251
252
  }
252
- await this.db
253
- .insertInto("component_scope_orgs")
254
- .values({ kind: p.kind, component_id: p.platformId, org_id: row.orgId })
255
- .execute();
253
+ await writeScope(this.db, {
254
+ kind: p.kind,
255
+ id: p.platformId,
256
+ scopeMode: "own",
257
+ scope: "named",
258
+ orgs: [row.orgId],
259
+ });
256
260
  await audit(this.db, {
257
261
  actorAccountId: actor,
258
262
  orgId: row.orgId,
@@ -13,6 +13,7 @@ import { type ComponentKind } from "./component-state.js";
13
13
  import { type Owner } from "./ownership.js";
14
14
  import { PluginInstaller } from "./plugin-install.js";
15
15
  import type { PluginScope } from "./scope.js";
16
+ import { ScopeWriter } from "./scope-writer.js";
16
17
  /**
17
18
  * What a component scope change, a component disable or a switch back to its plugin's scope would
18
19
  * do (spec §5 rules 8 and 10): the orgs where it is on now and would be off, with their agents that
@@ -240,6 +241,7 @@ export declare function nameConflictError(conflicts: ComponentScopePreview["conf
240
241
  export declare class ComponentScopeService {
241
242
  private readonly kdb;
242
243
  private readonly adminLock;
244
+ private readonly scopeWriter;
243
245
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
244
246
  private readonly orgLock;
245
247
  /** Promote on share (ruling P3-3): an org row shown or associated becomes a platform row. */
@@ -249,7 +251,7 @@ export declare class ComponentScopeService {
249
251
  private readonly guides;
250
252
  /** A connector template switched on where its plugin is installed gets its connector. */
251
253
  private readonly installer;
252
- constructor(kdb: KernelDb, adminLock: SuperAdminLock,
254
+ constructor(kdb: KernelDb, adminLock: SuperAdminLock, scopeWriter: ScopeWriter,
253
255
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
254
256
  orgLock: OrgLock,
255
257
  /** Promote on share (ruling P3-3): an org row shown or associated becomes a platform row. */
@@ -27,8 +27,8 @@ import { ComponentPromotion, notOwnedError, PROMOTION_ATTEMPTS, PromotionStale,
27
27
  import { agentsUsing, COMPONENT_KINDS, componentLocked, componentOffered, componentOn, componentPluginOn, connectorsMadeFrom, listedIn, loadComponents, loadScopeState, pluginFactsOf, skillNameClashes, switchOf, themeIdClashes, } from "./component-state.js";
28
28
  import { assertOwnerListed, assertShareable, assertShareableTarget, newlySharedWith, ownerOf, ownersOf, } from "./ownership.js";
29
29
  import { PluginInstaller } from "./plugin-install.js";
30
+ import { assertScopePreview, COMPONENT_SCOPE_TABLE, ScopeWriter } from "./scope-writer.js";
30
31
  const notFound = () => new ApiError("component.not_found", "Component not found");
31
- const staleError = () => new ApiError("plugin.scope_stale", "What this change affects has changed since the preview; preview it again and confirm the new hash");
32
32
  const builtinError = () => new ApiError("plugin.builtin", "This component belongs to a built-in plugin: it is on in every organization and its scope cannot be changed or disabled");
33
33
  /** The org action that manages a kind of component (the org admin's). */
34
34
  const ACTION = {
@@ -123,12 +123,13 @@ function switchHash(orgId, c, preview) {
123
123
  let ComponentScopeService = class ComponentScopeService {
124
124
  kdb;
125
125
  adminLock;
126
+ scopeWriter;
126
127
  orgLock;
127
128
  promotion;
128
129
  txHost;
129
130
  guides;
130
131
  installer;
131
- constructor(kdb, adminLock,
132
+ constructor(kdb, adminLock, scopeWriter,
132
133
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
133
134
  orgLock,
134
135
  /** Promote on share (ruling P3-3): an org row shown or associated becomes a platform row. */
@@ -139,6 +140,7 @@ let ComponentScopeService = class ComponentScopeService {
139
140
  installer) {
140
141
  this.kdb = kdb;
141
142
  this.adminLock = adminLock;
143
+ this.scopeWriter = scopeWriter;
142
144
  this.orgLock = orgLock;
143
145
  this.promotion = promotion;
144
146
  this.txHost = txHost;
@@ -253,7 +255,7 @@ let ComponentScopeService = class ComponentScopeService {
253
255
  const uiTheme = await platformDefaultThemeId(this.db);
254
256
  for (const kind of filter.kind !== undefined ? [filter.kind] : COMPONENT_KINDS) {
255
257
  const comps = await loadComponents(this.db, kind, filter.itemId !== undefined ? { itemId: filter.itemId } : {});
256
- const st = await loadScopeState(this.db, kind, comps);
258
+ const st = await loadScopeState(this.db, kind, comps, orgId);
257
259
  const linked = await this.linkedCopies(orgId, kind);
258
260
  const owners = await ownersOf(this.db, comps.flatMap((c) => (c.ownerOrgId === null ? [] : [c.ownerOrgId])));
259
261
  const guides = kind === "connector_template"
@@ -434,10 +436,7 @@ let ComponentScopeService = class ComponentScopeService {
434
436
  assertOwnerListed(gateRow(v), t);
435
437
  assertShareable(gateRow(v));
436
438
  const p = await this.compute(v, t, { hashId: id, listed });
437
- if (p.scopeHash !== scopeHash)
438
- throw staleError();
439
- if (p.conflicts.length > 0)
440
- throw nameConflictError(p.conflicts, kind);
439
+ assertScopePreview({ kind: "scope", hash: scopeHash }, p, (conflicts) => nameConflictError(conflicts, kind));
441
440
  const promotable = kind;
442
441
  const written = await this.withPromotion(promotable, id, (prepared) => this.writeScope(actor, kind, prepared.platformId, target, scopeHash, opts, {
443
442
  hashId: id,
@@ -493,7 +492,7 @@ let ComponentScopeService = class ComponentScopeService {
493
492
  const [c] = await loadComponents(this.db, kind, { ids: [id], forUpdate: true });
494
493
  if (!c)
495
494
  throw notFound();
496
- const st = await loadScopeState(this.db, kind, [c]);
495
+ const st = await loadScopeState(this.db, kind, [c], orgId);
497
496
  const p = pluginFactsOf(st, c.itemId, orgId);
498
497
  const listed = listedIn(st, c.id, orgId);
499
498
  const sw = switchOf(st, c.id, orgId);
@@ -565,21 +564,7 @@ let ComponentScopeService = class ComponentScopeService {
565
564
  }
566
565
  }
567
566
  if (sw !== body.enabled) {
568
- await this.db
569
- .insertInto("component_org_switches")
570
- .values({
571
- kind,
572
- component_id: c.id,
573
- org_id: orgId,
574
- enabled: body.enabled,
575
- updated_by: actor,
576
- })
577
- .onConflict((oc) => oc.columns(["kind", "component_id", "org_id"]).doUpdateSet({
578
- enabled: body.enabled,
579
- updated_by: actor,
580
- updated_at: sql `now()`,
581
- }))
582
- .execute();
567
+ await this.scopeWriter.setOrgSwitch({ kind, id: c.id }, orgId, body.enabled, actor);
583
568
  await audit(this.db, {
584
569
  actorAccountId: actor,
585
570
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -628,7 +613,7 @@ let ComponentScopeService = class ComponentScopeService {
628
613
  const [c] = await loadComponents(this.db, kind, { ids: [id] });
629
614
  if (!c)
630
615
  throw notFound();
631
- const st = await loadScopeState(this.db, kind, [c]);
616
+ const st = await loadScopeState(this.db, kind, [c], orgId);
632
617
  const p = pluginFactsOf(st, c.itemId, orgId);
633
618
  const listed = listedIn(st, c.id, orgId);
634
619
  const sw = switchOf(st, c.id, orgId);
@@ -659,108 +644,95 @@ let ComponentScopeService = class ComponentScopeService {
659
644
  * `x.promote`: the org row to promote first, in this transaction. Returns the id written.
660
645
  */
661
646
  async writeScope(actor, kind, id, target, hash, opts, x) {
662
- await this.adminLock.lockAndAuthorize(actor);
663
- if (x.promote)
664
- id = await this.promotion.promote(x.promote, actor);
665
- const c = await this.component(kind, id, true);
666
- const t = await this.targetOf(c, target);
667
- if (kind === "theme")
668
- await this.assertKeepsPlatformDefault(c, t);
669
- const from = await this.listed(kind, id);
670
- // Its own scope: the owner stays listed (P3-17), widening goes through the share gate (P3-16);
671
- // following the plugin again takes the plugin's scope, which its own writer gates
672
- if (t.scopeMode === "own") {
673
- assertOwnerListed(gateRow(c), t);
674
- assertShareableTarget(gateRow(c), await this.effectiveScope(c, from), t);
675
- }
676
- const p = await this.compute(c, t, { hashId: x.hashId });
677
- if (p.scopeHash !== hash)
678
- throw staleError();
679
- if (p.conflicts.length > 0)
680
- throw nameConflictError(p.conflicts, kind);
681
- if (c.scopeMode === t.scopeMode && c.scope === t.scope && from.join() === t.orgs.join()) {
682
- return id;
683
- }
684
- const before = await this.effectiveScope(c, from);
685
- await this.db
686
- .updateTable(TABLE[kind])
687
- .set({
688
- scope_mode: t.scopeMode,
689
- scope: t.scope,
690
- updated_at: sql `now()`,
691
- })
692
- .where("id", "=", id)
693
- .execute();
694
- // org-filter: super admin's scope change (adminLock above) replaces the platform component's
695
- // whole named list, which spans orgs by design
696
- await this.db
697
- .deleteFrom("component_scope_orgs")
698
- .where("kind", "=", kind)
699
- .where("component_id", "=", id)
700
- .execute();
701
- if (t.scopeMode === "own" && t.orgs.length > 0) {
702
- await this.db
703
- .insertInto("component_scope_orgs")
704
- .values(t.orgs.map((org_id) => ({ kind, component_id: id, org_id })))
705
- .execute();
706
- }
707
- // An own scope that newly shows an org-owned component tells its owner (P3-22); not a theme:
708
- // the `item_shared` notice names plugins, skills and agent templates only
709
- if (t.scopeMode === "own" && kind !== "connector_template" && kind !== "theme") {
710
- const shared = newlySharedWith(before, t);
711
- if (shared === "all_orgs" || shared.length > 0) {
712
- await notifyItemShared(this.db, c.ownerOrgId, { kind, id }, c.name, shared);
647
+ const written = await this.scopeWriter.platformChange(actor, { kind: "scope", hash }, async () => {
648
+ if (x.promote)
649
+ id = await this.promotion.promote(x.promote, actor);
650
+ const c = await this.component(kind, id, true);
651
+ const t = await this.targetOf(c, target);
652
+ if (kind === "theme")
653
+ await this.assertKeepsPlatformDefault(c, t);
654
+ const from = await this.listed(kind, id);
655
+ // Its own scope: the owner stays listed (P3-17), widening goes through the share gate (P3-16);
656
+ // following the plugin again takes the plugin's scope, which its own writer gates
657
+ if (t.scopeMode === "own") {
658
+ assertOwnerListed(gateRow(c), t);
659
+ assertShareableTarget(gateRow(c), await this.effectiveScope(c, from), t);
713
660
  }
714
- }
715
- await audit(this.db, {
716
- actorAccountId: actor,
717
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
718
- action: "component.scope_changed",
719
- target: id,
720
- detail: {
721
- kind,
722
- name: c.name,
723
- plugin: c.plugin,
724
- from: { scopeMode: c.scopeMode, scope: c.scope, orgs: from },
725
- to: { scopeMode: t.scopeMode, scope: t.scope, orgs: t.orgs },
726
- ...opts.auditDetail,
727
- },
661
+ const p = await this.compute(c, t, { hashId: x.hashId });
662
+ return {
663
+ preview: p,
664
+ conflict: (conflicts) => nameConflictError(conflicts, kind),
665
+ apply: async () => {
666
+ if (c.scopeMode === t.scopeMode &&
667
+ c.scope === t.scope &&
668
+ from.join() === t.orgs.join()) {
669
+ return id;
670
+ }
671
+ const before = await this.effectiveScope(c, from);
672
+ await this.scopeWriter.replaceScope({
673
+ kind,
674
+ id,
675
+ scopeMode: t.scopeMode,
676
+ scope: t.scope,
677
+ orgs: t.orgs,
678
+ });
679
+ // An own scope that newly shows an org-owned component tells its owner (P3-22); not a theme:
680
+ // the `item_shared` notice names plugins, skills and agent templates only
681
+ if (t.scopeMode === "own" && kind !== "connector_template" && kind !== "theme") {
682
+ const shared = newlySharedWith(before, t);
683
+ if (shared === "all_orgs" || shared.length > 0) {
684
+ await notifyItemShared(this.db, c.ownerOrgId, { kind, id }, c.name, shared);
685
+ }
686
+ }
687
+ await audit(this.db, {
688
+ actorAccountId: actor,
689
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
690
+ action: "component.scope_changed",
691
+ target: id,
692
+ detail: {
693
+ kind,
694
+ name: c.name,
695
+ plugin: c.plugin,
696
+ from: { scopeMode: c.scopeMode, scope: c.scope, orgs: from },
697
+ to: { scopeMode: t.scopeMode, scope: t.scope, orgs: t.orgs },
698
+ ...opts.auditDetail,
699
+ },
700
+ });
701
+ return id;
702
+ },
703
+ };
728
704
  });
729
- return id;
705
+ return written ?? id;
730
706
  }
731
707
  async writeDisabled(actor, kind, id, disabled, hash, opts) {
732
- await this.adminLock.lockAndAuthorize(actor);
733
- const c = await this.component(kind, id, true);
734
- if (c.disabled === disabled)
735
- return;
736
- const t = await this.targetOf(c, { disabled });
737
- if (kind === "theme")
738
- await this.assertKeepsPlatformDefault(c, t);
739
- const p = await this.compute(c, t);
740
- if (disabled && p.scopeHash !== hash)
741
- throw staleError();
742
- if (p.conflicts.length > 0)
743
- throw nameConflictError(p.conflicts, kind);
744
- await this.db
745
- .updateTable(TABLE[kind])
746
- .set({
747
- disabled,
748
- updated_at: sql `now()`,
749
- })
750
- .where("id", "=", id)
751
- .execute();
752
- await audit(this.db, {
753
- actorAccountId: actor,
754
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
755
- action: "component.scope_changed",
756
- target: id,
757
- detail: {
758
- kind,
759
- name: c.name,
760
- plugin: c.plugin,
761
- disabled: { from: c.disabled, to: disabled },
762
- ...opts.auditDetail,
763
- },
708
+ await this.scopeWriter.platformChange(actor, disabled ? { kind: "disable", hash } : { kind: "enable" }, async () => {
709
+ const c = await this.component(kind, id, true);
710
+ if (c.disabled === disabled)
711
+ return;
712
+ const t = await this.targetOf(c, { disabled });
713
+ if (kind === "theme")
714
+ await this.assertKeepsPlatformDefault(c, t);
715
+ const p = await this.compute(c, t);
716
+ return {
717
+ preview: p,
718
+ conflict: (conflicts) => nameConflictError(conflicts, kind),
719
+ apply: async () => {
720
+ await this.scopeWriter.setDisabled({ kind, id }, disabled);
721
+ await audit(this.db, {
722
+ actorAccountId: actor,
723
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
724
+ action: "component.scope_changed",
725
+ target: id,
726
+ detail: {
727
+ kind,
728
+ name: c.name,
729
+ plugin: c.plugin,
730
+ disabled: { from: c.disabled, to: disabled },
731
+ ...opts.auditDetail,
732
+ },
733
+ });
734
+ },
735
+ };
764
736
  });
765
737
  }
766
738
  /** `promote`: the org row to promote first, in this transaction. Returns the id written. */
@@ -777,7 +749,7 @@ let ComponentScopeService = class ComponentScopeService {
777
749
  if (c.shownToOthers === shown)
778
750
  return id;
779
751
  await this.db
780
- .updateTable(TABLE[kind])
752
+ .updateTable(COMPONENT_SCOPE_TABLE[kind])
781
753
  .set({ shown_to_others: shown, updated_at: sql `now()` })
782
754
  .where("id", "=", id)
783
755
  .execute();
@@ -1081,12 +1053,6 @@ let ComponentScopeService = class ComponentScopeService {
1081
1053
  __decorate([
1082
1054
  Transactional()
1083
1055
  ], ComponentScopeService.prototype, "setSwitch", null);
1084
- __decorate([
1085
- Transactional()
1086
- ], ComponentScopeService.prototype, "writeScope", null);
1087
- __decorate([
1088
- Transactional()
1089
- ], ComponentScopeService.prototype, "writeDisabled", null);
1090
1056
  __decorate([
1091
1057
  Transactional()
1092
1058
  ], ComponentScopeService.prototype, "writeShown", null);
@@ -1094,11 +1060,12 @@ ComponentScopeService = __decorate([
1094
1060
  Injectable(),
1095
1061
  __param(0, Inject(KernelDb)),
1096
1062
  __param(1, Inject(SuperAdminLock)),
1097
- __param(2, Inject(OrgLock)),
1098
- __param(3, Inject(ComponentPromotion)),
1099
- __param(4, Inject(TransactionHost)),
1100
- __param(5, Inject(PluginGuides)),
1101
- __param(6, Inject(PluginInstaller))
1063
+ __param(2, Inject(ScopeWriter)),
1064
+ __param(3, Inject(OrgLock)),
1065
+ __param(4, Inject(ComponentPromotion)),
1066
+ __param(5, Inject(TransactionHost)),
1067
+ __param(6, Inject(PluginGuides)),
1068
+ __param(7, Inject(PluginInstaller))
1102
1069
  ], ComponentScopeService);
1103
1070
  export { ComponentScopeService };
1104
1071
  /** Whether `c` is the platform default theme `uiTheme` (locked on in every org, themes spec §7). */
@@ -1143,9 +1110,3 @@ const gateRow = (c) => ({
1143
1110
  shareable: c.shareable,
1144
1111
  name: c.name,
1145
1112
  });
1146
- const TABLE = {
1147
- skill: "platform_skills",
1148
- agent_template: "platform_agent_templates",
1149
- connector_template: "platform_connector_templates",
1150
- theme: "platform_themes",
1151
- };
@@ -19,7 +19,7 @@ export interface ComponentScopeFacts {
19
19
  }
20
20
  /**
21
21
  * The component's plugin as one org sees it: `live` false for a deleted plugin; `listed` the org on
22
- * the plugin's `named` list; `installed` a live install of the plugin in the org.
22
+ * the plugin's `named` list; `usable` the effective plugin intent in the org.
23
23
  */
24
24
  export interface PluginFacts {
25
25
  live: boolean;
@@ -27,19 +27,20 @@ export interface PluginFacts {
27
27
  builtin: boolean;
28
28
  scope: PluginScope;
29
29
  listed: boolean;
30
- installed: boolean;
30
+ usable: boolean;
31
+ admitted?: boolean;
31
32
  }
32
33
  /**
33
34
  * Whether the component is on in the org (`listed`: the org on the component's own `named` list;
34
35
  * `sw`: the org's component switch):
35
36
  * - never when the component or its plugin is disabled, or its plugin is deleted;
36
- * - `follow`: its plugin is on in the org (a live install, or builtin) and the switch is not off
37
+ * - `follow`: its plugin is usable in the org and the switch is not off
37
38
  * (a `defaultOff` template of a plugin that is not builtin: the switch is on);
38
39
  * - `own`: `wantedOn` over the component's own scope, the list and the switch.
39
40
  */
40
41
  export declare function componentOn(c: ComponentScopeFacts, p: PluginFacts | null, listed: boolean, sw: boolean | null): boolean;
41
42
  /**
42
- * Whether the plugin a component follows is on in the org (a live install there, or builtin); a
43
+ * Whether the plugin a component follows is usable in the org; a
43
44
  * component with its own scope does not depend on it (true). A `follow` component comes on and off
44
45
  * with its plugin (spec §5 rule 5), so its own switch only matters while this holds.
45
46
  */
@@ -104,7 +105,8 @@ export interface ScopeState {
104
105
  disabled: boolean;
105
106
  }>;
106
107
  pluginListed: Map<string, Set<string>>;
107
- installed: Map<string, Set<string>>;
108
+ usable: Map<string, Set<string>>;
109
+ admitted: Map<string, Set<string>>;
108
110
  listed: Map<string, Set<string>>;
109
111
  switches: Map<string, Map<string, boolean>>;
110
112
  }
@@ -112,10 +114,10 @@ export interface ScopeState {
112
114
  export declare function loadScopeState(db: KernelSchemaDb, kind: ComponentKind, comps: readonly {
113
115
  id: string;
114
116
  itemId: string | null;
115
- }[]): Promise<ScopeState>;
117
+ }[], orgId?: string): Promise<ScopeState>;
116
118
  /**
117
119
  * Whether a catalog item is builtin: marked so and owned by the platform. An org-owned item marked
118
- * builtin (never so in practice) is an ordinary item: never on without an install, never locked,
120
+ * builtin (never so in practice) is an ordinary item with regular scope and switches,
119
121
  * and its skills can be turned off (skills default-on spec §3).
120
122
  */
121
123
  export declare const platformBuiltin: (item: {
@@ -235,7 +237,7 @@ export declare function connectorTemplateChoice(db: KernelSchemaDb, orgId: strin
235
237
  export declare function connectorsMadeFrom(db: KernelSchemaDb, orgId: string, id: string): Promise<number>;
236
238
  /**
237
239
  * Whether platform connector template `id` is on in the org (`on`), offered to it but off
238
- * (`off`: its plugin not installed for a `follow` template, or switched off there), or neither
240
+ * (`off`: its plugin off for a `follow` template, or the template switched off there), or neither
239
241
  * (`absent`: missing, deleted, without a plugin, stopped or not offered). One more connector from a
240
242
  * template needs `on` (ruling P4-T6-8), read before and again under the org lock.
241
243
  */