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

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/extensions.controller.d.ts +5 -2
  3. package/dist/admin/extensions.controller.js +10 -1
  4. package/dist/admin/extensions.schemas.d.ts +4 -0
  5. package/dist/admin/extensions.schemas.js +9 -0
  6. package/dist/admin/health.service.d.ts +1 -1
  7. package/dist/admin/health.service.js +3 -3
  8. package/dist/catalog/catalog-content.d.ts +5 -7
  9. package/dist/catalog/catalog-items.js +1 -1
  10. package/dist/catalog/catalog-scope.service.js +5 -5
  11. package/dist/catalog/catalog.module.js +5 -4
  12. package/dist/catalog/catalog.service.d.ts +7 -1
  13. package/dist/catalog/catalog.service.js +19 -2
  14. package/dist/catalog/effect-work.d.ts +27 -0
  15. package/dist/catalog/effect-work.js +151 -0
  16. package/dist/catalog/jobs.d.ts +4 -1
  17. package/dist/catalog/jobs.js +14 -4
  18. package/dist/catalog/org-catalog.service.d.ts +2 -0
  19. package/dist/catalog/org-catalog.service.js +68 -12
  20. package/dist/catalog/org-intent.d.ts +4 -2
  21. package/dist/catalog/org-intent.js +25 -4
  22. package/dist/catalog/owned-items.d.ts +5 -1
  23. package/dist/catalog/owned-items.js +18 -3
  24. package/dist/catalog/plugin-import.d.ts +4 -2
  25. package/dist/catalog/plugin-import.js +10 -5
  26. package/dist/catalog/plugin-install.d.ts +17 -51
  27. package/dist/catalog/plugin-install.js +209 -235
  28. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  29. package/dist/catalog/plugin-upgrade.js +63 -34
  30. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  31. package/dist/catalog/scope-sync-workers.js +10 -26
  32. package/dist/catalog/scope-sync.d.ts +19 -114
  33. package/dist/catalog/scope-sync.js +220 -239
  34. package/dist/catalog/scope-writer.d.ts +10 -1
  35. package/dist/catalog/scope-writer.js +62 -4
  36. package/dist/catalog/template-connector-ensure.js +1 -1
  37. package/dist/catalog/unshare.js +1 -2
  38. package/dist/config/schema.d.ts +1 -1
  39. package/dist/config/schema.js +7 -4
  40. package/dist/db/kernel-schema.d.ts +18 -17
  41. package/dist/erasure/org-catalog.js +2 -2
  42. package/dist/erasure/org-rules.js +2 -2
  43. package/dist/extensions/admin-ops.d.ts +1 -1
  44. package/dist/extensions/admin-ops.js +1 -1
  45. package/dist/extensions/admin-view.d.ts +4 -1
  46. package/dist/extensions/admin-view.js +27 -11
  47. package/dist/extensions/bootstrap.d.ts +1 -1
  48. package/dist/extensions/bootstrap.js +2 -3
  49. package/dist/extensions/enabled.d.ts +159 -0
  50. package/dist/extensions/enabled.js +7 -0
  51. package/dist/extensions/host.d.ts +1 -0
  52. package/dist/extensions/host.js +5 -2
  53. package/dist/extensions/isolated/authorization.d.ts +8 -0
  54. package/dist/extensions/isolated/authorization.js +56 -11
  55. package/dist/extensions/isolated/broker.js +30 -11
  56. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  57. package/dist/extensions/isolated/engine-binds.js +82 -0
  58. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  59. package/dist/extensions/isolated/engine-policy.js +75 -0
  60. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  61. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  62. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  63. package/dist/extensions/isolated/engine-proxy.js +408 -0
  64. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  65. package/dist/extensions/isolated/engine-vaults.js +93 -0
  66. package/dist/extensions/isolated/lanes.d.ts +11 -3
  67. package/dist/extensions/isolated/lanes.js +43 -16
  68. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  69. package/dist/extensions/isolated/postgres-gate.js +6 -6
  70. package/dist/extensions/isolated/revision.d.ts +1 -1
  71. package/dist/extensions/isolated/revision.js +3 -2
  72. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  73. package/dist/extensions/isolated/sandbox.js +101 -117
  74. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  75. package/dist/extensions/lifecycle-topics.js +1 -0
  76. package/dist/extensions/lifecycle.js +23 -2
  77. package/dist/extensions/permission-view.d.ts +6 -1
  78. package/dist/inbox/platform-inbox.service.js +16 -27
  79. package/dist/infra/events/kernel-events.d.ts +4 -0
  80. package/dist/infra/outbox/registry.d.ts +3 -36
  81. package/dist/infra/outbox/registry.js +4 -49
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -1
  84. package/dist/orgs/org-lock.d.ts +3 -1
  85. package/dist/orgs/org-lock.js +3 -1
  86. package/dist/orgs/orgs.service.d.ts +3 -1
  87. package/dist/orgs/orgs.service.js +15 -8
  88. package/dist/overrides.d.ts +0 -3
  89. package/dist/overrides.js +0 -2
  90. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  91. package/dist/platform/ops/org-plugins.ops.js +5 -2
  92. package/dist/platform/ops/plugins.ops.js +11 -10
  93. package/dist/tools/registry.d.ts +1 -1
  94. package/dist/tools/registry.js +6 -2
  95. package/package.json +2 -2
  96. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  97. package/src/migrations/0232_contract_plugin_effect_schema.sql +49 -0
  98. package/dist/catalog/install-status.d.ts +0 -5
  99. package/dist/catalog/install-status.js +0 -5
  100. package/dist/catalog/scope-jobs.d.ts +0 -59
  101. 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,8 +33,7 @@ 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";
40
- import { DEPENDENCY_DEPTH_LIMIT } from "./org-intent.js";
36
+ import { contentLostWhenOff, DEPENDENCY_DEPTH_LIMIT } from "./org-intent.js";
41
37
  import { assertItemInstallable, disabledPluginItems, pluginItemDisabled, resolveRequestsByInstall, } from "./request-rules.js";
42
38
  import { visibleTo } from "./scope.js";
43
39
  import { pluginEffectsWanted, ScopeNoLongerWanted, ScopeStillWanted, wantedByScope, } from "./scope-state.js";
@@ -58,6 +54,12 @@ export function uninstallPreviewHash(p) {
58
54
  }))
59
55
  .digest("hex");
60
56
  }
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)));
62
+ }
61
63
  /** A failed install step, carried up through the dependency installs to the root install. */
62
64
  export class InstallFailure extends Error {
63
65
  step;
@@ -86,7 +88,6 @@ const ALL_ACTIONS = [
86
88
  ];
87
89
  const installNotFound = () => new ApiError("plugin.install_not_found", "Plugin install not found");
88
90
  const fail = (path, message) => new ApiError("validation_failed", "Request validation failed", [{ path, message }]);
89
- const isUniqueViolation = (e) => typeof e === "object" && e !== null && e.code === "23505";
90
91
  const unresolved = (name, range, why) => new ApiError("catalog.dependency_unresolved", `Dependency ${name}@${range} cannot be resolved: ${why}`, [{ dependency: name, range }]);
91
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 }]);
92
93
  /**
@@ -266,18 +267,16 @@ let PluginInstaller = class PluginInstaller {
266
267
  skills;
267
268
  orgConfigs;
268
269
  scopeWriter;
269
- config;
270
270
  connectors;
271
- log;
272
271
  outbox;
273
272
  txHost;
274
273
  constructor(kdb,
275
274
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
276
275
  orgLock, storage,
277
276
  /** The loaded extensions and connectors of this replica (the extension registry). */
278
- registry, skills, orgConfigs, scopeWriter, config,
277
+ registry, skills, orgConfigs, scopeWriter,
279
278
  /** Org connectors: installs create, upgrade and remove them. */
280
- connectors, log,
279
+ connectors,
281
280
  /** Owes the template connector ensure of an install's commit (`markInstalled`). */
282
281
  outbox, txHost) {
283
282
  this.kdb = kdb;
@@ -287,9 +286,7 @@ let PluginInstaller = class PluginInstaller {
287
286
  this.skills = skills;
288
287
  this.orgConfigs = orgConfigs;
289
288
  this.scopeWriter = scopeWriter;
290
- this.config = config;
291
289
  this.connectors = connectors;
292
- this.log = log;
293
290
  this.outbox = outbox;
294
291
  this.txHost = txHost;
295
292
  }
@@ -297,10 +294,6 @@ let PluginInstaller = class PluginInstaller {
297
294
  get db() {
298
295
  return this.kdb.db;
299
296
  }
300
- /** `catalog.staleInstallMinutes`: an install `installing` for longer can be cleaned up by uninstalling it. */
301
- staleInstallMinutes() {
302
- return this.config.get().catalog.staleInstallMinutes;
303
- }
304
297
  /**
305
298
  * The checks an install runs before it creates anything, without the org's input (for the org
306
299
  * catalog to run before a request is created): dependency resolution, the extensions deployed and
@@ -317,6 +310,7 @@ let PluginInstaller = class PluginInstaller {
317
310
  const plan = await this.plan(orgId, actor, itemId, version, input, "", undefined);
318
311
  await this.assertNoSkillConflicts(orgId, plan);
319
312
  await this.assertNoThemeClashes(orgId, itemId);
313
+ const attemptedGeneration = actor !== null && via === undefined ? await this.effectGeneration(orgId, itemId) : undefined;
320
314
  let installId;
321
315
  try {
322
316
  installId = await this.execute(orgId, actor, plan, actorOpts, {
@@ -328,6 +322,9 @@ let PluginInstaller = class PluginInstaller {
328
322
  catch (e) {
329
323
  if (!(e instanceof InstallFailure))
330
324
  throw e;
325
+ if (actor !== null && via === undefined) {
326
+ await this.recordInstallFailure(orgId, actor, plan, e, switchOn === true, attemptedGeneration, actorOpts);
327
+ }
331
328
  // Retryable: a dependency another install is still installing, or the connector this install
332
329
  // would reuse went away meanwhile: a 409 as it is, with the message saying what to do
333
330
  if (e.cause instanceof ApiError &&
@@ -348,11 +345,77 @@ let PluginInstaller = class PluginInstaller {
348
345
  },
349
346
  ]);
350
347
  }
348
+ if (installId === null)
349
+ return null;
351
350
  const [view] = await this.list(orgId, installId);
352
351
  if (!view)
353
352
  throw installNotFound();
354
353
  return view;
355
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
+ }
356
419
  /**
357
420
  * Refuses a plan whose skills would overwrite a skill of other provenance (spec §9.2, Decision
358
421
  * 8) with 409 `plugin.skill_conflict`, before anything is written: for the plugin and each
@@ -618,13 +681,14 @@ let PluginInstaller = class PluginInstaller {
618
681
  async findLiveDependency(db, orgId, dep, lock) {
619
682
  let q = db
620
683
  .selectFrom("plugin_installs")
621
- .select(["id", "version", "status"])
684
+ .select(["id", "version"])
622
685
  .where("org_id", "=", orgId)
623
686
  .where("item_id", "=", dep.itemId)
624
- .where("status", "<>", "failed");
687
+ .where("version", "is not", null);
625
688
  if (lock)
626
689
  q = q.forShare();
627
- return q.executeTakeFirst();
690
+ const row = await q.executeTakeFirst();
691
+ return row?.version == null ? undefined : { id: row.id, version: row.version };
628
692
  }
629
693
  /**
630
694
  * Records an install of `dep` as a `plugin` component of the install, checked and written in one
@@ -640,7 +704,7 @@ let PluginInstaller = class PluginInstaller {
640
704
  await this.orgLock.lock(orgId);
641
705
  const live = await this.findLiveDependency(t, orgId, dep, true);
642
706
  if (child !== undefined) {
643
- if (live?.id !== child || live.status !== "installed") {
707
+ if (live?.id !== child) {
644
708
  throw unresolved(dep.name, dep.range, "its install in this organization was removed meanwhile; try again");
645
709
  }
646
710
  await record({ kind: "plugin", ref: child, created: true, skillVersion: null });
@@ -651,9 +715,6 @@ let PluginInstaller = class PluginInstaller {
651
715
  if (!satisfiesRange(live.version, dep.range)) {
652
716
  throw unresolved(dep.name, dep.range, `this organization has version ${live.version} installed; uninstall it to install a matching version`);
653
717
  }
654
- if (live.status !== "installed") {
655
- 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`);
656
- }
657
718
  await record({ kind: "plugin", ref: live.id, created: false, skillVersion: null });
658
719
  return live.id;
659
720
  }
@@ -666,8 +727,9 @@ let PluginInstaller = class PluginInstaller {
666
727
  const { itemId } = plan;
667
728
  // The install row (role and item policy re-checked under the lock; one live install per org
668
729
  // and item)
669
- const installId = randomUUID();
670
- 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;
671
733
  const done = [];
672
734
  // Records a component in the transaction of the context (none: on its own; the install row
673
735
  // already cleaned up -> the FK fails, the install aborts and rolls back)
@@ -712,19 +774,14 @@ let PluginInstaller = class PluginInstaller {
712
774
  if (e instanceof InstallFailure) {
713
775
  throw new InstallFailure(e.step, e.cause, [dep.name, ...e.dependency], e.rolledBack);
714
776
  }
715
- // Another install created it meanwhile: use that one
716
- if (e instanceof ApiError &&
717
- e.code === "plugin.already_installed" &&
718
- (await this.recordDependency(orgId, dep, record)) !== undefined) {
719
- continue;
720
- }
721
777
  throw new InstallFailure("dependencies", e, [dep.name], true);
722
778
  }
723
- await this.recordDependency(orgId, dep, record, child);
779
+ if (child !== null)
780
+ await this.recordDependency(orgId, dep, record, child);
724
781
  }
725
782
  step = "extension";
726
783
  if (plan.extension !== null) {
727
- 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 }) });
728
785
  }
729
786
  step = "connectors";
730
787
  for (const ct of plan.templates) {
@@ -772,37 +829,14 @@ let PluginInstaller = class PluginInstaller {
772
829
  }
773
830
  catch (e) {
774
831
  const failure = e instanceof InstallFailure ? e : undefined;
775
- const code = failure ? failure.code : e instanceof ApiError ? e.code : "internal";
776
- const rollbackErrors = await this.rollback(orgId, actor, installId, done, opts);
777
- await this.markFailed(orgId, actor, installId, plan, ctx, { step, code, done, rollbackErrors }, opts);
778
- 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);
779
833
  }
780
834
  }
781
- /**
782
- * The install row (role and item policy re-checked under the lock; one live install per org and
783
- * item). A step of the install: committed on its own.
784
- */
785
- /**
786
- * Enables a plugin's extension for the org and records it as a component of the install, in one
787
- * transaction (`put` joins it): "enabled before" is decided under the org row lock (already
788
- * enabled: `put` writes nothing, the config is untouched, the component is recorded as not
789
- * created), and the ledger row is written before the COMMIT, so no concurrent uninstall fits
790
- * between enabling and recording. Used only by a fresh install (and a dependency the install or a
791
- * platform update adds): a platform update of an installed plugin and switching an installed
792
- * plugin on again never call it, so an extension the org switched off stays off (extension switch
793
- * spec 2026-12-02 §3.2).
794
- */
795
- async enableExtension(orgId, name, input, actor, actorTokenId, opts, record) {
796
- const ifDisabled = { skipped: false };
797
- await this.orgConfigs.put(orgId, name, input, actor, actorTokenId, { ...opts, ifDisabled });
798
- await record({
799
- kind: "extension",
800
- ref: name,
801
- created: !ifDisabled.skipped,
802
- skillVersion: null,
803
- });
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);
804
838
  }
805
- async createInstallRow(orgId, actor, plan, ctx, installId) {
839
+ async createInstallRow(orgId, actor, plan, opts, ctx) {
806
840
  const { itemId, version } = plan;
807
841
  const t = this.db;
808
842
  await lockOrgForActions(this.orgLock, orgId, actor, ctx.actions);
@@ -828,37 +862,52 @@ let PluginInstaller = class PluginInstaller {
828
862
  throw dependencyDisabled(plan.name);
829
863
  }
830
864
  await assertItemInstallable(t, orgId, itemId, ctx.approvedBy ?? itemId);
831
- 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
832
885
  .selectFrom("plugin_installs")
833
- .select("id")
886
+ .select(["id", "version"])
834
887
  .where("org_id", "=", orgId)
835
888
  .where("item_id", "=", itemId)
836
- .where("status", "<>", "failed")
837
889
  .executeTakeFirst();
838
- if (live)
890
+ if (existing?.version != null)
839
891
  throw alreadyInstalled();
840
- try {
841
- await t
842
- .insertInto("plugin_installs")
843
- .values({
844
- id: installId,
845
- org_id: orgId,
846
- item_id: itemId,
847
- version,
848
- status: "installing",
849
- installed_by: actor,
850
- })
851
- .execute();
852
- }
853
- catch (e) {
854
- if (isUniqueViolation(e))
855
- throw alreadyInstalled();
856
- throw e;
857
- }
858
- // The connector and extension setup reads the committed bundle choice.
859
- if (ctx.switchOn === true && ctx.parent === undefined) {
860
- await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, true, actor);
861
- }
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;
862
911
  }
863
912
  /** The install `installed` and its `plugin.org_installed` audit, under the org row lock (its own transaction). */
864
913
  async markInstalled(orgId, actor, installId, plan, done, ctx, opts) {
@@ -870,7 +919,7 @@ let PluginInstaller = class PluginInstaller {
870
919
  const updated = await t
871
920
  .updateTable("plugin_installs")
872
921
  .set((eb) => ({
873
- status: "installed",
922
+ status: "on",
874
923
  version: eb.fn.coalesce(eb
875
924
  .selectFrom("catalog_items as i")
876
925
  .select("i.platform_synced_version")
@@ -878,7 +927,6 @@ let PluginInstaller = class PluginInstaller {
878
927
  }))
879
928
  .where("id", "=", installId)
880
929
  .where("org_id", "=", orgId)
881
- .where("status", "=", "installing")
882
930
  .executeTakeFirst();
883
931
  // The install row was already cleaned up as stale: do not audit plugin.org_installed, roll
884
932
  // back
@@ -888,7 +936,7 @@ let PluginInstaller = class PluginInstaller {
888
936
  await resolveRequestsByInstall(t, orgId, itemId, actor, opts);
889
937
  // The org's choice of connector templates is written with the install too: the chosen ones on,
890
938
  // the ones left out off (they stay available on the connectors page)
891
- for (const sw of plan.templateSwitches) {
939
+ for (const sw of ctx.via === "scope" ? [] : plan.templateSwitches) {
892
940
  await this.scopeWriter.setOrgSwitch({ kind: "connector_template", id: sw.componentId }, orgId, sw.to, actor);
893
941
  await audit(t, {
894
942
  actorAccountId: actor,
@@ -928,37 +976,6 @@ let PluginInstaller = class PluginInstaller {
928
976
  },
929
977
  });
930
978
  }
931
- /** The install `failed` with `{ step, code }` and its `plugin.org_install_failed` audit (its own transaction). */
932
- async markFailed(orgId, actor, installId, plan, ctx, f, opts) {
933
- const { itemId, version } = plan;
934
- const { step, code, done, rollbackErrors } = f;
935
- const t = this.db;
936
- await t
937
- .updateTable("plugin_installs")
938
- .set({ status: "failed", error: JSON.stringify({ step, code }) })
939
- .where("id", "=", installId)
940
- .where("org_id", "=", orgId)
941
- .execute();
942
- await audit(t, {
943
- actorAccountId: actor,
944
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
945
- orgId,
946
- action: "plugin.org_install_failed",
947
- target: installId,
948
- detail: {
949
- itemId,
950
- name: plan.name,
951
- version,
952
- step,
953
- code,
954
- rolledBack: done,
955
- rollbackErrors,
956
- ...(ctx.parent !== undefined && { dependencyOf: ctx.parent }),
957
- ...(ctx.via !== undefined && { via: ctx.via }),
958
- ...opts.auditDetail,
959
- },
960
- });
961
- }
962
979
  /**
963
980
  * The extension to enable: the plugin's own, when it has one. Not loaded on this replica ->
964
981
  * `catalog.not_deployed`; not yet enabled in this org while its own catalog item is disabled ->
@@ -978,76 +995,6 @@ let PluginInstaller = class PluginInstaller {
978
995
  }
979
996
  return name;
980
997
  }
981
- /**
982
- * Undoes the components this install created, in reverse order (the role is not re-checked: it
983
- * undoes this install's own changes); returns the ones that failed. The component rows of undone
984
- * (or already gone) components are deleted in the same transaction, so cleaning up the failed
985
- * install later only handles what failed to undo or was kept, and does not undo again an extension
986
- * an org admin re-enabled by hand or a skill version a user uploaded since.
987
- */
988
- async rollback(orgId, actor, installId, done, opts) {
989
- const errors = [];
990
- for (const c of [...done].reverse()) {
991
- if (!c.created && c.skillVersion === null)
992
- continue;
993
- try {
994
- const disabled = await this.rollbackOne(orgId, actor, installId, c, opts);
995
- for (const p of disabled)
996
- await this.orgConfigs.afterDisable(orgId, p);
997
- }
998
- catch (e) {
999
- errors.push({ kind: c.kind, ref: c.ref });
1000
- this.log.warn("plugin install rollback step failed", {
1001
- orgId,
1002
- kind: c.kind,
1003
- ref: c.ref,
1004
- error: e instanceof Error ? e.message : String(e),
1005
- });
1006
- }
1007
- }
1008
- return errors;
1009
- }
1010
- /**
1011
- * Undoes one component of a failed install and deletes its component row, under the org row lock,
1012
- * in a transaction of its own (committed when it returns); returns the extensions it disabled
1013
- * (the caller notifies them).
1014
- */
1015
- async rollbackOne(orgId, actor, installId, c, opts) {
1016
- const disabled = [];
1017
- const t = this.db;
1018
- await this.orgLock.lock(orgId);
1019
- if (c.kind === "plugin") {
1020
- // A dependency install this install created: uninstalled by the usual rules
1021
- const sub = { removed: [], kept: [] };
1022
- await this.uninstallIn(orgId, actor, c.ref, {
1023
- report: sub,
1024
- removing: new Set([installId]),
1025
- from: installId,
1026
- authorize: false,
1027
- reason: "plugin_install_rollback",
1028
- opts,
1029
- });
1030
- disabled.push(...sub.removed.filter((r) => r.kind === "extension").map((r) => r.ref));
1031
- }
1032
- else {
1033
- // Another enabled extension depends on it (only it provides what that one needs in this
1034
- // org): kept (its component row too), so the other does not lose its dependency
1035
- if (c.kind === "extension" &&
1036
- (await this.orgConfigs.enabledDependents(orgId, c.ref)).length > 0) {
1037
- return [];
1038
- }
1039
- const removed = await this.removeComponent(orgId, actor, c, "plugin_install_rollback");
1040
- if (removed && c.kind === "extension")
1041
- disabled.push(c.ref);
1042
- }
1043
- await t
1044
- .deleteFrom("plugin_install_components")
1045
- .where("install_id", "=", installId)
1046
- .where("kind", "=", c.kind)
1047
- .where("ref", "=", c.ref)
1048
- .execute();
1049
- return disabled;
1050
- }
1051
998
  /** Removes one component (one already gone is no error); returns whether anything changed. */
1052
999
  async removeComponent(orgId, actor, c, reason) {
1053
1000
  if (c.kind === "extension") {
@@ -1221,7 +1168,7 @@ let PluginInstaller = class PluginInstaller {
1221
1168
  .innerJoin("plugin_installs as a", "a.id", "c.install_id")
1222
1169
  .select("a.id")
1223
1170
  .where("a.org_id", "=", orgId)
1224
- .where("a.status", "in", [...LIVE_INSTALL_STATUSES])
1171
+ .where("a.version", "is not", null)
1225
1172
  .where("c.kind", "=", kind)
1226
1173
  .where("c.ref", "=", ref);
1227
1174
  if (removing.size > 0)
@@ -1260,7 +1207,6 @@ let PluginInstaller = class PluginInstaller {
1260
1207
  mine.kept.push(x);
1261
1208
  ctx.report.kept.push(x);
1262
1209
  };
1263
- const staleMinutes = this.staleInstallMinutes();
1264
1210
  if (ctx.authorize) {
1265
1211
  const target = await t
1266
1212
  .selectFrom("plugin_installs as a")
@@ -1274,14 +1220,7 @@ let PluginInstaller = class PluginInstaller {
1274
1220
  const row = await t
1275
1221
  .selectFrom("plugin_installs as a")
1276
1222
  .innerJoin("catalog_items as i", "i.id", "a.item_id")
1277
- .select([
1278
- "a.id",
1279
- "a.item_id",
1280
- "a.version",
1281
- "a.status",
1282
- "i.name",
1283
- sql `a.installed_at < now() - make_interval(mins => ${staleMinutes})`.as("stale"),
1284
- ])
1223
+ .select(["a.id", "a.item_id", "a.version", "a.status", "i.name"])
1285
1224
  .where("a.id", "=", installId)
1286
1225
  .where("a.org_id", "=", orgId)
1287
1226
  .forUpdate("a")
@@ -1301,13 +1240,8 @@ let PluginInstaller = class PluginInstaller {
1301
1240
  await this.handOver(user, "plugin", installId);
1302
1241
  return "kept";
1303
1242
  }
1304
- if (row.status === "uninstalling" || (row.status === "installing" && !row.stale)) {
1305
- throw new ApiError("plugin.install_in_progress", `This plugin install is still in progress; it can be cleaned up after ${staleMinutes} minutes`);
1306
- }
1307
1243
  removing.add(installId);
1308
- // failed (already rolled back) and a stale installing (a replica crashed midway) are cleaned up
1309
- // as a rollback
1310
- const rollbackMode = row.status !== "installed";
1244
+ const rollbackMode = row.version === null;
1311
1245
  // A dependency install removed by a failed install's rollback removes what it created, like
1312
1246
  // the rolled-back install itself: it is a rollback, not a switch-off
1313
1247
  const connectorRollback = rollbackMode || ctx.reason === "plugin_install_rollback";
@@ -1318,6 +1252,18 @@ let PluginInstaller = class PluginInstaller {
1318
1252
  .orderBy("kind")
1319
1253
  .orderBy("ref")
1320
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
+ }
1321
1267
  // Skills and agent templates -> connectors -> extensions (in reverse requires order: dependents before providers)
1322
1268
  // -> dependency installs (created ones first)
1323
1269
  const extensionOrder = this.uninstallExtensionOrder(comps.filter((c) => c.kind === "extension").map((c) => c.ref));
@@ -1506,7 +1452,7 @@ let PluginInstaller = class PluginInstaller {
1506
1452
  status: r.status,
1507
1453
  installedBy: r.installed_by,
1508
1454
  installedAt: r.installed_at.toISOString(),
1509
- error: r.error ?? null,
1455
+ error: r.error,
1510
1456
  components: comps
1511
1457
  .filter((c) => c.install_id === r.id)
1512
1458
  .map((c) => ({
@@ -1531,11 +1477,11 @@ let PluginInstaller = class PluginInstaller {
1531
1477
  const row = await this.db
1532
1478
  .selectFrom("plugin_installs as a")
1533
1479
  .innerJoin("catalog_item_versions as v", (j) => j.onRef("v.item_id", "=", "a.item_id").onRef("v.version", "=", "a.version"))
1534
- .select(["a.item_id", "a.status", "v.manifest"])
1480
+ .select(["a.item_id", "v.manifest"])
1535
1481
  .where("a.id", "=", installId)
1536
1482
  .where("a.org_id", "=", orgId)
1537
1483
  .executeTakeFirst();
1538
- if (row?.status !== "installed")
1484
+ if (!row)
1539
1485
  return 0;
1540
1486
  let installed = 0;
1541
1487
  const record = async (c) => {
@@ -1561,8 +1507,10 @@ let PluginInstaller = class PluginInstaller {
1561
1507
  parent: installId,
1562
1508
  via: "scope",
1563
1509
  });
1564
- await this.recordDependency(orgId, dep, record, child);
1565
- installed += 1;
1510
+ if (child !== null) {
1511
+ await this.recordDependency(orgId, dep, record, child);
1512
+ installed += 1;
1513
+ }
1566
1514
  }
1567
1515
  return installed;
1568
1516
  }
@@ -1633,7 +1581,7 @@ let PluginInstaller = class PluginInstaller {
1633
1581
  .leftJoin("plugin_installs as a", (j) => j
1634
1582
  .onRef("a.item_id", "=", "t.catalog_item_id")
1635
1583
  .on("a.org_id", "=", orgId)
1636
- .on("a.status", "=", "installed"))
1584
+ .on("a.version", "is not", null))
1637
1585
  .select([
1638
1586
  "t.template_id",
1639
1587
  "t.catalog_item_id",
@@ -1723,12 +1671,12 @@ let PluginInstaller = class PluginInstaller {
1723
1671
  .innerJoin("plugin_installs as a", (j) => j
1724
1672
  .onRef("a.item_id", "=", "t.catalog_item_id")
1725
1673
  .on("a.org_id", "=", orgId)
1726
- .on("a.status", "=", "installed"))
1674
+ .on("a.version", "is not", null))
1727
1675
  .select(["t.template_id", "t.catalog_item_id", "t.file", "a.version"])
1728
1676
  .where("t.id", "=", platformTemplateId)
1729
1677
  .where("t.deleted_at", "is", null)
1730
1678
  .executeTakeFirst();
1731
- if (row?.catalog_item_id == null)
1679
+ if (row?.catalog_item_id == null || row.version === null)
1732
1680
  return undefined;
1733
1681
  const itemId = row.catalog_item_id;
1734
1682
  if ((await this.liveTemplateConnector(orgId, itemId, row.template_id)) !== undefined) {
@@ -1747,7 +1695,7 @@ let PluginInstaller = class PluginInstaller {
1747
1695
  return undefined;
1748
1696
  }
1749
1697
  const connectorId = await this.connectors.createDeferredIn(orgId, actor, ci, opts);
1750
- await this.recordTemplateConnectorIn(orgId, itemId, connectorId, ct.id, ["installed"]);
1698
+ await this.recordTemplateConnectorIn(orgId, itemId, connectorId, ct.id);
1751
1699
  return connectorId;
1752
1700
  }
1753
1701
  /**
@@ -1755,13 +1703,13 @@ let PluginInstaller = class PluginInstaller {
1755
1703
  * the item whose status is one of `statuses` (`created`: the plugin made it, so an uninstall and
1756
1704
  * upgrades see it), in the caller's transaction. True when such an install exists.
1757
1705
  */
1758
- async recordTemplateConnectorIn(orgId, itemId, connectorId, templateId, statuses) {
1706
+ async recordTemplateConnectorIn(orgId, itemId, connectorId, templateId) {
1759
1707
  const install = await this.db
1760
1708
  .selectFrom("plugin_installs")
1761
1709
  .select("id")
1762
1710
  .where("org_id", "=", orgId)
1763
1711
  .where("item_id", "=", itemId)
1764
- .where("status", "in", [...statuses])
1712
+ .where("version", "is not", null)
1765
1713
  .executeTakeFirst();
1766
1714
  if (!install)
1767
1715
  return false;
@@ -1785,7 +1733,7 @@ let PluginInstaller = class PluginInstaller {
1785
1733
  */
1786
1734
  async recordOnLiveInstall(orgId, itemId, connectorId, templateId) {
1787
1735
  await this.orgLock.lock(orgId);
1788
- await this.recordTemplateConnectorIn(orgId, itemId, connectorId, templateId, ["installed"]);
1736
+ await this.recordTemplateConnectorIn(orgId, itemId, connectorId, templateId);
1789
1737
  }
1790
1738
  /** The `connector@1` implementations loaded on this replica, by extension and kind. */
1791
1739
  loadedConnectors() {
@@ -1826,6 +1774,29 @@ let PluginInstaller = class PluginInstaller {
1826
1774
  .executeTakeFirst();
1827
1775
  if (!row)
1828
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;
1829
1800
  const ledger = (id) => t
1830
1801
  .selectFrom("plugin_install_components")
1831
1802
  .select(["kind", "ref", "created"])
@@ -1833,7 +1804,7 @@ let PluginInstaller = class PluginInstaller {
1833
1804
  .orderBy("kind")
1834
1805
  .orderBy("ref")
1835
1806
  .execute();
1836
- 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");
1837
1808
  const agents = await agentDefinitionRefs(t, orgId);
1838
1809
  const used = new Map();
1839
1810
  const use = (a, kind, ref) => {
@@ -1911,7 +1882,9 @@ let PluginInstaller = class PluginInstaller {
1911
1882
  };
1912
1883
  /** The themes that go off in the org with the install (and the dependencies it removes). */
1913
1884
  const lostThemes = new Map();
1914
- 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
+ }
1915
1888
  const themes = await themesPreview(t, lostThemes);
1916
1889
  return {
1917
1890
  installId,
@@ -1944,23 +1917,23 @@ let PluginInstaller = class PluginInstaller {
1944
1917
  }
1945
1918
  };
1946
1919
  __decorate([
1947
- Transactional({ propagation: "requires_new" })
1920
+ Transactional()
1921
+ ], PluginInstaller.prototype, "recordInstallFailure", null);
1922
+ __decorate([
1923
+ Transactional({ propagation: "mandatory" })
1948
1924
  ], PluginInstaller.prototype, "recordDependency", null);
1925
+ __decorate([
1926
+ Transactional()
1927
+ ], PluginInstaller.prototype, "execute", null);
1949
1928
  __decorate([
1950
1929
  Transactional()
1951
1930
  ], PluginInstaller.prototype, "enableExtension", null);
1952
1931
  __decorate([
1953
- Transactional({ propagation: "requires_new" })
1932
+ Transactional({ propagation: "mandatory" })
1954
1933
  ], PluginInstaller.prototype, "createInstallRow", null);
1955
1934
  __decorate([
1956
- Transactional({ propagation: "requires_new" })
1935
+ Transactional({ propagation: "mandatory" })
1957
1936
  ], PluginInstaller.prototype, "markInstalled", null);
1958
- __decorate([
1959
- Transactional({ propagation: "requires_new" })
1960
- ], PluginInstaller.prototype, "markFailed", null);
1961
- __decorate([
1962
- Transactional({ propagation: "requires_new" })
1963
- ], PluginInstaller.prototype, "rollbackOne", null);
1964
1937
  __decorate([
1965
1938
  Transactional({ propagation: "mandatory" })
1966
1939
  ], PluginInstaller.prototype, "removeComponent", null);
@@ -1979,6 +1952,9 @@ __decorate([
1979
1952
  __decorate([
1980
1953
  Transactional({ propagation: "mandatory" })
1981
1954
  ], PluginInstaller.prototype, "decideRemovalIn", null);
1955
+ __decorate([
1956
+ Transactional()
1957
+ ], PluginInstaller.prototype, "addMissingDependencies", null);
1982
1958
  __decorate([
1983
1959
  Transactional({ propagation: "mandatory" })
1984
1960
  ], PluginInstaller.prototype, "createSwitchedOnTemplateConnectorIn", null);
@@ -1997,11 +1973,9 @@ PluginInstaller = __decorate([
1997
1973
  __param(4, Inject(SkillsService)),
1998
1974
  __param(5, Inject(OrgExtensionConfigs)),
1999
1975
  __param(6, Inject(ScopeWriter)),
2000
- __param(7, Inject(KernelConfigService)),
2001
- __param(8, Inject(ConnectorsService)),
2002
- __param(9, Inject(KERNEL_LOGGER)),
2003
- __param(10, Inject(OutboxService)),
2004
- __param(11, Inject(TransactionHost))
1976
+ __param(7, Inject(ConnectorsService)),
1977
+ __param(8, Inject(OutboxService)),
1978
+ __param(9, Inject(TransactionHost))
2005
1979
  ], PluginInstaller);
2006
1980
  export { PluginInstaller };
2007
1981
  /**