@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,7 +10,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { createHash, randomUUID } from "node:crypto";
11
11
  import { EXTENSION_POINTS, marketplaceEntryDeprecation, parseExtensionPoint, parseSkillMd, SKILL_ENTRY_FILE, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
- import { sql } from "kysely";
14
13
  import semver from "semver";
15
14
  import { revertTemplateVersionIn, softDeleteTemplateIn } from "../agents/templates.js";
16
15
  import { ApiError } from "../errors.js";
@@ -18,13 +17,11 @@ import { isExtensionEnabled } from "../extensions/enabled.js";
18
17
  import { OrgExtensionConfigs, } from "../extensions/org-config.js";
19
18
  import { ExtensionRegistry } from "../extensions/registry.js";
20
19
  import { audit } from "../identity/audit.js";
21
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
22
20
  import { afterCommit } from "../infra/database/after-commit.js";
23
21
  import { KernelDb } from "../infra/database/kernel-db.js";
24
22
  import { TransactionHost } from "../infra/database/transaction-host.js";
25
23
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
24
  import { OutboxService } from "../infra/outbox/outbox.service.js";
27
- import { KERNEL_LOGGER } from "../infra/tokens.js";
28
25
  import { OrgLock } from "../orgs/org-lock.js";
29
26
  import { packagePath } from "../packages/tgz.js";
30
27
  import { SkillsService, skillConflictError, skillConflicts, } from "../skills/skills.service.js";
@@ -36,10 +33,11 @@ import { isOAuth } from "../tools/credentials.js";
36
33
  import { findConnectorIn, lockOrgForActions, readCatalogAgentTemplates, readCatalogFiles, readCatalogTemplates, requiredActions, templateConnectorInput, templatePluginProblem, } from "./catalog-content.js";
37
34
  import { versionUsable } from "./catalog-items.js";
38
35
  import { agentDefinitionRefs, componentOn, connectorTemplateChoice, connectorTemplateState, connectorTemplatesOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, referenceIds, switchOf, themeIdClashes, } from "./component-state.js";
39
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
36
+ import { contentLostWhenOff, DEPENDENCY_DEPTH_LIMIT } from "./org-intent.js";
40
37
  import { assertItemInstallable, disabledPluginItems, pluginItemDisabled, resolveRequestsByInstall, } from "./request-rules.js";
41
38
  import { visibleTo } from "./scope.js";
42
- import { ScopeNoLongerWanted, ScopeStillWanted, wantedByScope } from "./scope-state.js";
39
+ import { pluginEffectsWanted, ScopeNoLongerWanted, ScopeStillWanted, wantedByScope, } from "./scope-state.js";
40
+ import { ScopeWriter } from "./scope-writer.js";
43
41
  import { oweTemplateConnectors } from "./template-connector-jobs.js";
44
42
  import { maxSatisfying, satisfiesRange } from "./versions.js";
45
43
  /** The confirm hash of an uninstall preview: sha256 over its sorted JSON (the scheme of `diffHash`). */
@@ -56,20 +54,12 @@ export function uninstallPreviewHash(p) {
56
54
  }))
57
55
  .digest("hex");
58
56
  }
59
- /** Upserts the org's switch row of an item in the caller's transaction (the org lock is held). */
60
- export async function upsertOrgSwitch(db, orgId, itemId, enabled, actor) {
61
- await db
62
- .insertInto("catalog_item_org_switches")
63
- .values({ item_id: itemId, org_id: orgId, enabled, updated_by: actor })
64
- .onConflict((oc) => oc.columns(["item_id", "org_id"]).doUpdateSet({
65
- enabled,
66
- updated_by: actor,
67
- updated_at: sql `now()`,
68
- }))
69
- .execute();
57
+ /** An install owns setup only when this plan or one of its dependencies applies org resources. */
58
+ function appliesOrgEffects(plan) {
59
+ return (plan.extension !== null ||
60
+ (plan.manifest.connectorTemplates?.length ?? 0) > 0 ||
61
+ plan.dependencies.some(({ plan: child }) => child === null || appliesOrgEffects(child)));
70
62
  }
71
- /** How deep plugin dependencies may nest (the root plugin's dependencies are level 1). */
72
- export const DEPENDENCY_DEPTH_LIMIT = 10;
73
63
  /** A failed install step, carried up through the dependency installs to the root install. */
74
64
  export class InstallFailure extends Error {
75
65
  step;
@@ -98,7 +88,6 @@ const ALL_ACTIONS = [
98
88
  ];
99
89
  const installNotFound = () => new ApiError("plugin.install_not_found", "Plugin install not found");
100
90
  const fail = (path, message) => new ApiError("validation_failed", "Request validation failed", [{ path, message }]);
101
- const isUniqueViolation = (e) => typeof e === "object" && e !== null && e.code === "23505";
102
91
  const unresolved = (name, range, why) => new ApiError("catalog.dependency_unresolved", `Dependency ${name}@${range} cannot be resolved: ${why}`, [{ dependency: name, range }]);
103
92
  const dependencyDisabled = (name) => new ApiError("catalog.dependency_disabled", `Dependency ${name} is disabled by the super admin, so this plugin cannot be installed`, [{ dependency: name }]);
104
93
  /**
@@ -277,18 +266,17 @@ let PluginInstaller = class PluginInstaller {
277
266
  registry;
278
267
  skills;
279
268
  orgConfigs;
280
- config;
269
+ scopeWriter;
281
270
  connectors;
282
- log;
283
271
  outbox;
284
272
  txHost;
285
273
  constructor(kdb,
286
274
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
287
275
  orgLock, storage,
288
276
  /** The loaded extensions and connectors of this replica (the extension registry). */
289
- registry, skills, orgConfigs, config,
277
+ registry, skills, orgConfigs, scopeWriter,
290
278
  /** Org connectors: installs create, upgrade and remove them. */
291
- connectors, log,
279
+ connectors,
292
280
  /** Owes the template connector ensure of an install's commit (`markInstalled`). */
293
281
  outbox, txHost) {
294
282
  this.kdb = kdb;
@@ -297,9 +285,8 @@ let PluginInstaller = class PluginInstaller {
297
285
  this.registry = registry;
298
286
  this.skills = skills;
299
287
  this.orgConfigs = orgConfigs;
300
- this.config = config;
288
+ this.scopeWriter = scopeWriter;
301
289
  this.connectors = connectors;
302
- this.log = log;
303
290
  this.outbox = outbox;
304
291
  this.txHost = txHost;
305
292
  }
@@ -307,10 +294,6 @@ let PluginInstaller = class PluginInstaller {
307
294
  get db() {
308
295
  return this.kdb.db;
309
296
  }
310
- /** `catalog.staleInstallMinutes`: an install `installing` for longer can be cleaned up by uninstalling it. */
311
- staleInstallMinutes() {
312
- return this.config.get().catalog.staleInstallMinutes;
313
- }
314
297
  /**
315
298
  * The checks an install runs before it creates anything, without the org's input (for the org
316
299
  * catalog to run before a request is created): dependency resolution, the extensions deployed and
@@ -327,6 +310,7 @@ let PluginInstaller = class PluginInstaller {
327
310
  const plan = await this.plan(orgId, actor, itemId, version, input, "", undefined);
328
311
  await this.assertNoSkillConflicts(orgId, plan);
329
312
  await this.assertNoThemeClashes(orgId, itemId);
313
+ const attemptedGeneration = actor !== null && via === undefined ? await this.effectGeneration(orgId, itemId) : undefined;
330
314
  let installId;
331
315
  try {
332
316
  installId = await this.execute(orgId, actor, plan, actorOpts, {
@@ -338,6 +322,9 @@ let PluginInstaller = class PluginInstaller {
338
322
  catch (e) {
339
323
  if (!(e instanceof InstallFailure))
340
324
  throw e;
325
+ if (actor !== null && via === undefined) {
326
+ await this.recordInstallFailure(orgId, actor, plan, e, switchOn === true, attemptedGeneration, actorOpts);
327
+ }
341
328
  // Retryable: a dependency another install is still installing, or the connector this install
342
329
  // would reuse went away meanwhile: a 409 as it is, with the message saying what to do
343
330
  if (e.cause instanceof ApiError &&
@@ -358,11 +345,77 @@ let PluginInstaller = class PluginInstaller {
358
345
  },
359
346
  ]);
360
347
  }
348
+ if (installId === null)
349
+ return null;
361
350
  const [view] = await this.list(orgId, installId);
362
351
  if (!view)
363
352
  throw installNotFound();
364
353
  return view;
365
354
  }
355
+ async effectGeneration(orgId, itemId) {
356
+ const work = await this.db
357
+ .selectFrom("plugin_effect_work")
358
+ .select("generation")
359
+ .where("item_id", "=", itemId)
360
+ .where("org_id", "=", orgId)
361
+ .executeTakeFirst();
362
+ return work?.generation;
363
+ }
364
+ async recordInstallFailure(orgId, actor, plan, failure, switchOn, attemptedGeneration, opts) {
365
+ await lockOrgForActions(this.orgLock, orgId, actor, planActions(plan));
366
+ await assertItemInstallable(this.db, orgId, plan.itemId);
367
+ if ((await this.effectGeneration(orgId, plan.itemId)) !== attemptedGeneration)
368
+ return;
369
+ const existing = await this.db
370
+ .selectFrom("plugin_installs")
371
+ .select("version")
372
+ .where("item_id", "=", plan.itemId)
373
+ .where("org_id", "=", orgId)
374
+ .executeTakeFirst();
375
+ if (existing?.version != null)
376
+ return;
377
+ if (switchOn) {
378
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: plan.itemId }, orgId, true, actor);
379
+ }
380
+ const work = await this.db
381
+ .updateTable("plugin_effect_work")
382
+ .set({ state: "settled", updated_at: new Date() })
383
+ .where("item_id", "=", plan.itemId)
384
+ .where("org_id", "=", orgId)
385
+ .returning("generation")
386
+ .executeTakeFirst();
387
+ const error = {
388
+ generation: work?.generation ?? "0",
389
+ operation: "install",
390
+ code: failure.code,
391
+ message: `Plugin setup failed at the ${failure.step} step (${failure.code}). Check the plugin's configuration and dependencies.`,
392
+ attemptedAt: new Date().toISOString(),
393
+ };
394
+ await this.db
395
+ .insertInto("plugin_installs")
396
+ .values({
397
+ id: randomUUID(),
398
+ item_id: plan.itemId,
399
+ org_id: orgId,
400
+ version: null,
401
+ installed_by: actor,
402
+ status: "install_failed",
403
+ error: JSON.stringify(error),
404
+ })
405
+ .onConflict((oc) => oc.columns(["org_id", "item_id"]).doUpdateSet({
406
+ status: "install_failed",
407
+ error: JSON.stringify(error),
408
+ }))
409
+ .execute();
410
+ await audit(this.db, {
411
+ actorAccountId: actor,
412
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
413
+ orgId,
414
+ action: "plugin.org_install_failed",
415
+ target: plan.itemId,
416
+ detail: { ...error, ...opts.auditDetail },
417
+ });
418
+ }
366
419
  /**
367
420
  * Refuses a plan whose skills would overwrite a skill of other provenance (spec §9.2, Decision
368
421
  * 8) with 409 `plugin.skill_conflict`, before anything is written: for the plugin and each
@@ -390,7 +443,7 @@ let PluginInstaller = class PluginInstaller {
390
443
  const listed = listedIn(st, c.id, orgId);
391
444
  const sw = switchOf(st, c.id, orgId);
392
445
  if (componentOn(c, p, listed, sw) ||
393
- !componentOn(c, p && { ...p, installed: true }, listed, sw)) {
446
+ !componentOn(c, p && { ...p, usable: true }, listed, sw)) {
394
447
  continue;
395
448
  }
396
449
  const clash = await themeIdClashes(this.db, orgId, c, c.name);
@@ -628,13 +681,14 @@ let PluginInstaller = class PluginInstaller {
628
681
  async findLiveDependency(db, orgId, dep, lock) {
629
682
  let q = db
630
683
  .selectFrom("plugin_installs")
631
- .select(["id", "version", "status"])
684
+ .select(["id", "version"])
632
685
  .where("org_id", "=", orgId)
633
686
  .where("item_id", "=", dep.itemId)
634
- .where("status", "<>", "failed");
687
+ .where("version", "is not", null);
635
688
  if (lock)
636
689
  q = q.forShare();
637
- return q.executeTakeFirst();
690
+ const row = await q.executeTakeFirst();
691
+ return row?.version == null ? undefined : { id: row.id, version: row.version };
638
692
  }
639
693
  /**
640
694
  * Records an install of `dep` as a `plugin` component of the install, checked and written in one
@@ -650,7 +704,7 @@ let PluginInstaller = class PluginInstaller {
650
704
  await this.orgLock.lock(orgId);
651
705
  const live = await this.findLiveDependency(t, orgId, dep, true);
652
706
  if (child !== undefined) {
653
- if (live?.id !== child || live.status !== "installed") {
707
+ if (live?.id !== child) {
654
708
  throw unresolved(dep.name, dep.range, "its install in this organization was removed meanwhile; try again");
655
709
  }
656
710
  await record({ kind: "plugin", ref: child, created: true, skillVersion: null });
@@ -661,9 +715,6 @@ let PluginInstaller = class PluginInstaller {
661
715
  if (!satisfiesRange(live.version, dep.range)) {
662
716
  throw unresolved(dep.name, dep.range, `this organization has version ${live.version} installed; uninstall it to install a matching version`);
663
717
  }
664
- if (live.status !== "installed") {
665
- throw new ApiError("plugin.install_in_progress", `Dependency ${dep.name} is being installed by another install in this organization; try again when it finishes. An install stuck for longer than catalog.staleInstallMinutes can be removed by uninstalling it`);
666
- }
667
718
  await record({ kind: "plugin", ref: live.id, created: false, skillVersion: null });
668
719
  return live.id;
669
720
  }
@@ -676,8 +727,9 @@ let PluginInstaller = class PluginInstaller {
676
727
  const { itemId } = plan;
677
728
  // The install row (role and item policy re-checked under the lock; one live install per org
678
729
  // and item)
679
- const installId = randomUUID();
680
- await this.createInstallRow(orgId, actor, plan, ctx, installId);
730
+ const installId = await this.createInstallRow(orgId, actor, plan, opts, ctx);
731
+ if (installId === null)
732
+ return null;
681
733
  const done = [];
682
734
  // Records a component in the transaction of the context (none: on its own; the install row
683
735
  // already cleaned up -> the FK fails, the install aborts and rolls back)
@@ -722,19 +774,14 @@ let PluginInstaller = class PluginInstaller {
722
774
  if (e instanceof InstallFailure) {
723
775
  throw new InstallFailure(e.step, e.cause, [dep.name, ...e.dependency], e.rolledBack);
724
776
  }
725
- // Another install created it meanwhile: use that one
726
- if (e instanceof ApiError &&
727
- e.code === "plugin.already_installed" &&
728
- (await this.recordDependency(orgId, dep, record)) !== undefined) {
729
- continue;
730
- }
731
777
  throw new InstallFailure("dependencies", e, [dep.name], true);
732
778
  }
733
- await this.recordDependency(orgId, dep, record, child);
779
+ if (child !== null)
780
+ await this.recordDependency(orgId, dep, record, child);
734
781
  }
735
782
  step = "extension";
736
783
  if (plan.extension !== null) {
737
- await this.enableExtension(orgId, plan.extension, { enabled: true }, actor, opts.actorTokenId, { viaItem: itemId, ...(nested && { approvedBy }) }, record);
784
+ await this.enableExtension(orgId, plan.extension, { enabled: true }, actor, opts.actorTokenId, { viaItem: itemId, ...(nested && { approvedBy }) });
738
785
  }
739
786
  step = "connectors";
740
787
  for (const ct of plan.templates) {
@@ -782,37 +829,14 @@ let PluginInstaller = class PluginInstaller {
782
829
  }
783
830
  catch (e) {
784
831
  const failure = e instanceof InstallFailure ? e : undefined;
785
- const code = failure ? failure.code : e instanceof ApiError ? e.code : "internal";
786
- const rollbackErrors = await this.rollback(orgId, actor, installId, done, opts);
787
- await this.markFailed(orgId, actor, installId, plan, ctx, { step, code, done, rollbackErrors }, opts);
788
- throw new InstallFailure(failure ? failure.step : step, failure ? failure.cause : e, failure ? failure.dependency : [], rollbackErrors.length === 0 && (failure?.rolledBack ?? true));
832
+ throw new InstallFailure(failure ? failure.step : step, failure ? failure.cause : e, failure ? failure.dependency : [], true);
789
833
  }
790
834
  }
791
- /**
792
- * The install row (role and item policy re-checked under the lock; one live install per org and
793
- * item). A step of the install: committed on its own.
794
- */
795
- /**
796
- * Enables a plugin's extension for the org and records it as a component of the install, in one
797
- * transaction (`put` joins it): "enabled before" is decided under the org row lock (already
798
- * enabled: `put` writes nothing, the config is untouched, the component is recorded as not
799
- * created), and the ledger row is written before the COMMIT, so no concurrent uninstall fits
800
- * between enabling and recording. Used only by a fresh install (and a dependency the install or a
801
- * platform update adds): a platform update of an installed plugin and switching an installed
802
- * plugin on again never call it, so an extension the org switched off stays off (extension switch
803
- * spec 2026-12-02 §3.2).
804
- */
805
- async enableExtension(orgId, name, input, actor, actorTokenId, opts, record) {
806
- const ifDisabled = { skipped: false };
807
- await this.orgConfigs.put(orgId, name, input, actor, actorTokenId, { ...opts, ifDisabled });
808
- await record({
809
- kind: "extension",
810
- ref: name,
811
- created: !ifDisabled.skipped,
812
- skillVersion: null,
813
- });
835
+ /** Validates extension setup and owes connector discovery in the caller's transaction. */
836
+ async enableExtension(orgId, name, input, actor, actorTokenId, opts) {
837
+ await this.orgConfigs.put(orgId, name, input, actor, actorTokenId, opts);
814
838
  }
815
- async createInstallRow(orgId, actor, plan, ctx, installId) {
839
+ async createInstallRow(orgId, actor, plan, opts, ctx) {
816
840
  const { itemId, version } = plan;
817
841
  const t = this.db;
818
842
  await lockOrgForActions(this.orgLock, orgId, actor, ctx.actions);
@@ -838,33 +862,52 @@ let PluginInstaller = class PluginInstaller {
838
862
  throw dependencyDisabled(plan.name);
839
863
  }
840
864
  await assertItemInstallable(t, orgId, itemId, ctx.approvedBy ?? itemId);
841
- const live = await t
865
+ if (ctx.switchOn === true && ctx.parent === undefined) {
866
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, true, actor);
867
+ }
868
+ if (!appliesOrgEffects(plan)) {
869
+ if (ctx.parent === undefined) {
870
+ await resolveRequestsByInstall(t, orgId, itemId, actor, opts);
871
+ if (ctx.switchOn === true) {
872
+ await audit(t, {
873
+ actorAccountId: actor,
874
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
875
+ orgId,
876
+ action: "catalog.scope_changed",
877
+ target: itemId,
878
+ detail: { enabled: true, ...opts.auditDetail },
879
+ });
880
+ }
881
+ }
882
+ return null;
883
+ }
884
+ const existing = await t
842
885
  .selectFrom("plugin_installs")
843
- .select("id")
886
+ .select(["id", "version"])
844
887
  .where("org_id", "=", orgId)
845
888
  .where("item_id", "=", itemId)
846
- .where("status", "<>", "failed")
847
889
  .executeTakeFirst();
848
- if (live)
890
+ if (existing?.version != null)
849
891
  throw alreadyInstalled();
850
- try {
851
- await t
852
- .insertInto("plugin_installs")
853
- .values({
854
- id: installId,
855
- org_id: orgId,
856
- item_id: itemId,
857
- version,
858
- status: "installing",
859
- installed_by: actor,
860
- })
861
- .execute();
862
- }
863
- catch (e) {
864
- if (isUniqueViolation(e))
865
- throw alreadyInstalled();
866
- throw e;
867
- }
892
+ const installId = existing?.id ?? randomUUID();
893
+ await t
894
+ .insertInto("plugin_installs")
895
+ .values({
896
+ id: installId,
897
+ org_id: orgId,
898
+ item_id: itemId,
899
+ version,
900
+ status: "on",
901
+ installed_by: actor,
902
+ })
903
+ .onConflict((oc) => oc.columns(["org_id", "item_id"]).doUpdateSet({
904
+ version,
905
+ status: "on",
906
+ error: null,
907
+ installed_by: actor,
908
+ }))
909
+ .execute();
910
+ return installId;
868
911
  }
869
912
  /** The install `installed` and its `plugin.org_installed` audit, under the org row lock (its own transaction). */
870
913
  async markInstalled(orgId, actor, installId, plan, done, ctx, opts) {
@@ -876,7 +919,7 @@ let PluginInstaller = class PluginInstaller {
876
919
  const updated = await t
877
920
  .updateTable("plugin_installs")
878
921
  .set((eb) => ({
879
- status: "installed",
922
+ status: "on",
880
923
  version: eb.fn.coalesce(eb
881
924
  .selectFrom("catalog_items as i")
882
925
  .select("i.platform_synced_version")
@@ -884,7 +927,6 @@ let PluginInstaller = class PluginInstaller {
884
927
  }))
885
928
  .where("id", "=", installId)
886
929
  .where("org_id", "=", orgId)
887
- .where("status", "=", "installing")
888
930
  .executeTakeFirst();
889
931
  // The install row was already cleaned up as stale: do not audit plugin.org_installed, roll
890
932
  // back
@@ -892,28 +934,10 @@ let PluginInstaller = class PluginInstaller {
892
934
  throw new ApiError("plugin.install_not_found", "The install record was cleaned up as stale while the install was running");
893
935
  }
894
936
  await resolveRequestsByInstall(t, orgId, itemId, actor, opts);
895
- // The org switch is written with the install, in one transaction under the org lock
896
- if (ctx.switchOn === true && ctx.parent === undefined) {
897
- await upsertOrgSwitch(t, orgId, itemId, true, actor);
898
- }
899
937
  // The org's choice of connector templates is written with the install too: the chosen ones on,
900
938
  // the ones left out off (they stay available on the connectors page)
901
- for (const sw of plan.templateSwitches) {
902
- await t
903
- .insertInto("component_org_switches")
904
- .values({
905
- kind: "connector_template",
906
- component_id: sw.componentId,
907
- org_id: orgId,
908
- enabled: sw.to,
909
- updated_by: actor,
910
- })
911
- .onConflict((oc) => oc.columns(["kind", "component_id", "org_id"]).doUpdateSet({
912
- enabled: sw.to,
913
- updated_by: actor,
914
- updated_at: sql `now()`,
915
- }))
916
- .execute();
939
+ for (const sw of ctx.via === "scope" ? [] : plan.templateSwitches) {
940
+ await this.scopeWriter.setOrgSwitch({ kind: "connector_template", id: sw.componentId }, orgId, sw.to, actor);
917
941
  await audit(t, {
918
942
  actorAccountId: actor,
919
943
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
@@ -952,37 +976,6 @@ let PluginInstaller = class PluginInstaller {
952
976
  },
953
977
  });
954
978
  }
955
- /** The install `failed` with `{ step, code }` and its `plugin.org_install_failed` audit (its own transaction). */
956
- async markFailed(orgId, actor, installId, plan, ctx, f, opts) {
957
- const { itemId, version } = plan;
958
- const { step, code, done, rollbackErrors } = f;
959
- const t = this.db;
960
- await t
961
- .updateTable("plugin_installs")
962
- .set({ status: "failed", error: JSON.stringify({ step, code }) })
963
- .where("id", "=", installId)
964
- .where("org_id", "=", orgId)
965
- .execute();
966
- await audit(t, {
967
- actorAccountId: actor,
968
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
969
- orgId,
970
- action: "plugin.org_install_failed",
971
- target: installId,
972
- detail: {
973
- itemId,
974
- name: plan.name,
975
- version,
976
- step,
977
- code,
978
- rolledBack: done,
979
- rollbackErrors,
980
- ...(ctx.parent !== undefined && { dependencyOf: ctx.parent }),
981
- ...(ctx.via !== undefined && { via: ctx.via }),
982
- ...opts.auditDetail,
983
- },
984
- });
985
- }
986
979
  /**
987
980
  * The extension to enable: the plugin's own, when it has one. Not loaded on this replica ->
988
981
  * `catalog.not_deployed`; not yet enabled in this org while its own catalog item is disabled ->
@@ -1002,76 +995,6 @@ let PluginInstaller = class PluginInstaller {
1002
995
  }
1003
996
  return name;
1004
997
  }
1005
- /**
1006
- * Undoes the components this install created, in reverse order (the role is not re-checked: it
1007
- * undoes this install's own changes); returns the ones that failed. The component rows of undone
1008
- * (or already gone) components are deleted in the same transaction, so cleaning up the failed
1009
- * install later only handles what failed to undo or was kept, and does not undo again an extension
1010
- * an org admin re-enabled by hand or a skill version a user uploaded since.
1011
- */
1012
- async rollback(orgId, actor, installId, done, opts) {
1013
- const errors = [];
1014
- for (const c of [...done].reverse()) {
1015
- if (!c.created && c.skillVersion === null)
1016
- continue;
1017
- try {
1018
- const disabled = await this.rollbackOne(orgId, actor, installId, c, opts);
1019
- for (const p of disabled)
1020
- await this.orgConfigs.afterDisable(orgId, p);
1021
- }
1022
- catch (e) {
1023
- errors.push({ kind: c.kind, ref: c.ref });
1024
- this.log.warn("plugin install rollback step failed", {
1025
- orgId,
1026
- kind: c.kind,
1027
- ref: c.ref,
1028
- error: e instanceof Error ? e.message : String(e),
1029
- });
1030
- }
1031
- }
1032
- return errors;
1033
- }
1034
- /**
1035
- * Undoes one component of a failed install and deletes its component row, under the org row lock,
1036
- * in a transaction of its own (committed when it returns); returns the extensions it disabled
1037
- * (the caller notifies them).
1038
- */
1039
- async rollbackOne(orgId, actor, installId, c, opts) {
1040
- const disabled = [];
1041
- const t = this.db;
1042
- await this.orgLock.lock(orgId);
1043
- if (c.kind === "plugin") {
1044
- // A dependency install this install created: uninstalled by the usual rules
1045
- const sub = { removed: [], kept: [] };
1046
- await this.uninstallIn(orgId, actor, c.ref, {
1047
- report: sub,
1048
- removing: new Set([installId]),
1049
- from: installId,
1050
- authorize: false,
1051
- reason: "plugin_install_rollback",
1052
- opts,
1053
- });
1054
- disabled.push(...sub.removed.filter((r) => r.kind === "extension").map((r) => r.ref));
1055
- }
1056
- else {
1057
- // Another enabled extension depends on it (only it provides what that one needs in this
1058
- // org): kept (its component row too), so the other does not lose its dependency
1059
- if (c.kind === "extension" &&
1060
- (await this.orgConfigs.enabledDependents(orgId, c.ref)).length > 0) {
1061
- return [];
1062
- }
1063
- const removed = await this.removeComponent(orgId, actor, c, "plugin_install_rollback");
1064
- if (removed && c.kind === "extension")
1065
- disabled.push(c.ref);
1066
- }
1067
- await t
1068
- .deleteFrom("plugin_install_components")
1069
- .where("install_id", "=", installId)
1070
- .where("kind", "=", c.kind)
1071
- .where("ref", "=", c.ref)
1072
- .execute();
1073
- return disabled;
1074
- }
1075
998
  /** Removes one component (one already gone is no error); returns whether anything changed. */
1076
999
  async removeComponent(orgId, actor, c, reason) {
1077
1000
  if (c.kind === "extension") {
@@ -1157,9 +1080,7 @@ let PluginInstaller = class PluginInstaller {
1157
1080
  .where("id", "=", installId)
1158
1081
  .where("org_id", "=", orgId)
1159
1082
  .executeTakeFirst();
1160
- if (row !== undefined &&
1161
- ((await wantedByScope(this.db, orgId, row.item_id)) ||
1162
- (await this.heir(orgId, new Set([installId]), "plugin", installId)) !== undefined)) {
1083
+ if (row !== undefined && (await pluginEffectsWanted(this.db, orgId, row.item_id))) {
1163
1084
  throw new ScopeStillWanted(orgId, row.item_id);
1164
1085
  }
1165
1086
  }
@@ -1195,6 +1116,10 @@ let PluginInstaller = class PluginInstaller {
1195
1116
  // a scope sync uninstall follows a scope change or disable that was guarded already)
1196
1117
  if (via !== "scope")
1197
1118
  await this.assertKeepsPlatformDefault(orgId, installId);
1119
+ // Reconciliation below must see the new intent when it considers the remaining roots.
1120
+ if (itemId !== undefined) {
1121
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, false, actor);
1122
+ }
1198
1123
  const outcome = await this.uninstallIn(orgId, actor, installId, {
1199
1124
  report,
1200
1125
  removing: new Set(),
@@ -1207,9 +1132,6 @@ let PluginInstaller = class PluginInstaller {
1207
1132
  if (outcome === "kept") {
1208
1133
  report.kept.push({ kind: "plugin", ref: installId, reason: "used_by_other_install" });
1209
1134
  }
1210
- if (itemId !== undefined && outcome === "removed") {
1211
- await upsertOrgSwitch(this.db, orgId, itemId, false, actor);
1212
- }
1213
1135
  afterCommit(async () => {
1214
1136
  for (const r of report.removed) {
1215
1137
  if (r.kind === "extension")
@@ -1246,7 +1168,7 @@ let PluginInstaller = class PluginInstaller {
1246
1168
  .innerJoin("plugin_installs as a", "a.id", "c.install_id")
1247
1169
  .select("a.id")
1248
1170
  .where("a.org_id", "=", orgId)
1249
- .where("a.status", "in", [...LIVE_INSTALL_STATUSES])
1171
+ .where("a.version", "is not", null)
1250
1172
  .where("c.kind", "=", kind)
1251
1173
  .where("c.ref", "=", ref);
1252
1174
  if (removing.size > 0)
@@ -1285,7 +1207,6 @@ let PluginInstaller = class PluginInstaller {
1285
1207
  mine.kept.push(x);
1286
1208
  ctx.report.kept.push(x);
1287
1209
  };
1288
- const staleMinutes = this.staleInstallMinutes();
1289
1210
  if (ctx.authorize) {
1290
1211
  const target = await t
1291
1212
  .selectFrom("plugin_installs as a")
@@ -1299,14 +1220,7 @@ let PluginInstaller = class PluginInstaller {
1299
1220
  const row = await t
1300
1221
  .selectFrom("plugin_installs as a")
1301
1222
  .innerJoin("catalog_items as i", "i.id", "a.item_id")
1302
- .select([
1303
- "a.id",
1304
- "a.item_id",
1305
- "a.version",
1306
- "a.status",
1307
- "i.name",
1308
- sql `a.installed_at < now() - make_interval(mins => ${staleMinutes})`.as("stale"),
1309
- ])
1223
+ .select(["a.id", "a.item_id", "a.version", "a.status", "i.name"])
1310
1224
  .where("a.id", "=", installId)
1311
1225
  .where("a.org_id", "=", orgId)
1312
1226
  .forUpdate("a")
@@ -1326,13 +1240,8 @@ let PluginInstaller = class PluginInstaller {
1326
1240
  await this.handOver(user, "plugin", installId);
1327
1241
  return "kept";
1328
1242
  }
1329
- if (row.status === "uninstalling" || (row.status === "installing" && !row.stale)) {
1330
- throw new ApiError("plugin.install_in_progress", `This plugin install is still in progress; it can be cleaned up after ${staleMinutes} minutes`);
1331
- }
1332
1243
  removing.add(installId);
1333
- // failed (already rolled back) and a stale installing (a replica crashed midway) are cleaned up
1334
- // as a rollback
1335
- const rollbackMode = row.status !== "installed";
1244
+ const rollbackMode = row.version === null;
1336
1245
  // A dependency install removed by a failed install's rollback removes what it created, like
1337
1246
  // the rolled-back install itself: it is a rollback, not a switch-off
1338
1247
  const connectorRollback = rollbackMode || ctx.reason === "plugin_install_rollback";
@@ -1343,6 +1252,18 @@ let PluginInstaller = class PluginInstaller {
1343
1252
  .orderBy("kind")
1344
1253
  .orderBy("ref")
1345
1254
  .execute();
1255
+ if (row.version !== null) {
1256
+ const version = await t
1257
+ .selectFrom("catalog_item_versions")
1258
+ .select("manifest")
1259
+ .where("item_id", "=", row.item_id)
1260
+ .where("version", "=", row.version)
1261
+ .executeTakeFirst();
1262
+ const manifest = version?.manifest;
1263
+ if (manifest?.extension && !comps.some((component) => component.kind === "extension")) {
1264
+ comps.push({ kind: "extension", ref: manifest.name, created: true, skill_version: null });
1265
+ }
1266
+ }
1346
1267
  // Skills and agent templates -> connectors -> extensions (in reverse requires order: dependents before providers)
1347
1268
  // -> dependency installs (created ones first)
1348
1269
  const extensionOrder = this.uninstallExtensionOrder(comps.filter((c) => c.kind === "extension").map((c) => c.ref));
@@ -1531,7 +1452,7 @@ let PluginInstaller = class PluginInstaller {
1531
1452
  status: r.status,
1532
1453
  installedBy: r.installed_by,
1533
1454
  installedAt: r.installed_at.toISOString(),
1534
- error: r.error ?? null,
1455
+ error: r.error,
1535
1456
  components: comps
1536
1457
  .filter((c) => c.install_id === r.id)
1537
1458
  .map((c) => ({
@@ -1556,11 +1477,11 @@ let PluginInstaller = class PluginInstaller {
1556
1477
  const row = await this.db
1557
1478
  .selectFrom("plugin_installs as a")
1558
1479
  .innerJoin("catalog_item_versions as v", (j) => j.onRef("v.item_id", "=", "a.item_id").onRef("v.version", "=", "a.version"))
1559
- .select(["a.item_id", "a.status", "v.manifest"])
1480
+ .select(["a.item_id", "v.manifest"])
1560
1481
  .where("a.id", "=", installId)
1561
1482
  .where("a.org_id", "=", orgId)
1562
1483
  .executeTakeFirst();
1563
- if (row?.status !== "installed")
1484
+ if (!row)
1564
1485
  return 0;
1565
1486
  let installed = 0;
1566
1487
  const record = async (c) => {
@@ -1586,8 +1507,10 @@ let PluginInstaller = class PluginInstaller {
1586
1507
  parent: installId,
1587
1508
  via: "scope",
1588
1509
  });
1589
- await this.recordDependency(orgId, dep, record, child);
1590
- installed += 1;
1510
+ if (child !== null) {
1511
+ await this.recordDependency(orgId, dep, record, child);
1512
+ installed += 1;
1513
+ }
1591
1514
  }
1592
1515
  return installed;
1593
1516
  }
@@ -1658,7 +1581,7 @@ let PluginInstaller = class PluginInstaller {
1658
1581
  .leftJoin("plugin_installs as a", (j) => j
1659
1582
  .onRef("a.item_id", "=", "t.catalog_item_id")
1660
1583
  .on("a.org_id", "=", orgId)
1661
- .on("a.status", "=", "installed"))
1584
+ .on("a.version", "is not", null))
1662
1585
  .select([
1663
1586
  "t.template_id",
1664
1587
  "t.catalog_item_id",
@@ -1748,12 +1671,12 @@ let PluginInstaller = class PluginInstaller {
1748
1671
  .innerJoin("plugin_installs as a", (j) => j
1749
1672
  .onRef("a.item_id", "=", "t.catalog_item_id")
1750
1673
  .on("a.org_id", "=", orgId)
1751
- .on("a.status", "=", "installed"))
1674
+ .on("a.version", "is not", null))
1752
1675
  .select(["t.template_id", "t.catalog_item_id", "t.file", "a.version"])
1753
1676
  .where("t.id", "=", platformTemplateId)
1754
1677
  .where("t.deleted_at", "is", null)
1755
1678
  .executeTakeFirst();
1756
- if (row?.catalog_item_id == null)
1679
+ if (row?.catalog_item_id == null || row.version === null)
1757
1680
  return undefined;
1758
1681
  const itemId = row.catalog_item_id;
1759
1682
  if ((await this.liveTemplateConnector(orgId, itemId, row.template_id)) !== undefined) {
@@ -1772,7 +1695,7 @@ let PluginInstaller = class PluginInstaller {
1772
1695
  return undefined;
1773
1696
  }
1774
1697
  const connectorId = await this.connectors.createDeferredIn(orgId, actor, ci, opts);
1775
- await this.recordTemplateConnectorIn(orgId, itemId, connectorId, ct.id, ["installed"]);
1698
+ await this.recordTemplateConnectorIn(orgId, itemId, connectorId, ct.id);
1776
1699
  return connectorId;
1777
1700
  }
1778
1701
  /**
@@ -1780,13 +1703,13 @@ let PluginInstaller = class PluginInstaller {
1780
1703
  * the item whose status is one of `statuses` (`created`: the plugin made it, so an uninstall and
1781
1704
  * upgrades see it), in the caller's transaction. True when such an install exists.
1782
1705
  */
1783
- async recordTemplateConnectorIn(orgId, itemId, connectorId, templateId, statuses) {
1706
+ async recordTemplateConnectorIn(orgId, itemId, connectorId, templateId) {
1784
1707
  const install = await this.db
1785
1708
  .selectFrom("plugin_installs")
1786
1709
  .select("id")
1787
1710
  .where("org_id", "=", orgId)
1788
1711
  .where("item_id", "=", itemId)
1789
- .where("status", "in", [...statuses])
1712
+ .where("version", "is not", null)
1790
1713
  .executeTakeFirst();
1791
1714
  if (!install)
1792
1715
  return false;
@@ -1810,7 +1733,7 @@ let PluginInstaller = class PluginInstaller {
1810
1733
  */
1811
1734
  async recordOnLiveInstall(orgId, itemId, connectorId, templateId) {
1812
1735
  await this.orgLock.lock(orgId);
1813
- await this.recordTemplateConnectorIn(orgId, itemId, connectorId, templateId, ["installed"]);
1736
+ await this.recordTemplateConnectorIn(orgId, itemId, connectorId, templateId);
1814
1737
  }
1815
1738
  /** The `connector@1` implementations loaded on this replica, by extension and kind. */
1816
1739
  loadedConnectors() {
@@ -1851,6 +1774,29 @@ let PluginInstaller = class PluginInstaller {
1851
1774
  .executeTakeFirst();
1852
1775
  if (!row)
1853
1776
  throw installNotFound();
1777
+ return this.previewRemoval(orgId, row, installId);
1778
+ }
1779
+ /** A pure content plugin can take components away without an org install row. */
1780
+ async previewContentOff(orgId, itemId) {
1781
+ const lost = await contentLostWhenOff(this.db, orgId, itemId);
1782
+ if (lost.length === 0)
1783
+ return null;
1784
+ const item = await this.db
1785
+ .selectFrom("catalog_items")
1786
+ .select(["id", "name", "latest_version", "platform_synced_version"])
1787
+ .where("id", "=", itemId)
1788
+ .where("deleted_at", "is", null)
1789
+ .executeTakeFirst();
1790
+ if (!item)
1791
+ throw installNotFound();
1792
+ return this.previewRemoval(orgId, {
1793
+ item_id: item.id,
1794
+ name: item.name,
1795
+ version: item.platform_synced_version ?? item.latest_version,
1796
+ }, null, lost);
1797
+ }
1798
+ async previewRemoval(orgId, row, installId, lostContent = [row.item_id]) {
1799
+ const t = this.db;
1854
1800
  const ledger = (id) => t
1855
1801
  .selectFrom("plugin_install_components")
1856
1802
  .select(["kind", "ref", "created"])
@@ -1858,7 +1804,7 @@ let PluginInstaller = class PluginInstaller {
1858
1804
  .orderBy("kind")
1859
1805
  .orderBy("ref")
1860
1806
  .execute();
1861
- const comps = (await ledger(installId)).filter((c) => c.kind !== "skill" && c.kind !== "agent_template");
1807
+ const comps = (installId === null ? [] : await ledger(installId)).filter((c) => c.kind !== "skill" && c.kind !== "agent_template");
1862
1808
  const agents = await agentDefinitionRefs(t, orgId);
1863
1809
  const used = new Map();
1864
1810
  const use = (a, kind, ref) => {
@@ -1914,7 +1860,7 @@ let PluginInstaller = class PluginInstaller {
1914
1860
  }
1915
1861
  for (const kind of ["skill", "agent_template"]) {
1916
1862
  const platform = await loadComponents(t, kind, { itemId });
1917
- const st = await loadScopeState(t, kind, platform);
1863
+ const st = await loadScopeState(t, kind, platform, orgId);
1918
1864
  const off = platform.filter((c) => c.scopeMode === "follow" &&
1919
1865
  componentOn(c, pluginFactsOf(st, c.itemId, orgId), listedIn(st, c.id, orgId), switchOf(st, c.id, orgId)));
1920
1866
  const refs = await referenceIds(t, orgId, kind, off.map((c) => c.id));
@@ -1926,7 +1872,7 @@ let PluginInstaller = class PluginInstaller {
1926
1872
  }
1927
1873
  }
1928
1874
  const themes = await loadComponents(t, "theme", { itemId });
1929
- const tst = await loadScopeState(t, "theme", themes);
1875
+ const tst = await loadScopeState(t, "theme", themes, orgId);
1930
1876
  for (const c of themes) {
1931
1877
  if (c.scopeMode === "follow" &&
1932
1878
  componentOn(c, pluginFactsOf(tst, c.itemId, orgId), listedIn(tst, c.id, orgId), switchOf(tst, c.id, orgId))) {
@@ -1936,7 +1882,9 @@ let PluginInstaller = class PluginInstaller {
1936
1882
  };
1937
1883
  /** The themes that go off in the org with the install (and the dependencies it removes). */
1938
1884
  const lostThemes = new Map();
1939
- await visit(row.item_id, comps, true, new Set([installId]));
1885
+ for (const itemId of lostContent) {
1886
+ await visit(itemId, comps, true, new Set(installId === null ? [] : [installId]));
1887
+ }
1940
1888
  const themes = await themesPreview(t, lostThemes);
1941
1889
  return {
1942
1890
  installId,
@@ -1969,23 +1917,23 @@ let PluginInstaller = class PluginInstaller {
1969
1917
  }
1970
1918
  };
1971
1919
  __decorate([
1972
- Transactional({ propagation: "requires_new" })
1920
+ Transactional()
1921
+ ], PluginInstaller.prototype, "recordInstallFailure", null);
1922
+ __decorate([
1923
+ Transactional({ propagation: "mandatory" })
1973
1924
  ], PluginInstaller.prototype, "recordDependency", null);
1925
+ __decorate([
1926
+ Transactional()
1927
+ ], PluginInstaller.prototype, "execute", null);
1974
1928
  __decorate([
1975
1929
  Transactional()
1976
1930
  ], PluginInstaller.prototype, "enableExtension", null);
1977
1931
  __decorate([
1978
- Transactional({ propagation: "requires_new" })
1932
+ Transactional({ propagation: "mandatory" })
1979
1933
  ], PluginInstaller.prototype, "createInstallRow", null);
1980
1934
  __decorate([
1981
- Transactional({ propagation: "requires_new" })
1935
+ Transactional({ propagation: "mandatory" })
1982
1936
  ], PluginInstaller.prototype, "markInstalled", null);
1983
- __decorate([
1984
- Transactional({ propagation: "requires_new" })
1985
- ], PluginInstaller.prototype, "markFailed", null);
1986
- __decorate([
1987
- Transactional({ propagation: "requires_new" })
1988
- ], PluginInstaller.prototype, "rollbackOne", null);
1989
1937
  __decorate([
1990
1938
  Transactional({ propagation: "mandatory" })
1991
1939
  ], PluginInstaller.prototype, "removeComponent", null);
@@ -2004,6 +1952,9 @@ __decorate([
2004
1952
  __decorate([
2005
1953
  Transactional({ propagation: "mandatory" })
2006
1954
  ], PluginInstaller.prototype, "decideRemovalIn", null);
1955
+ __decorate([
1956
+ Transactional()
1957
+ ], PluginInstaller.prototype, "addMissingDependencies", null);
2007
1958
  __decorate([
2008
1959
  Transactional({ propagation: "mandatory" })
2009
1960
  ], PluginInstaller.prototype, "createSwitchedOnTemplateConnectorIn", null);
@@ -2021,11 +1972,10 @@ PluginInstaller = __decorate([
2021
1972
  __param(3, Inject(ExtensionRegistry)),
2022
1973
  __param(4, Inject(SkillsService)),
2023
1974
  __param(5, Inject(OrgExtensionConfigs)),
2024
- __param(6, Inject(KernelConfigService)),
1975
+ __param(6, Inject(ScopeWriter)),
2025
1976
  __param(7, Inject(ConnectorsService)),
2026
- __param(8, Inject(KERNEL_LOGGER)),
2027
- __param(9, Inject(OutboxService)),
2028
- __param(10, Inject(TransactionHost))
1977
+ __param(8, Inject(OutboxService)),
1978
+ __param(9, Inject(TransactionHost))
2029
1979
  ], PluginInstaller);
2030
1980
  export { PluginInstaller };
2031
1981
  /**