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

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 (203) 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/admin/extensions.controller.d.ts +5 -2
  10. package/dist/admin/extensions.controller.js +10 -1
  11. package/dist/admin/extensions.schemas.d.ts +4 -0
  12. package/dist/admin/extensions.schemas.js +9 -0
  13. package/dist/admin/health.service.d.ts +1 -1
  14. package/dist/admin/health.service.js +3 -3
  15. package/dist/agents/templates.js +3 -10
  16. package/dist/app.d.ts +3 -1
  17. package/dist/app.js +1 -0
  18. package/dist/automations/automations.service.js +4 -5
  19. package/dist/catalog/catalog-content.d.ts +6 -8
  20. package/dist/catalog/catalog-content.js +17 -22
  21. package/dist/catalog/catalog-items.d.ts +5 -10
  22. package/dist/catalog/catalog-items.js +27 -51
  23. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  24. package/dist/catalog/catalog-scope.service.js +109 -145
  25. package/dist/catalog/catalog.module.js +7 -4
  26. package/dist/catalog/catalog.service.d.ts +10 -4
  27. package/dist/catalog/catalog.service.js +52 -10
  28. package/dist/catalog/cli.js +17 -0
  29. package/dist/catalog/component-promotion.js +8 -4
  30. package/dist/catalog/component-scope.service.d.ts +3 -1
  31. package/dist/catalog/component-scope.service.js +101 -140
  32. package/dist/catalog/component-state.d.ts +10 -8
  33. package/dist/catalog/component-state.js +42 -30
  34. package/dist/catalog/dependency-edges.d.ts +25 -0
  35. package/dist/catalog/dependency-edges.js +125 -0
  36. package/dist/catalog/effect-work.d.ts +27 -0
  37. package/dist/catalog/effect-work.js +151 -0
  38. package/dist/catalog/jobs.d.ts +4 -1
  39. package/dist/catalog/jobs.js +14 -4
  40. package/dist/catalog/org-catalog.service.d.ts +5 -1
  41. package/dist/catalog/org-catalog.service.js +101 -106
  42. package/dist/catalog/org-intent.d.ts +45 -0
  43. package/dist/catalog/org-intent.js +205 -0
  44. package/dist/catalog/owned-items.d.ts +6 -2
  45. package/dist/catalog/owned-items.js +27 -32
  46. package/dist/catalog/ownership.d.ts +2 -3
  47. package/dist/catalog/ownership.js +10 -28
  48. package/dist/catalog/platform-components.d.ts +3 -1
  49. package/dist/catalog/platform-components.js +9 -1
  50. package/dist/catalog/plugin-import.d.ts +4 -2
  51. package/dist/catalog/plugin-import.js +22 -21
  52. package/dist/catalog/plugin-install.d.ts +19 -54
  53. package/dist/catalog/plugin-install.js +221 -271
  54. package/dist/catalog/plugin-upgrade.d.ts +10 -5
  55. package/dist/catalog/plugin-upgrade.js +80 -67
  56. package/dist/catalog/request-rules.js +20 -8
  57. package/dist/catalog/scope-orgs.js +2 -7
  58. package/dist/catalog/scope-state.d.ts +6 -6
  59. package/dist/catalog/scope-state.js +24 -43
  60. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  61. package/dist/catalog/scope-sync-workers.js +10 -26
  62. package/dist/catalog/scope-sync.d.ts +19 -116
  63. package/dist/catalog/scope-sync.js +228 -275
  64. package/dist/catalog/scope-writer.d.ts +87 -0
  65. package/dist/catalog/scope-writer.js +239 -0
  66. package/dist/catalog/template-connector-ensure.js +1 -1
  67. package/dist/catalog/unshare.js +9 -43
  68. package/dist/channels/connections.service.js +6 -6
  69. package/dist/channels/supervisor.js +3 -7
  70. package/dist/client/client-access.service.js +2 -12
  71. package/dist/config/schema.d.ts +6 -0
  72. package/dist/config/schema.js +32 -1
  73. package/dist/ctx/create-ctx.d.ts +2 -2
  74. package/dist/ctx/create-ctx.js +2 -60
  75. package/dist/ctx/guard-db.d.ts +6 -0
  76. package/dist/ctx/guard-db.js +55 -0
  77. package/dist/db/extension-handoff-schema.d.ts +1 -1
  78. package/dist/db/extension-handoff-schema.js +48 -10
  79. package/dist/db/extension-schema-transfer.js +5 -2
  80. package/dist/db/kernel-schema.d.ts +32 -6
  81. package/dist/device-access/host-services.d.ts +2 -2
  82. package/dist/device-access/host-services.js +5 -6
  83. package/dist/erasure/org-catalog.js +2 -2
  84. package/dist/erasure/org-rules.js +7 -0
  85. package/dist/extensions/admin-ops.d.ts +10 -6
  86. package/dist/extensions/admin-ops.js +53 -9
  87. package/dist/extensions/admin-view.d.ts +4 -1
  88. package/dist/extensions/admin-view.js +27 -14
  89. package/dist/extensions/bootstrap.d.ts +1 -1
  90. package/dist/extensions/bootstrap.js +6 -4
  91. package/dist/extensions/cli.js +1 -0
  92. package/dist/extensions/effective-config.js +1 -4
  93. package/dist/extensions/enabled.d.ts +183 -29
  94. package/dist/extensions/enabled.js +148 -62
  95. package/dist/extensions/host.d.ts +65 -45
  96. package/dist/extensions/host.js +446 -128
  97. package/dist/extensions/installs.d.ts +9 -0
  98. package/dist/extensions/installs.js +23 -0
  99. package/dist/extensions/isolated/admission.d.ts +10 -0
  100. package/dist/extensions/isolated/admission.js +206 -0
  101. package/dist/extensions/isolated/authorization.d.ts +45 -0
  102. package/dist/extensions/isolated/authorization.js +191 -0
  103. package/dist/extensions/isolated/broker.d.ts +15 -0
  104. package/dist/extensions/isolated/broker.js +471 -0
  105. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  106. package/dist/extensions/isolated/child-protocol.js +21 -0
  107. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  108. package/dist/extensions/isolated/child-registration.js +152 -0
  109. package/dist/extensions/isolated/child-session.d.ts +6 -0
  110. package/dist/extensions/isolated/child-session.js +343 -0
  111. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  112. package/dist/extensions/isolated/child-streams.js +142 -0
  113. package/dist/extensions/isolated/child.d.ts +1 -0
  114. package/dist/extensions/isolated/child.js +10 -0
  115. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  116. package/dist/extensions/isolated/configured-package.js +73 -0
  117. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  118. package/dist/extensions/isolated/engine-binds.js +82 -0
  119. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  120. package/dist/extensions/isolated/engine-policy.js +75 -0
  121. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  122. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  123. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  124. package/dist/extensions/isolated/engine-proxy.js +408 -0
  125. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  126. package/dist/extensions/isolated/engine-vaults.js +93 -0
  127. package/dist/extensions/isolated/lanes.d.ts +108 -0
  128. package/dist/extensions/isolated/lanes.js +726 -0
  129. package/dist/extensions/isolated/postgres-gate.d.ts +15 -0
  130. package/dist/extensions/isolated/postgres-gate.js +255 -0
  131. package/dist/extensions/isolated/revision.d.ts +32 -0
  132. package/dist/extensions/isolated/revision.js +359 -0
  133. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  134. package/dist/extensions/isolated/rpc-frame.js +193 -0
  135. package/dist/extensions/isolated/rpc.d.ts +66 -0
  136. package/dist/extensions/isolated/rpc.js +314 -0
  137. package/dist/extensions/isolated/sandbox.d.ts +39 -0
  138. package/dist/extensions/isolated/sandbox.js +356 -0
  139. package/dist/extensions/isolated/tier.d.ts +6 -0
  140. package/dist/extensions/isolated/tier.js +45 -0
  141. package/dist/extensions/ledger.d.ts +1 -1
  142. package/dist/extensions/lifecycle-topics.d.ts +2 -0
  143. package/dist/extensions/lifecycle-topics.js +2 -0
  144. package/dist/extensions/lifecycle.d.ts +3 -1
  145. package/dist/extensions/lifecycle.js +53 -5
  146. package/dist/extensions/locks.d.ts +2 -0
  147. package/dist/extensions/locks.js +7 -0
  148. package/dist/extensions/org-config.d.ts +17 -27
  149. package/dist/extensions/org-config.js +114 -129
  150. package/dist/extensions/permission-view.d.ts +6 -1
  151. package/dist/extensions/plugin-guides.d.ts +5 -10
  152. package/dist/extensions/plugin-guides.js +18 -37
  153. package/dist/extensions/plugin-icons.d.ts +3 -21
  154. package/dist/extensions/plugin-icons.js +9 -44
  155. package/dist/extensions/plugin-items.d.ts +10 -30
  156. package/dist/extensions/plugin-items.js +32 -73
  157. package/dist/extensions/source-intent.d.ts +14 -0
  158. package/dist/extensions/source-intent.js +77 -0
  159. package/dist/inbox/platform-inbox.service.js +16 -27
  160. package/dist/index.d.ts +2 -1
  161. package/dist/index.js +2 -1
  162. package/dist/infra/database/database.module.js +6 -1
  163. package/dist/infra/database/kernel-db.d.ts +3 -1
  164. package/dist/infra/database/kernel-db.js +4 -0
  165. package/dist/infra/events/kernel-events.d.ts +4 -0
  166. package/dist/infra/outbox/registry.d.ts +3 -36
  167. package/dist/infra/outbox/registry.js +4 -49
  168. package/dist/infra/paging/paged-read.d.ts +56 -0
  169. package/dist/infra/paging/paged-read.js +78 -0
  170. package/dist/infra/queue/queue-names.d.ts +1 -1
  171. package/dist/infra/queue/queue-names.js +1 -1
  172. package/dist/kernel.d.ts +3 -2
  173. package/dist/kernel.js +21 -2
  174. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  175. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  176. package/dist/lifecycle/tokens.d.ts +8 -0
  177. package/dist/lifecycle/tokens.js +2 -0
  178. package/dist/orgs/directory-sync.js +1 -4
  179. package/dist/orgs/org-lock.d.ts +3 -1
  180. package/dist/orgs/org-lock.js +3 -1
  181. package/dist/orgs/orgs.service.d.ts +3 -1
  182. package/dist/orgs/orgs.service.js +15 -8
  183. package/dist/overrides.d.ts +0 -3
  184. package/dist/overrides.js +0 -2
  185. package/dist/platform/ops/admin.ops.js +14 -3
  186. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  187. package/dist/platform/ops/org-plugins.ops.js +5 -2
  188. package/dist/platform/ops/orgs.ops.js +13 -3
  189. package/dist/platform/ops/plugins.ops.js +11 -10
  190. package/dist/setup/setup-checks.service.js +3 -2
  191. package/dist/skills/usable.js +41 -30
  192. package/dist/themes/theme-state.js +3 -3
  193. package/dist/tools/registry.d.ts +2 -2
  194. package/dist/tools/registry.js +7 -3
  195. package/package.json +2 -2
  196. package/src/migrations/0228_extension_org_switches.sql +56 -0
  197. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  198. package/src/migrations/0230_audit_filter_idx.sql +18 -0
  199. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  200. package/dist/catalog/install-status.d.ts +0 -6
  201. package/dist/catalog/install-status.js +0 -6
  202. package/dist/catalog/scope-jobs.d.ts +0 -59
  203. package/dist/catalog/scope-jobs.js +0 -78
@@ -10,6 +10,7 @@ import { packagePath } from "../packages/tgz.js";
10
10
  import { checkSkillFiles, SkillArchiveError } from "../skills/package.js";
11
11
  import { mergeEditableEndpoint } from "../tools/editable-endpoint.js";
12
12
  import { readDisplayFiles } from "./catalog-files.js";
13
+ import { orgSees } from "./org-intent.js";
13
14
  import { iconProblem, pluginThemeError, themeApiError } from "./plugin-package.js";
14
15
  import { templateDescriptionText } from "./template-description.js";
15
16
  import { satisfiesRange } from "./versions.js";
@@ -62,28 +63,22 @@ export function dirDigest(row, dir) {
62
63
  * The item's latest version row; item missing, deleted or (when `includeDisabled` is false)
63
64
  * disabled -> `catalog.item_not_found`.
64
65
  */
65
- async function latestVersionRow(db, itemId, includeDisabled) {
66
+ async function latestVersionRow(db, itemId, includeDisabled, orgId) {
66
67
  if (!UUID_RE.test(itemId))
67
68
  throw itemNotFound();
68
- const item = await db
69
- .selectFrom("catalog_items")
70
- .select(["latest_version", "disabled"])
71
- .where("id", "=", itemId)
72
- .where("deleted_at", "is", null)
73
- .executeTakeFirst();
74
- // An item the caller cannot see is "not found" before any version / storage is read, so "no icon"
75
- // never reveals that it exists
76
- if (!item || (!includeDisabled && item.disabled))
69
+ const query = db
70
+ .selectFrom("catalog_items as item")
71
+ .innerJoin("catalog_item_versions as v", (join) => join.onRef("v.item_id", "=", "item.id").onRef("v.version", "=", "item.latest_version"))
72
+ .select(["v.manifest", "v.object_prefix", "v.files"])
73
+ .where("item.id", "=", itemId)
74
+ .where("item.deleted_at", "is", null)
75
+ .$if(!includeDisabled, (q) => q.where("item.disabled", "=", false));
76
+ const version = await (orgId === undefined
77
+ ? query
78
+ : query.where("item.id", "in", orgSees(db, orgId, includeDisabled).select("item.id"))).executeTakeFirst();
79
+ if (version === undefined)
77
80
  throw itemNotFound();
78
- const v = await db
79
- .selectFrom("catalog_item_versions")
80
- .select(["manifest", "object_prefix", "files"])
81
- .where("item_id", "=", itemId)
82
- .where("version", "=", item.latest_version)
83
- .executeTakeFirst();
84
- if (!v)
85
- throw itemNotFound();
86
- return { item, v };
81
+ return version;
87
82
  }
88
83
  /** The icon's path in the version's files (undefined without an icon). */
89
84
  const iconPath = (v) => {
@@ -93,7 +88,7 @@ const iconPath = (v) => {
93
88
  /** Whether the item's latest version has an icon; unreadable counts as none. */
94
89
  export async function catalogHasIcon(db, itemId) {
95
90
  try {
96
- const { v } = await latestVersionRow(db, itemId, true);
91
+ const v = await latestVersionRow(db, itemId, true);
97
92
  const path = iconPath(v);
98
93
  return path !== undefined && v.files.some((f) => f.path === path);
99
94
  }
@@ -108,8 +103,8 @@ export async function catalogHasIcon(db, itemId) {
108
103
  * storage); no icon -> `catalog.icon_not_found`; stored content that is not a valid svg / png
109
104
  * (checked at import, this guards against tampered storage) -> `internal`.
110
105
  */
111
- export async function readCatalogIcon(db, itemId, includeDisabled) {
112
- const { v } = await latestVersionRow(db, itemId, includeDisabled);
106
+ export async function readCatalogIcon(db, itemId, includeDisabled, orgId) {
107
+ const v = await latestVersionRow(db, itemId, includeDisabled, orgId);
113
108
  const path = iconPath(v);
114
109
  const f = path === undefined ? undefined : v.files.find((x) => x.path === path);
115
110
  if (path === undefined || !f)
@@ -160,11 +160,13 @@ export declare function precheckCatalogImport(db: KernelSchemaDb, name: string,
160
160
  * the release with the same content; `version` not taken meanwhile), creates the item when there is
161
161
  * none or adds the version (latest and display fields change only for a newer version, a version
162
162
  * equal but for build metadata being newer as the later import), and writes the version row (with
163
- * its content digest) and the `catalog.imported` audit. Returns the item id.
163
+ * its content digest) and the `catalog.imported` audit. The caller refreshes dependency edges if
164
+ * the selected version changed, after applying the new item's components.
164
165
  */
165
166
  export declare function writeCatalogVersion(db: KernelSchemaDb, w: CatalogVersionWrite): Promise<{
166
167
  id: string;
167
168
  created: boolean;
169
+ selectedVersionChanged: boolean;
168
170
  }>;
169
171
  /**
170
172
  * Records that `version` of the item was applied (ruling P3-52), in the caller's
@@ -207,15 +209,8 @@ export declare function marketplaceLatest(db: KernelSchemaDb, config: KernelConf
207
209
  name: string;
208
210
  marketplace_id?: string | null;
209
211
  }[], versions: ReadonlyMap<string, readonly RecordedVersion[]>): Promise<Map<string, MarketplaceStatus>>;
210
- /** Org install counts per item (see {@link CatalogItemView.installs}). */
211
- export declare function countInstalls(db: KernelSchemaDb, items: {
212
- id: string;
213
- name: string;
214
- latest_version: string;
215
- }[], versions: ReadonlyMap<string, {
216
- version: string;
217
- extension_sha256: string | null;
218
- }[]>): Promise<Map<string, number>>;
212
+ /** How many organizations have applied setup effects for each item. */
213
+ export declare function countInstalls(db: KernelSchemaDb, itemIds: string[]): Promise<Map<string, number>>;
219
214
  /**
220
215
  * Every id is a live org (`validation_failed` naming the unknown ones otherwise): the orgs of a
221
216
  * `named` scope.
@@ -2,13 +2,12 @@ import { pluginDescription } from "@capybara-hq/plugin-sdk";
2
2
  import { sql } from "kysely";
3
3
  import semver from "semver";
4
4
  import { ApiError } from "../errors.js";
5
- import { enabledExtensionsByOrg } from "../extensions/enabled.js";
6
5
  import { blockingKeys } from "../extensions/permission-set.js";
7
6
  import { audit } from "../identity/audit.js";
8
7
  import { endpointCredentialIssues } from "../tools/endpoint.js";
9
8
  import { gitLocationIdentity } from "./git-source.js";
10
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
11
9
  import { entryCompatible, entryContentChanged, entryDeprecated, sourceEffective, unimportable, } from "./marketplaces.service.js";
10
+ import { orgUsable } from "./org-intent.js";
12
11
  import { ownerOf, ownersOf, PLATFORM_OWNER, packageOwner } from "./ownership.js";
13
12
  import { schemaHasPath } from "./schema-path.js";
14
13
  import { compareVersions, newestFirst, sameRelease, withBuild } from "./versions.js";
@@ -97,7 +96,7 @@ export function inAuthorOrder(manifest, order) {
97
96
  async function liveItem(db, name) {
98
97
  const item = await db
99
98
  .selectFrom("catalog_items")
100
- .select(["id", "package_name", "latest_version", "marketplace_id"])
99
+ .select(["id", "package_name", "latest_version", "platform_synced_version", "marketplace_id"])
101
100
  .where("name", "=", name)
102
101
  .where("deleted_at", "is", null)
103
102
  .executeTakeFirst();
@@ -236,7 +235,8 @@ export async function precheckCatalogImport(db, name, p) {
236
235
  * the release with the same content; `version` not taken meanwhile), creates the item when there is
237
236
  * none or adds the version (latest and display fields change only for a newer version, a version
238
237
  * equal but for build metadata being newer as the later import), and writes the version row (with
239
- * its content digest) and the `catalog.imported` audit. Returns the item id.
238
+ * its content digest) and the `catalog.imported` audit. The caller refreshes dependency edges if
239
+ * the selected version changed, after applying the new item's components.
240
240
  */
241
241
  export async function writeCatalogVersion(db, w) {
242
242
  const t = db;
@@ -244,6 +244,7 @@ export async function writeCatalogVersion(db, w) {
244
244
  const live = await liveItem(t, name);
245
245
  let id;
246
246
  const created = live === undefined;
247
+ let selectedVersionChanged = created;
247
248
  if (live) {
248
249
  id = live.id;
249
250
  assertSameSource(live, w.packageName, sourceIdentity(w.source.detail, w.marketplaceId));
@@ -257,6 +258,7 @@ export async function writeCatalogVersion(db, w) {
257
258
  if (existing.some((v) => v.version === version))
258
259
  throw versionExists(version, false, true);
259
260
  const newer = w.keepLatest !== true && compareVersions(version, live.latest_version) >= 0;
261
+ selectedVersionChanged = newer && live.platform_synced_version === null;
260
262
  await t
261
263
  .updateTable("catalog_items")
262
264
  .set({
@@ -331,7 +333,7 @@ export async function writeCatalogVersion(db, w) {
331
333
  ...w.auditDetail,
332
334
  },
333
335
  });
334
- return { id, created };
336
+ return { id, created, selectedVersionChanged };
335
337
  }
336
338
  /**
337
339
  * Records that `version` of the item was applied (ruling P3-52), in the caller's
@@ -447,34 +449,20 @@ export async function marketplaceLatest(db, config, items, versions) {
447
449
  }
448
450
  return out;
449
451
  }
450
- /** Org install counts per item (see {@link CatalogItemView.installs}). */
451
- export async function countInstalls(db, items, versions) {
452
- const orgs = new Map(items.map((i) => [i.id, new Set()]));
453
- // org-filter: the platform catalog's install count per item (super admin's catalog view): it
454
- // counts the orgs on purpose and returns no org row
455
- const installed = await db
456
- .selectFrom("plugin_installs")
457
- .select(["item_id", "org_id"])
458
- .where("item_id", "in", items.map((i) => i.id))
459
- .where("status", "=", "installed")
452
+ /** How many organizations have applied setup effects for each item. */
453
+ export async function countInstalls(db, itemIds) {
454
+ if (itemIds.length === 0)
455
+ return new Map();
456
+ const applied = await db
457
+ .selectFrom("plugin_installs as install")
458
+ .innerJoin("orgs as org", "org.id", "install.org_id")
459
+ .select(["install.item_id", (eb) => eb.fn.count("install.org_id").distinct().as("n")])
460
+ .where("install.item_id", "in", itemIds)
461
+ .where("install.version", "is not", null)
462
+ .where("org.deleted_at", "is", null)
463
+ .groupBy("install.item_id")
460
464
  .execute();
461
- for (const r of installed)
462
- orgs.get(r.item_id)?.add(r.org_id);
463
- const withExtension = items.filter((i) => (versions.get(i.id) ?? []).find((v) => v.version === i.latest_version)?.extension_sha256 !=
464
- null);
465
- if (withExtension.length > 0) {
466
- const enabled = await db
467
- .selectFrom(enabledExtensionsByOrg(db).as("en"))
468
- .select(["en.plugin", "en.org_id"])
469
- .where("en.plugin", "in", withExtension.map((p) => p.name))
470
- .execute();
471
- for (const i of withExtension) {
472
- for (const r of enabled)
473
- if (r.plugin === i.name)
474
- orgs.get(i.id)?.add(r.org_id);
475
- }
476
- }
477
- return new Map([...orgs].map(([id, set]) => [id, set.size]));
465
+ return new Map(applied.map((row) => [row.item_id, Number(row.n)]));
478
466
  }
479
467
  /**
480
468
  * Every id is a live org (`validation_failed` naming the unknown ones otherwise): the orgs of a
@@ -580,13 +568,13 @@ export async function itemScopeFacts(db, items, confirmations) {
580
568
  for (const r of listed)
581
569
  out.get(r.item_id)?.scopeOrgs.push(r.org_id);
582
570
  const live = await db
583
- .selectFrom("plugin_installs as a")
584
- .innerJoin("orgs as o", "o.id", "a.org_id")
585
- .select(["a.item_id", (eb) => eb.fn.count("a.org_id").distinct().as("n")])
586
- .where("a.item_id", "in", ids)
587
- .where("a.status", "in", [...LIVE_INSTALL_STATUSES])
588
- .where("o.deleted_at", "is", null)
589
- .groupBy("a.item_id")
571
+ .selectFrom("catalog_items as item")
572
+ .crossJoin("orgs as org")
573
+ .select(["item.id as item_id", (eb) => eb.fn.countAll().as("n")])
574
+ .where("item.id", "in", ids)
575
+ .where("org.deleted_at", "is", null)
576
+ .where(({ ref }) => orgUsable(db, ref("org.id"), ref("item.id")))
577
+ .groupBy("item.id")
590
578
  .execute();
591
579
  for (const r of live) {
592
580
  const f = out.get(r.item_id);
@@ -611,18 +599,6 @@ export async function itemScopeFacts(db, items, confirmations) {
611
599
  f.offCount = Number(r.n);
612
600
  }
613
601
  }
614
- if (items.some((i) => i.builtin)) {
615
- const orgs = await db
616
- .selectFrom("orgs")
617
- .select((eb) => eb.fn.countAll().as("n"))
618
- .where("deleted_at", "is", null)
619
- .executeTakeFirstOrThrow();
620
- for (const i of items) {
621
- const f = out.get(i.id);
622
- if (i.builtin && f)
623
- f.enabledOrgs = Number(orgs.n);
624
- }
625
- }
626
602
  return out;
627
603
  }
628
604
  /** The `zh` text of a stored manifest's description; null without one (or an unreadable manifest). */
@@ -9,8 +9,9 @@ import { type ActorOpts, type CatalogItemView, CatalogService } from "./catalog.
9
9
  import { type ComponentKind } from "./component-state.js";
10
10
  import { type PluginConfirmResult, PluginImport } from "./plugin-import.js";
11
11
  import { PluginInstaller } from "./plugin-install.js";
12
- import { type PluginScope } from "./scope.js";
12
+ import type { PluginScope } from "./scope.js";
13
13
  import { PluginScopeSync } from "./scope-sync.js";
14
+ import { ScopeWriter } from "./scope-writer.js";
14
15
  /**
15
16
  * What a scope change or a deployment-level disable would take away (spec §5 rule 8): the orgs
16
17
  * that have the plugin on now (a live install) and would no longer want it, each with its agents
@@ -89,6 +90,7 @@ export declare function conflictsError(conflicts: ScopePreview["conflicts"]): Ap
89
90
  export declare class CatalogScopeService {
90
91
  private readonly kdb;
91
92
  private readonly adminLock;
93
+ private readonly scopeWriter;
92
94
  private readonly catalog;
93
95
  private readonly pluginImport;
94
96
  private readonly installer;
@@ -96,7 +98,7 @@ export declare class CatalogScopeService {
96
98
  private readonly ops;
97
99
  private readonly sync;
98
100
  readonly txHost: TransactionHost;
99
- constructor(kdb: KernelDb, adminLock: SuperAdminLock, catalog: CatalogService, pluginImport: PluginImport, installer: PluginInstaller, extensions: ExtensionAdmin, ops: ExtensionAdminOps, sync: PluginScopeSync, txHost: TransactionHost);
101
+ constructor(kdb: KernelDb, adminLock: SuperAdminLock, scopeWriter: ScopeWriter, catalog: CatalogService, pluginImport: PluginImport, installer: PluginInstaller, extensions: ExtensionAdmin, ops: ExtensionAdminOps, sync: PluginScopeSync, txHost: TransactionHost);
100
102
  private get db();
101
103
  /**
102
104
  * Confirms a staged import ({@link PluginImport.confirm}: installs and enables the extension,
@@ -24,18 +24,17 @@ 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 { LIVE_INSTALL_STATUSES } from "./install-status.js";
27
+ import { orgUsable } from "./org-intent.js";
28
28
  import { assertOwnerListed, assertShareable, assertShareableTarget, newlySharedWith, } from "./ownership.js";
29
29
  import { PluginImport } from "./plugin-import.js";
30
30
  import { PluginInstaller } from "./plugin-install.js";
31
- import { wantedOn } from "./scope.js";
32
31
  import { addScopeOrg } from "./scope-orgs.js";
33
32
  import { PluginScopeSync } from "./scope-sync.js";
33
+ import { ScopeWriter } from "./scope-writer.js";
34
34
  import { narrowComponentOnUnshare, narrowItemOnUnshare } from "./unshare.js";
35
35
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
36
36
  const notFound = () => new ApiError("catalog.item_not_found", "Catalog item not found");
37
37
  const builtinError = () => new ApiError("plugin.builtin", "This plugin is built in: it is on in every organization and its scope cannot be changed or disabled");
38
- const staleError = () => new ApiError("plugin.scope_stale", "What this change affects has changed since the preview; preview it again and confirm the new hash");
39
38
  /** The hash of a preview: sha256 over its sorted JSON, the target included. */
40
39
  function scopeHash(target, p) {
41
40
  return createHash("sha256")
@@ -86,6 +85,7 @@ export function conflictsError(conflicts) {
86
85
  let CatalogScopeService = class CatalogScopeService {
87
86
  kdb;
88
87
  adminLock;
88
+ scopeWriter;
89
89
  catalog;
90
90
  pluginImport;
91
91
  installer;
@@ -93,9 +93,10 @@ let CatalogScopeService = class CatalogScopeService {
93
93
  ops;
94
94
  sync;
95
95
  txHost;
96
- constructor(kdb, adminLock, catalog, pluginImport, installer, extensions, ops, sync, txHost) {
96
+ constructor(kdb, adminLock, scopeWriter, catalog, pluginImport, installer, extensions, ops, sync, txHost) {
97
97
  this.kdb = kdb;
98
98
  this.adminLock = adminLock;
99
+ this.scopeWriter = scopeWriter;
99
100
  this.catalog = catalog;
100
101
  this.pluginImport = pluginImport;
101
102
  this.installer = installer;
@@ -245,91 +246,81 @@ let CatalogScopeService = class CatalogScopeService {
245
246
  });
246
247
  }
247
248
  async writeScope(actor, itemId, target, hash, opts) {
248
- await this.adminLock.lockAndAuthorize(actor);
249
- const item = await this.item(itemId, true);
250
- const t = await this.targetOf(item, target);
251
- const from = await this.listed(itemId);
252
- // The owner stays listed (P3-17); widening goes through the share gate (P3-16)
253
- assertOwnerListed(item, t);
254
- assertShareableTarget(item, { scope: item.scope, orgs: from }, t);
255
- // A scope change sends every theme back to following the plugin (rule 2): each is `all` after
256
- // only when the plugin is (themes spec §7)
257
- await this.assertKeepsPlatformDefault(item.id, (c) => c.disabled || item.disabled ? "gone" : t.scope === "all" ? "all" : "narrower");
258
- const p = await this.compute(item, t);
259
- if (p.scopeHash !== hash)
260
- throw staleError();
261
- if (p.conflicts.length > 0)
262
- throw conflictsError(p.conflicts);
263
- if (item.scope === t.scope && from.join() === t.orgs.join() && p.replaced.length === 0)
264
- return;
265
- await this.followAgain(actor, itemId, p.replaced, opts);
266
- await this.db
267
- .updateTable("catalog_items")
268
- .set({
269
- scope: t.scope,
270
- updated_at: sql `now()`,
271
- })
272
- .where("id", "=", itemId)
273
- .execute();
274
- await this.db.deleteFrom("catalog_item_scope_orgs").where("item_id", "=", itemId).execute();
275
- if (t.orgs.length > 0) {
276
- await this.db
277
- .insertInto("catalog_item_scope_orgs")
278
- .values(t.orgs.map((org_id) => ({ item_id: itemId, org_id })))
279
- .execute();
280
- }
281
- const shared = newlySharedWith({ scope: item.scope, orgs: from }, t);
282
- if (shared === "all_orgs" || shared.length > 0) {
283
- await notifyItemShared(this.db, item.owner_org_id, { kind: "plugin", id: itemId }, item.name, shared);
284
- }
285
- await audit(this.db, {
286
- actorAccountId: actor,
287
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
288
- action: "catalog.scope_changed",
289
- target: itemId,
290
- detail: {
291
- name: item.name,
292
- from: { scope: item.scope, orgs: from },
293
- to: { scope: t.scope, orgs: t.orgs },
294
- ...opts.auditDetail,
295
- },
249
+ await this.scopeWriter.platformChange(actor, { kind: "scope", hash }, async () => {
250
+ const item = await this.item(itemId, true);
251
+ const t = await this.targetOf(item, target);
252
+ const from = await this.listed(itemId);
253
+ // The owner stays listed (P3-17); widening goes through the share gate (P3-16)
254
+ assertOwnerListed(item, t);
255
+ assertShareableTarget(item, { scope: item.scope, orgs: from }, t);
256
+ // A scope change sends every theme back to following the plugin (rule 2): each is `all` after
257
+ // only when the plugin is (themes spec §7)
258
+ await this.assertKeepsPlatformDefault(item.id, (c) => c.disabled || item.disabled ? "gone" : t.scope === "all" ? "all" : "narrower");
259
+ const p = await this.compute(item, t);
260
+ return {
261
+ preview: p,
262
+ conflict: conflictsError,
263
+ apply: async () => {
264
+ if (item.scope === t.scope && from.join() === t.orgs.join() && p.replaced.length === 0)
265
+ return;
266
+ await this.followAgain(actor, itemId, p.replaced, opts);
267
+ await this.scopeWriter.replaceScope({
268
+ kind: "plugin",
269
+ id: itemId,
270
+ scope: t.scope,
271
+ orgs: t.orgs,
272
+ });
273
+ const shared = newlySharedWith({ scope: item.scope, orgs: from }, t);
274
+ if (shared === "all_orgs" || shared.length > 0) {
275
+ await notifyItemShared(this.db, item.owner_org_id, { kind: "plugin", id: itemId }, item.name, shared);
276
+ }
277
+ await audit(this.db, {
278
+ actorAccountId: actor,
279
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
280
+ action: "catalog.scope_changed",
281
+ target: itemId,
282
+ detail: {
283
+ name: item.name,
284
+ from: { scope: item.scope, orgs: from },
285
+ to: { scope: t.scope, orgs: t.orgs },
286
+ ...opts.auditDetail,
287
+ },
288
+ });
289
+ await this.enqueue(itemId, from);
290
+ },
291
+ };
296
292
  });
297
- await this.enqueue(itemId);
298
293
  }
299
294
  async writeDisabled(actor, itemId, disabled, hash, opts) {
300
- await this.adminLock.lockAndAuthorize(actor);
301
- const item = await this.item(itemId, true);
302
- if (item.disabled === disabled)
303
- return;
304
- if (disabled)
305
- await this.assertKeepsPlatformDefault(item.id, () => "gone");
306
- const p = await this.compute(item, disabled
307
- ? await this.targetOf(item, { disabled: true })
308
- : { scope: item.scope, orgs: await this.listed(itemId), disabled, scopeChange: false });
309
- if (disabled && p.scopeHash !== hash)
310
- throw staleError();
311
- if (p.conflicts.length > 0)
312
- throw conflictsError(p.conflicts);
313
- await this.db
314
- .updateTable("catalog_items")
315
- .set({
316
- disabled,
317
- updated_at: sql `now()`,
318
- })
319
- .where("id", "=", itemId)
320
- .execute();
321
- await audit(this.db, {
322
- actorAccountId: actor,
323
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
324
- action: "catalog.scope_changed",
325
- target: itemId,
326
- detail: {
327
- name: item.name,
328
- disabled: { from: item.disabled, to: disabled },
329
- ...opts.auditDetail,
330
- },
295
+ await this.scopeWriter.platformChange(actor, disabled ? { kind: "disable", hash } : { kind: "enable" }, async () => {
296
+ const item = await this.item(itemId, true);
297
+ if (item.disabled === disabled)
298
+ return;
299
+ if (disabled)
300
+ await this.assertKeepsPlatformDefault(item.id, () => "gone");
301
+ const p = await this.compute(item, disabled
302
+ ? await this.targetOf(item, { disabled: true })
303
+ : { scope: item.scope, orgs: await this.listed(itemId), disabled, scopeChange: false });
304
+ return {
305
+ preview: p,
306
+ conflict: conflictsError,
307
+ apply: async () => {
308
+ await this.scopeWriter.setDisabled({ kind: "plugin", id: itemId }, disabled);
309
+ await audit(this.db, {
310
+ actorAccountId: actor,
311
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
312
+ action: "catalog.scope_changed",
313
+ target: itemId,
314
+ detail: {
315
+ name: item.name,
316
+ disabled: { from: item.disabled, to: disabled },
317
+ ...opts.auditDetail,
318
+ },
319
+ });
320
+ await this.enqueue(itemId);
321
+ },
322
+ };
331
323
  });
332
- await this.enqueue(itemId);
333
324
  }
334
325
  /**
335
326
  * Writes an org-owned plugin's 可共享 flag and copies it to its component rows (ruling P3-2).
@@ -378,6 +369,7 @@ let CatalogScopeService = class CatalogScopeService {
378
369
  }
379
370
  if (narrowed)
380
371
  await this.enqueue(itemId);
372
+ this.scopeWriter.refreshIsolatedOrgIntent();
381
373
  }
382
374
  /**
383
375
  * Adds one org to a `named` item's list in the caller's transaction (an approved `access`
@@ -400,8 +392,8 @@ let CatalogScopeService = class CatalogScopeService {
400
392
  await this.enqueue(itemId);
401
393
  }
402
394
  /** Owes the item's scope sync in the transaction that changes its scope (outbox spec §8.1). */
403
- async enqueue(itemId) {
404
- await this.sync.enqueueItem(itemId);
395
+ async enqueue(itemId, previousOrgs = []) {
396
+ await this.sync.enqueueItem(itemId, previousOrgs);
405
397
  }
406
398
  /**
407
399
  * 409 `theme.platform_default` when a live theme of the item is the platform default and `after`
@@ -475,39 +467,32 @@ let CatalogScopeService = class CatalogScopeService {
475
467
  const orgs = await db
476
468
  .selectFrom("orgs")
477
469
  .select(["id", "name"])
470
+ .select(({ ref }) => [
471
+ orgUsable(db, ref("orgs.id"), item.id).as("onNow"),
472
+ orgUsable(db, ref("orgs.id"), item.id, {
473
+ itemId: item.id,
474
+ scope: target.scope,
475
+ orgs: target.orgs,
476
+ disabled: target.disabled,
477
+ resetComponents: target.scopeChange,
478
+ }).as("onAfter"),
479
+ ])
478
480
  .where("deleted_at", "is", null)
479
481
  .orderBy("id")
480
482
  .execute();
481
- const listedNow = new Set(await this.listed(item.id));
482
- const switches = await db
483
- .selectFrom("catalog_item_org_switches")
484
- .select(["org_id", "enabled"])
485
- .where("item_id", "=", item.id)
486
- .execute();
487
483
  const installs = await db
488
484
  .selectFrom("plugin_installs")
489
485
  .select(["id", "org_id"])
490
486
  .where("item_id", "=", item.id)
491
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
487
+ .where("version", "is not", null)
492
488
  .execute();
493
- const sw = new Map(switches.map((s) => [s.org_id, s.enabled]));
494
- const live = new Map(installs.map((a) => [a.org_id, a.id]));
495
- const listedAfter = new Set(target.orgs);
496
- const after = { scope: target.scope, disabled: target.disabled, builtin: false };
489
+ const live = new Map(installs.map((install) => [install.org_id, install.id]));
497
490
  const affected = [];
498
491
  const needsConfig = [];
499
- /** The orgs the plugin will be on in after the change (a live install kept or made). */
500
- const onAfter = new Set();
492
+ const onAfter = new Set(orgs.filter((org) => org.onAfter).map((org) => org.id));
501
493
  for (const org of orgs) {
502
- const s = sw.get(org.id) ?? null;
503
- const wanted = wantedOn(after, listedAfter.has(org.id), s);
504
494
  const installId = live.get(org.id);
505
- if (installId !== undefined) {
506
- // A live install another one depends on stays (spec §5 rule 9, as the sync does)
507
- if (wanted || (await this.sync.dependedOn(org.id, installId))) {
508
- onAfter.add(org.id);
509
- continue;
510
- }
495
+ if (installId !== undefined && !org.onAfter) {
511
496
  const p = await this.installer.previewUninstall(org.id, installId);
512
497
  affected.push({
513
498
  orgId: org.id,
@@ -519,7 +504,7 @@ let CatalogScopeService = class CatalogScopeService {
519
504
  });
520
505
  continue;
521
506
  }
522
- if (!wanted || wantedOn(item, listedNow.has(org.id), s))
507
+ if (!org.onAfter || org.onNow || installId !== undefined)
523
508
  continue;
524
509
  let needs = false;
525
510
  try {
@@ -535,7 +520,6 @@ let CatalogScopeService = class CatalogScopeService {
535
520
  // `needsConfig` names the orgs where its extension waits for the org's config
536
521
  if (needs)
537
522
  needsConfig.push(org.id);
538
- onAfter.add(org.id);
539
523
  }
540
524
  const { replaced, conflicts, themesLost } = await this.componentChanges(item, target, orgs, onAfter, affected);
541
525
  const themes = await themesPreview(db, themesLost);
@@ -585,7 +569,7 @@ let CatalogScopeService = class CatalogScopeService {
585
569
  scope: target.scope,
586
570
  disabled: target.disabled,
587
571
  listed: target.orgs.includes(org.id),
588
- installed: onAfter.has(org.id),
572
+ usable: onAfter.has(org.id),
589
573
  };
590
574
  const listed = listedIn(st, c.id, org.id);
591
575
  const s = switchOf(st, c.id, org.id);
@@ -656,27 +640,12 @@ let CatalogScopeService = class CatalogScopeService {
656
640
  */
657
641
  async followAgain(actor, itemId, replaced, opts) {
658
642
  for (const r of replaced) {
659
- const table = r.kind === "skill"
660
- ? "platform_skills"
661
- : r.kind === "agent_template"
662
- ? "platform_agent_templates"
663
- : r.kind === "theme"
664
- ? "platform_themes"
665
- : "platform_connector_templates";
666
- await this.db
667
- .updateTable(table)
668
- .set({
669
- scope_mode: "follow",
670
- updated_at: sql `now()`,
671
- })
672
- .where("id", "=", r.id)
673
- .where("scope_mode", "=", "own")
674
- .execute();
675
- await this.db
676
- .deleteFrom("component_scope_orgs")
677
- .where("kind", "=", r.kind)
678
- .where("component_id", "=", r.id)
679
- .execute();
643
+ await this.scopeWriter.replaceScope({
644
+ kind: r.kind,
645
+ id: r.id,
646
+ scopeMode: "follow",
647
+ orgs: [],
648
+ });
680
649
  await audit(this.db, {
681
650
  actorAccountId: actor,
682
651
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
@@ -690,12 +659,6 @@ let CatalogScopeService = class CatalogScopeService {
690
659
  __decorate([
691
660
  Transactional()
692
661
  ], CatalogScopeService.prototype, "writeShown", null);
693
- __decorate([
694
- Transactional()
695
- ], CatalogScopeService.prototype, "writeScope", null);
696
- __decorate([
697
- Transactional()
698
- ], CatalogScopeService.prototype, "writeDisabled", null);
699
662
  __decorate([
700
663
  Transactional()
701
664
  ], CatalogScopeService.prototype, "setShareable", null);
@@ -715,12 +678,13 @@ CatalogScopeService = __decorate([
715
678
  ,
716
679
  __param(0, Inject(KernelDb)),
717
680
  __param(1, Inject(SuperAdminLock)),
718
- __param(2, Inject(CatalogService)),
719
- __param(3, Inject(PluginImport)),
720
- __param(4, Inject(PluginInstaller)),
721
- __param(5, Inject(ExtensionAdmin)),
722
- __param(6, Inject(ExtensionAdminOps)),
723
- __param(7, Inject(PluginScopeSync)),
724
- __param(8, Inject(TransactionHost))
681
+ __param(2, Inject(ScopeWriter)),
682
+ __param(3, Inject(CatalogService)),
683
+ __param(4, Inject(PluginImport)),
684
+ __param(5, Inject(PluginInstaller)),
685
+ __param(6, Inject(ExtensionAdmin)),
686
+ __param(7, Inject(ExtensionAdminOps)),
687
+ __param(8, Inject(PluginScopeSync)),
688
+ __param(9, Inject(TransactionHost))
725
689
  ], CatalogScopeService);
726
690
  export { CatalogScopeService };