@capybara-hq/kernel 0.1.0-rc.83 → 0.1.0-rc.85

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 (94) hide show
  1. package/dist/admin/admin.module.js +5 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +10 -2
  4. package/dist/catalog/admin-catalog.controller.d.ts +2 -1
  5. package/dist/catalog/admin-catalog.controller.js +2 -1
  6. package/dist/catalog/catalog-content.d.ts +5 -15
  7. package/dist/catalog/catalog-content.js +5 -56
  8. package/dist/catalog/catalog-scope.service.d.ts +3 -3
  9. package/dist/catalog/catalog-scope.service.js +4 -3
  10. package/dist/catalog/catalog.module.d.ts +3 -1
  11. package/dist/catalog/catalog.module.js +14 -1
  12. package/dist/catalog/component-scope.service.d.ts +6 -1
  13. package/dist/catalog/component-scope.service.js +16 -2
  14. package/dist/catalog/git-source.d.ts +8 -0
  15. package/dist/catalog/git-source.js +34 -0
  16. package/dist/catalog/job-ids.d.ts +29 -0
  17. package/dist/catalog/job-ids.js +29 -0
  18. package/dist/catalog/jobs.d.ts +12 -3
  19. package/dist/catalog/jobs.js +28 -7
  20. package/dist/catalog/marketplaces.service.d.ts +1 -1
  21. package/dist/catalog/org-catalog.controller.d.ts +2 -30
  22. package/dist/catalog/org-catalog.controller.js +3 -29
  23. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  24. package/dist/catalog/org-catalog.schemas.js +9 -23
  25. package/dist/catalog/org-catalog.service.js +14 -23
  26. package/dist/catalog/plugin-import.d.ts +21 -0
  27. package/dist/catalog/plugin-import.js +33 -3
  28. package/dist/catalog/plugin-install.d.ts +69 -76
  29. package/dist/catalog/plugin-install.js +156 -234
  30. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  31. package/dist/catalog/plugin-upgrade.js +222 -43
  32. package/dist/catalog/scope-sync.d.ts +22 -20
  33. package/dist/catalog/scope-sync.js +57 -42
  34. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  35. package/dist/catalog/template-connector-ensure.js +285 -0
  36. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  37. package/dist/catalog/template-connector-jobs.js +54 -0
  38. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  39. package/dist/catalog/template-connector-reconcile.js +114 -0
  40. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  41. package/dist/catalog/template-connectors.processor.js +101 -0
  42. package/dist/db/kernel-schema.d.ts +2 -1
  43. package/dist/extensions/bootstrap.js +5 -1
  44. package/dist/extensions/instance.js +1 -16
  45. package/dist/extensions/org-config.d.ts +6 -1
  46. package/dist/extensions/org-config.js +15 -2
  47. package/dist/git/gateway.js +3 -1
  48. package/dist/infra/outbox/registry.d.ts +28 -0
  49. package/dist/infra/outbox/registry.js +33 -0
  50. package/dist/infra/queue/queue-names.d.ts +1 -1
  51. package/dist/infra/queue/queue-names.js +2 -0
  52. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  53. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  54. package/dist/orgs/org-owner.d.ts +7 -0
  55. package/dist/orgs/org-owner.js +16 -0
  56. package/dist/platform/operation.d.ts +3 -4
  57. package/dist/platform/ops/connectors.ops.js +8 -1
  58. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  59. package/dist/platform/ops/org-plugins.ops.js +18 -235
  60. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  61. package/dist/platform/ops/plugins.ops.js +3 -31
  62. package/dist/roles/worker-role.d.ts +9 -4
  63. package/dist/roles/worker-role.js +18 -5
  64. package/dist/roles/worker.module.d.ts +1 -1
  65. package/dist/roles/worker.module.js +8 -1
  66. package/dist/setup/setup-guides.service.d.ts +9 -1
  67. package/dist/setup/setup-guides.service.js +38 -8
  68. package/dist/tools/admin-connectors.d.ts +3 -2
  69. package/dist/tools/admin-connectors.js +5 -4
  70. package/dist/tools/connector-setup.d.ts +28 -0
  71. package/dist/tools/connector-setup.js +33 -0
  72. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  73. package/dist/tools/connector-tools-jobs.js +40 -0
  74. package/dist/tools/connector-tools.processor.d.ts +32 -0
  75. package/dist/tools/connector-tools.processor.js +97 -0
  76. package/dist/tools/connectors.controller.d.ts +1 -0
  77. package/dist/tools/connectors.schemas.d.ts +1 -0
  78. package/dist/tools/connectors.schemas.js +5 -0
  79. package/dist/tools/connectors.service.d.ts +138 -14
  80. package/dist/tools/connectors.service.js +410 -50
  81. package/dist/tools/credentials.d.ts +35 -0
  82. package/dist/tools/credentials.js +89 -1
  83. package/dist/tools/drift.d.ts +5 -0
  84. package/dist/tools/drift.js +21 -2
  85. package/dist/tools/editable-endpoint.d.ts +23 -0
  86. package/dist/tools/editable-endpoint.js +92 -0
  87. package/dist/tools/oauth/flow.d.ts +1 -1
  88. package/dist/tools/oauth/flow.js +3 -2
  89. package/dist/tools/pipeline.js +14 -5
  90. package/dist/tools/registry.d.ts +14 -2
  91. package/dist/tools/registry.js +27 -6
  92. package/dist/tools/tools.module.js +4 -0
  93. package/package.json +3 -3
  94. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -23,13 +23,16 @@ import { afterCommit } from "../infra/database/after-commit.js";
23
23
  import { KernelDb } from "../infra/database/kernel-db.js";
24
24
  import { TransactionHost } from "../infra/database/transaction-host.js";
25
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
26
27
  import { KERNEL_LOGGER } from "../infra/tokens.js";
27
28
  import { OrgLock } from "../orgs/org-lock.js";
28
29
  import { packagePath } from "../packages/tgz.js";
29
30
  import { SkillsService, skillConflictError, skillConflicts, } from "../skills/skills.service.js";
30
31
  import { StorageService } from "../storage/storage.service.js";
31
32
  import { assertNotPlatformDefault, themesPreview, } from "../themes/theme-usage.js";
33
+ import { setupNeed } from "../tools/connector-setup.js";
32
34
  import { ConnectorsService } from "../tools/connectors.service.js";
35
+ import { isOAuth } from "../tools/credentials.js";
33
36
  import { findConnectorIn, lockOrgForActions, readCatalogAgentTemplates, readCatalogFiles, readCatalogTemplates, requiredActions, templateConnectorInput, templatePluginProblem, } from "./catalog-content.js";
34
37
  import { versionUsable } from "./catalog-items.js";
35
38
  import { agentDefinitionRefs, componentOn, connectorTemplateChoice, connectorTemplateState, connectorTemplatesOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, referenceIds, switchOf, themeIdClashes, } from "./component-state.js";
@@ -37,6 +40,7 @@ import { LIVE_INSTALL_STATUSES } from "./install-status.js";
37
40
  import { assertItemInstallable, disabledPluginItems, pluginItemDisabled, resolveRequestsByInstall, } from "./request-rules.js";
38
41
  import { visibleTo } from "./scope.js";
39
42
  import { ScopeNoLongerWanted, ScopeStillWanted, wantedByScope } from "./scope-state.js";
43
+ import { oweTemplateConnectors } from "./template-connector-jobs.js";
40
44
  import { maxSatisfying, satisfiesRange } from "./versions.js";
41
45
  /** The confirm hash of an uninstall preview: sha256 over its sorted JSON (the scheme of `diffHash`). */
42
46
  export function uninstallPreviewHash(p) {
@@ -64,15 +68,6 @@ export async function upsertOrgSwitch(db, orgId, itemId, enabled, actor) {
64
68
  }))
65
69
  .execute();
66
70
  }
67
- /** The kernel (actor null, the scope sync) never installs what needs the org's input. */
68
- export class NeedsOrgInput extends ApiError {
69
- plugin;
70
- constructor(plugin) {
71
- super("internal", `Plugin ${plugin} needs the organization's input (connector templates); only a person can install it`);
72
- this.plugin = plugin;
73
- }
74
- }
75
- const systemNeedsInput = (name) => new NeedsOrgInput(name);
76
71
  /** How deep plugin dependencies may nest (the root plugin's dependencies are level 1). */
77
72
  export const DEPENDENCY_DEPTH_LIMIT = 10;
78
73
  /** A failed install step, carried up through the dependency installs to the root install. */
@@ -237,25 +232,13 @@ export async function resolveDependencies(db, manifest) {
237
232
  await visit(manifest, [manifest.name]);
238
233
  return direct;
239
234
  }
240
- /**
241
- * The input a template needs that the org did not give: a static credential (the org's for an
242
- * org-owned template; for a personal one the installer's own, stored as their personal credential,
243
- * since creating the connector lists its tools with it), or the OAuth client of a
244
- * client-credentials / manual-client template. Undefined when nothing is missing.
245
- * `personalCredential: false` keeps a personal static template optional (an existing connector
246
- * whose template's auth changed: its members keep giving their own).
247
- */
248
- export function missingTemplateInput(template, given, o = {}) {
249
- const auth = template.auth;
250
- if (auth.type === "oauth_client" || (auth.type === "oauth_code" && auth.client === "manual")) {
251
- return given?.client === undefined ? "client" : undefined;
252
- }
253
- if (auth.type === "none" || auth.type === "oauth_code")
254
- return undefined;
255
- if (auth.ownership !== "org" && o.personalCredential === false)
256
- return undefined;
257
- return given?.credential === undefined ? "credential" : undefined;
258
- }
235
+ /** A static connector with per-member credentials, created without the creator's own. */
236
+ const personalWithoutCredential = (ci) => ci.auth.type !== "none" &&
237
+ !isOAuth(ci.auth) &&
238
+ ci.auth.ownership !== "org" &&
239
+ ci.credential === undefined;
240
+ /** An authorization-code connector whose client is registered dynamically. */
241
+ const isDcr = (ci) => ci.auth.type === "oauth_code" && ci.auth.client === "dcr";
259
242
  /** `e` with its validation paths under `at` (input errors of a template's connector). */
260
243
  export function under(e, at) {
261
244
  if (!(e instanceof ApiError) || e.code !== "validation_failed" || !Array.isArray(e.details)) {
@@ -302,6 +285,7 @@ let PluginInstaller = class PluginInstaller {
302
285
  config;
303
286
  connectors;
304
287
  log;
288
+ outbox;
305
289
  txHost;
306
290
  constructor(kdb,
307
291
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
@@ -309,7 +293,9 @@ let PluginInstaller = class PluginInstaller {
309
293
  /** The loaded extensions and connectors of this replica (the extension registry). */
310
294
  registry, skills, orgConfigs, config,
311
295
  /** Org connectors: installs create, upgrade and remove them. */
312
- connectors, log, txHost) {
296
+ connectors, log,
297
+ /** Owes the template connector ensure of an install's commit (`markInstalled`). */
298
+ outbox, txHost) {
313
299
  this.kdb = kdb;
314
300
  this.orgLock = orgLock;
315
301
  this.storage = storage;
@@ -319,6 +305,7 @@ let PluginInstaller = class PluginInstaller {
319
305
  this.config = config;
320
306
  this.connectors = connectors;
321
307
  this.log = log;
308
+ this.outbox = outbox;
322
309
  this.txHost = txHost;
323
310
  }
324
311
  /** The kernel-schema handle of the current context (the transaction, else the pool). */
@@ -435,9 +422,10 @@ let PluginInstaller = class PluginInstaller {
435
422
  }
436
423
  /**
437
424
  * Plans the install of one plugin version and, depth first, of its dependencies not yet
438
- * installed in the org. `input` null skips the input checks (preflight); dependencies always get
439
- * an empty input. `at` prefixes validation paths (`dependencies.<name>.` for a dependency);
440
- * `approvedBy` is the root item for a dependency.
425
+ * installed in the org. `input` null plans no connectors (preflight, the scope preview: only the
426
+ * templates' connector extensions are checked); dependencies always get an empty input. `at`
427
+ * prefixes validation paths (`dependencies.<name>.` for a dependency); `approvedBy` is the root
428
+ * item for a dependency.
441
429
  */
442
430
  async plan(orgId, actor, itemId, version, input, at, approvedBy) {
443
431
  if (!UUID_RE.test(itemId))
@@ -484,25 +472,18 @@ let PluginInstaller = class PluginInstaller {
484
472
  const skillNames = await catalogSkillNames(this.storage, v, manifest);
485
473
  const agentTemplates = await readCatalogAgentTemplates(this.storage, v);
486
474
  const connectors = new Map();
487
- if (input === null) {
488
- for (const ct of templates) {
475
+ for (const ct of templates) {
476
+ if (input === null) {
489
477
  const problem = templatePluginProblem(this.templateDeps(), ct.file.template);
490
478
  if (problem !== undefined)
491
479
  throw new ApiError("catalog.not_deployed", problem);
480
+ continue;
492
481
  }
493
- }
494
- else {
495
- this.checkInput(allTemplates, input, at);
496
- for (const ct of templates) {
497
- // The kernel installs only what needs no org input (the scope sync's `needs_config` rule)
498
- if (actor === null)
499
- throw systemNeedsInput(manifest.name);
500
- // An earlier switch-off kept this template's connector: the install takes it back, so its
501
- // input is not asked for here (the connector keeps its endpoint and credentials)
502
- if ((await this.liveTemplateConnector(orgId, itemId, ct.id)) !== undefined)
503
- continue;
504
- connectors.set(ct.id, this.planConnector(actor, { itemId, version, name: manifest.name }, ct, input, at, approvedBy));
505
- }
482
+ // An earlier switch-off kept this template's connector: the install takes it back (the
483
+ // connector keeps its endpoint and credentials)
484
+ if ((await this.liveTemplateConnector(orgId, itemId, ct.id)) !== undefined)
485
+ continue;
486
+ connectors.set(ct.id, this.planConnector(actor, { itemId, version }, ct, at, approvedBy));
506
487
  }
507
488
  const dependencies = [];
508
489
  for (const dep of deps) {
@@ -607,41 +588,29 @@ let PluginInstaller = class PluginInstaller {
607
588
  return out;
608
589
  }
609
590
  /**
610
- * The connector input of one template from the org's input (C30), checked without a connection:
611
- * the template's connector extension deployed, the input valid, the credential / OAuth client it
612
- * needs given (else 400; a dependency's says to install it on its own first).
591
+ * The connector of one template as an install creates it (plugin pages spec §5.2.2), checked
592
+ * without a connection: the template's connector extension deployed and its preset valid. No
593
+ * input is asked for: a template that needs an org credential or OAuth client becomes a
594
+ * `needs_config` connector ({@link setupNeed}), one that needs none `ready`. The name and slug
595
+ * are the first free defaults, chosen under the org lock (`slugDefault`), so an org connector of
596
+ * the same slug never blocks an install nobody can give input to.
613
597
  */
614
- planConnector(actor, plugin, ct, input, at, approvedBy) {
598
+ planConnector(actor, plugin, ct, at, approvedBy) {
615
599
  const path = `${at}connectors.${ct.id}`;
616
- const given = input.connectors?.[ct.id];
600
+ const display = ct.file.displayName.en;
617
601
  const ci = templateConnectorInput(this.templateDeps(), ct.file.template, {
618
602
  itemId: plugin.itemId,
619
603
  version: plugin.version,
620
604
  templateId: ct.id,
621
605
  ...(approvedBy !== undefined && { approvedBy }),
622
- }, given, ct.file.displayName.en, path);
623
- const missing = missingTemplateInput(ct.file.template, given);
624
- if (missing !== undefined) {
625
- const personal = missing === "credential" &&
626
- ct.file.template.auth.ownership !== "org";
627
- const needs = missing === "client"
628
- ? "an OAuth client"
629
- : personal
630
- ? "the installer's own credential"
631
- : "an org credential";
632
- throw fail(`${path}.${missing}`, approvedBy !== undefined
633
- ? `Dependency ${plugin.name} has a connector template that needs ${needs}; install ${plugin.name} on its own first`
634
- : personal
635
- ? "This connector template uses each member's own credential; give yours (it lists the tools and is stored as your personal credential)"
636
- : `This connector template needs ${needs}`);
637
- }
606
+ }, undefined, display, path);
638
607
  try {
639
- this.connectors.checkCreateInput(actor, ci);
608
+ this.connectors.checkCreateInput(actor, ci, { deferred: true });
640
609
  }
641
610
  catch (e) {
642
611
  throw under(e, path);
643
612
  }
644
- return ci;
613
+ return { ...ci, slugDefault: { display } };
645
614
  }
646
615
  /**
647
616
  * The org's live install of a dependency's item (installing or installed), or undefined. One at a
@@ -709,7 +678,7 @@ let PluginInstaller = class PluginInstaller {
709
678
  * as they are. Returns the install id.
710
679
  */
711
680
  async execute(orgId, actor, plan, opts, ctx) {
712
- const { itemId, manifest } = plan;
681
+ const { itemId } = plan;
713
682
  // The install row (role and item policy re-checked under the lock; one live install per org
714
683
  // and item)
715
684
  const installId = randomUUID();
@@ -792,17 +761,20 @@ let PluginInstaller = class PluginInstaller {
792
761
  }
793
762
  const ci = plan.connectors.get(ct.id);
794
763
  if (!ci) {
795
- // The plan skipped this template's input because a live connector existed, and it went
796
- // away since (deleted between planning and this step): fail honestly, so the person
797
- // retries and the new plan asks for the input
764
+ // The plan skipped this template because a live connector existed, and it went away
765
+ // since (deleted between planning and this step): fail honestly, so the install is
766
+ // retried and the new plan creates the connector
798
767
  throw new ApiError("catalog.connector_removed", `The connector this install would reuse for connector template ${ct.id} was removed meanwhile; start the install again`);
799
768
  }
800
- if (actor === null)
801
- throw systemNeedsInput(manifest.name);
802
- const r = await this.connectors.create(orgId, actor, ci, opts.actorTokenId, opts.auditDetail);
769
+ // No outbound call: the row is written with an empty tool list, which the outbox lists
770
+ // after the commit when the connector is ready (plugin pages spec §5.2.1)
771
+ const connectorId = await this.connectors.createDeferredIn(orgId, actor, ci, {
772
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
773
+ ...(opts.auditDetail !== undefined && { auditDetail: opts.auditDetail }),
774
+ });
803
775
  await record({
804
776
  kind: "connector",
805
- ref: r.connector.id,
777
+ ref: connectorId,
806
778
  created: true,
807
779
  skillVersion: null,
808
780
  templateId: ct.id,
@@ -961,6 +933,10 @@ let PluginInstaller = class PluginInstaller {
961
933
  },
962
934
  });
963
935
  }
936
+ // The org's template connectors it never had, after the commit (ruling R27): an extension
937
+ // this install enabled may provide the connector kind of another plugin's template, and it
938
+ // loads on the replica only after the commit
939
+ await oweTemplateConnectors(this.outbox, t, orgId);
964
940
  await audit(t, {
965
941
  actorAccountId: actor,
966
942
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
@@ -1028,14 +1004,6 @@ let PluginInstaller = class PluginInstaller {
1028
1004
  }
1029
1005
  return name;
1030
1006
  }
1031
- /** The input only names the plugin's template ids. */
1032
- checkInput(templates, input, at) {
1033
- const ids = new Set(templates.map((c) => c.id));
1034
- for (const k of Object.keys(input.connectors ?? {})) {
1035
- if (!ids.has(k))
1036
- throw fail(`${at}connectors.${k}`, "No such connector template in this plugin");
1037
- }
1038
- }
1039
1007
  /**
1040
1008
  * Undoes the components this install created, in reverse order (the role is not re-checked: it
1041
1009
  * undoes this install's own changes); returns the ones that failed. The component rows of undone
@@ -1582,9 +1550,9 @@ let PluginInstaller = class PluginInstaller {
1582
1550
  /**
1583
1551
  * Installs the dependencies an installed plugin's version declares and the org lacks (rule 9),
1584
1552
  * as the kernel (actor null): a platform update can add one. Each is recorded on the install
1585
- * as a `plugin` component (created when this installed it, so an uninstall takes it along). One
1586
- * that needs the org's input (connector templates) is left out and its name returned. A
1587
- * dependency already installed in the org is recorded as it is (created false).
1553
+ * as a `plugin` component (created when this installed it, so an uninstall takes it along); its
1554
+ * connector templates become connectors as at any install. A dependency already installed in
1555
+ * the org is recorded as it is (created false). Returns how many dependencies it installed.
1588
1556
  */
1589
1557
  async addMissingDependencies(orgId, installId) {
1590
1558
  const row = await this.db
@@ -1595,7 +1563,8 @@ let PluginInstaller = class PluginInstaller {
1595
1563
  .where("a.org_id", "=", orgId)
1596
1564
  .executeTakeFirst();
1597
1565
  if (row?.status !== "installed")
1598
- return [];
1566
+ return 0;
1567
+ let installed = 0;
1599
1568
  const record = async (c) => {
1600
1569
  await this.db
1601
1570
  .insertInto("plugin_install_components")
@@ -1609,21 +1578,10 @@ let PluginInstaller = class PluginInstaller {
1609
1578
  .onConflict((oc) => oc.columns(["install_id", "kind", "ref"]).doNothing())
1610
1579
  .execute();
1611
1580
  };
1612
- const needsInput = [];
1613
1581
  for (const dep of await resolveDependencies(this.db, row.manifest)) {
1614
1582
  if ((await this.recordDependency(orgId, dep, record)) !== undefined)
1615
1583
  continue;
1616
- let plan;
1617
- try {
1618
- plan = await this.plan(orgId, null, dep.itemId, dep.version, {}, "", row.item_id);
1619
- }
1620
- catch (e) {
1621
- if (e instanceof NeedsOrgInput) {
1622
- needsInput.push(dep.name);
1623
- continue;
1624
- }
1625
- throw e;
1626
- }
1584
+ const plan = await this.plan(orgId, null, dep.itemId, dep.version, {}, "", row.item_id);
1627
1585
  const child = await this.execute(orgId, null, plan, {}, {
1628
1586
  actions: requiredActions(plan.manifest),
1629
1587
  approvedBy: row.item_id,
@@ -1631,55 +1589,9 @@ let PluginInstaller = class PluginInstaller {
1631
1589
  via: "scope",
1632
1590
  });
1633
1591
  await this.recordDependency(orgId, dep, record, child);
1592
+ installed += 1;
1634
1593
  }
1635
- return needsInput;
1636
- }
1637
- /**
1638
- * The connector templates of an installed plugin that are on in the org (ruling P2-6) and have
1639
- * no live connector there: made from the platform template (`platform_template_id`) or recorded
1640
- * on the install (`template_id`). The org's plugin is `needs_config` while any is missing (ruling
1641
- * P2-10). Empty for a plugin not installed.
1642
- */
1643
- async missingConnectors(orgId, itemId) {
1644
- const a = await this.db
1645
- .selectFrom("plugin_installs as a")
1646
- .innerJoin("catalog_item_versions as v", (j) => j.onRef("v.item_id", "=", "a.item_id").onRef("v.version", "=", "a.version"))
1647
- .select(["a.id", "a.version", "v.manifest", "v.object_prefix", "v.files"])
1648
- .where("a.org_id", "=", orgId)
1649
- .where("a.item_id", "=", itemId)
1650
- .where("a.status", "=", "installed")
1651
- .executeTakeFirst();
1652
- if (!a)
1653
- return undefined;
1654
- if ((a.manifest.connectorTemplates ?? []).length === 0) {
1655
- return { installId: a.id, version: a.version, templates: [] };
1656
- }
1657
- const all = await readCatalogTemplates(this.storage, a);
1658
- const on = await connectorTemplatesOn(this.db, orgId, itemId, all.map((t) => t.id));
1659
- const made = new Set((await this.db
1660
- .selectFrom("connectors as c")
1661
- .innerJoin("platform_connector_templates as p", "p.id", "c.platform_template_id")
1662
- .select("p.template_id")
1663
- .where("c.org_id", "=", orgId)
1664
- .where("c.deleted_at", "is", null)
1665
- .where("p.catalog_item_id", "=", itemId)
1666
- .execute()).map((r) => r.template_id));
1667
- const recorded = await this.db
1668
- .selectFrom("plugin_install_components as l")
1669
- .innerJoin("connectors as c", (j) => j.on(sql `c.id::text`, "=", sql `l.ref`))
1670
- .select("l.template_id")
1671
- .where("l.install_id", "=", a.id)
1672
- .where("l.kind", "=", "connector")
1673
- .where("c.deleted_at", "is", null)
1674
- .execute();
1675
- for (const r of recorded)
1676
- if (r.template_id !== null)
1677
- made.add(r.template_id);
1678
- return {
1679
- installId: a.id,
1680
- version: a.version,
1681
- templates: all.filter((t) => on.has(t.id) && !made.has(t.id)),
1682
- };
1594
+ return installed;
1683
1595
  }
1684
1596
  /**
1685
1597
  * The org's live connectors made from one of the item's connector templates, oldest first
@@ -1706,84 +1618,26 @@ let PluginInstaller = class PluginInstaller {
1706
1618
  }
1707
1619
  /**
1708
1620
  * The org's connector templates it already has a live connector for, by template id: the install
1709
- * takes that connector back instead of creating one, so the org item detail tells the wizard not
1710
- * to ask for their input (the same join as {@link liveTemplateConnector}).
1621
+ * takes that connector back instead of creating one (the same join as
1622
+ * {@link liveTemplateConnector}).
1711
1623
  */
1712
1624
  async connectedTemplates(orgId, itemId) {
1713
1625
  const rows = await this.liveTemplateConnectors(orgId, itemId);
1714
1626
  return new Set(rows.map((r) => r.templateId));
1715
1627
  }
1716
- /**
1717
- * Creates the connectors an installed plugin is missing (ruling P2-10, `POST …/catalog/:itemId/
1718
- * connectors`): `input.connectors` names some of {@link missingConnectors}' templates with the
1719
- * same input as an install (endpoint, credential or OAuth client); each is created as at install
1720
- * and recorded on the install. Returns the created connectors by template.
1721
- */
1722
- async configureConnectors(orgId, actor, itemId, input, opts = {}) {
1723
- if (!UUID_RE.test(itemId))
1724
- throw installNotFound();
1725
- const missing = await this.missingConnectors(orgId, itemId);
1726
- if (!missing)
1727
- throw installNotFound();
1728
- const keys = Object.keys(input.connectors ?? {});
1729
- if (keys.length === 0) {
1730
- throw new ApiError("validation_failed", "Request validation failed", [
1731
- { path: "connectors", message: "Give the input of at least one missing connector" },
1732
- ]);
1733
- }
1734
- for (const k of keys) {
1735
- if (!missing.templates.some((t) => t.id === k)) {
1736
- throw new ApiError("validation_failed", "Request validation failed", [
1737
- {
1738
- path: `connectors.${k}`,
1739
- message: "No connector of this template is missing in this organization",
1740
- },
1741
- ]);
1742
- }
1743
- }
1744
- const item = await this.db
1745
- .selectFrom("catalog_items")
1746
- .select("name")
1747
- .where("id", "=", itemId)
1748
- .executeTakeFirstOrThrow();
1749
- const plans = missing.templates
1750
- .filter((t) => keys.includes(t.id))
1751
- .map((t) => ({
1752
- id: t.id,
1753
- ci: this.planConnector(actor, { itemId, version: missing.version, name: item.name }, t, input, "", undefined),
1754
- }));
1755
- const out = [];
1756
- for (const p of plans) {
1757
- const r = await this.connectors.create(orgId, actor, p.ci, opts.actorTokenId, opts.auditDetail);
1758
- await this.recordConnector(missing.installId, r.connector.id, p.id);
1759
- out.push({ templateId: p.id, connectorId: r.connector.id });
1760
- }
1761
- return out;
1762
- }
1763
- /** A configured connector's ledger row (its own transaction). */
1764
- async recordConnector(installId, ref, templateId) {
1765
- await this.db
1766
- .insertInto("plugin_install_components")
1767
- .values({
1768
- install_id: installId,
1769
- kind: "connector",
1770
- ref,
1771
- created: true,
1772
- skill_version: null,
1773
- template_id: templateId,
1774
- })
1775
- .onConflict((oc) => oc.columns(["install_id", "kind", "ref"]).doNothing())
1776
- .execute();
1777
- }
1778
1628
  /**
1779
1629
  * One more connector from a platform connector template on in the org (rulings P4-7, P4-T6-8;
1780
1630
  * `POST …/connector-templates/:templateId/connectors`): `templateId` is the platform connector
1781
- * template's id; `config` is an install's connector input (endpoint, credential or OAuth client,
1782
- * slug) and `name` its name. Without a slug the name and slug default to the first free ones,
1783
- * chosen by the create under the org lock after its outbound calls
1784
- * (`CreateConnectorInput.slugDefault`); only a given slug answers 409 `connector.slug_taken`. Created as at install ({@link planConnector}, then
1785
- * `ConnectorsService.create`, which checks the slug before any outbound call and re-checks it,
1786
- * `connectors.manage`, the item and the template being on under the org lock), linked to the
1631
+ * template's id; `config` is the connector's input (endpoint, credential or OAuth client, slug)
1632
+ * and `name` its name. Without a slug the name and slug default to the first free ones, chosen
1633
+ * by the create under the org lock after its outbound calls (`CreateConnectorInput.slugDefault`);
1634
+ * only a given slug answers 409 `connector.slug_taken`. As on the connectors page's own create,
1635
+ * the org credential or OAuth client the template needs is required; a personal static template
1636
+ * given no credential is created ready without one, and a `dcr` one without a client
1637
+ * (`createDeferredIn`: its members connect their own, the client registers on the first
1638
+ * connect). Otherwise created by `ConnectorsService.create`, which lists the tools, checks the
1639
+ * slug before any outbound call and re-checks it, `connectors.manage`, the item and the
1640
+ * template being on under the org lock. Linked to the
1787
1641
  * template, and recorded on the plugin's live install in the org when there is one. A template
1788
1642
  * that is missing, deleted or not offered to the org -> 404 `component.not_found`; offered but
1789
1643
  * off there (its plugin not installed, or switched off) -> 409 `component.off`; input errors ->
@@ -1840,11 +1694,18 @@ let PluginInstaller = class PluginInstaller {
1840
1694
  const defaulted = input.config.slug === undefined;
1841
1695
  let ci;
1842
1696
  try {
1843
- ci = this.planConnector(actor, { itemId: row.catalog_item_id, version: row.version ?? row.latest_version, name: row.name }, ct, {
1844
- connectors: {
1845
- [ct.id]: { ...input.config, ...(input.name !== undefined && { name: input.name }) },
1846
- },
1847
- }, "", undefined);
1697
+ ci = templateConnectorInput(this.templateDeps(), ct.file.template, {
1698
+ itemId: row.catalog_item_id,
1699
+ version: row.version ?? row.latest_version,
1700
+ templateId: ct.id,
1701
+ }, { ...input.config, ...(input.name !== undefined && { name: input.name }) }, display, at);
1702
+ // as on the connectors page's own create, the org-level input is required here
1703
+ const need = setupNeed(ci.auth);
1704
+ if (need !== undefined && ci.credential === undefined) {
1705
+ throw fail(`${at}.${need}`, need === "client"
1706
+ ? "This connector template needs an OAuth client"
1707
+ : "This connector template needs an org credential");
1708
+ }
1848
1709
  }
1849
1710
  catch (e) {
1850
1711
  throw rebase(e);
@@ -1857,6 +1718,14 @@ let PluginInstaller = class PluginInstaller {
1857
1718
  }),
1858
1719
  };
1859
1720
  try {
1721
+ // a personal static template without the creator's own credential: created ready with no
1722
+ // credential and no tool list, its members connect their own (plugin pages spec §5.2.1); a
1723
+ // dcr template registers its client on the first connect, as an install's (ruling R16)
1724
+ if (personalWithoutCredential(ci) || isDcr(ci)) {
1725
+ const id = await this.connectors.createDeferredIn(orgId, actor, ci, opts);
1726
+ await this.recordOnLiveInstall(orgId, row.catalog_item_id, id, ct.id);
1727
+ return { connector: await this.connectors.get(orgId, id, actor), issues: [] };
1728
+ }
1860
1729
  const r = await this.connectors.create(orgId, actor, ci, opts.actorTokenId, opts.auditDetail);
1861
1730
  await this.recordOnLiveInstall(orgId, row.catalog_item_id, r.connector.id, ct.id);
1862
1731
  return r;
@@ -1866,20 +1735,53 @@ let PluginInstaller = class PluginInstaller {
1866
1735
  }
1867
1736
  }
1868
1737
  /**
1869
- * Records a connector made from a plugin's template on the org's live install of that plugin,
1870
- * when there is one, under the org lock (so an uninstall in between is seen).
1738
+ * The connector of a platform connector template an org admin just switched on (plugin pages
1739
+ * spec §5.2.2: a template switched on later creates its connector under the install rule), in
1740
+ * the switch's transaction: only where the org has the template's plugin installed and no live
1741
+ * connector from the template yet (one a switch-off kept is reused, left as it is). Created like
1742
+ * an install's ({@link planConnector}, `createDeferredIn`: no outbound call, `needs_config` when
1743
+ * it needs an org credential or OAuth client) and recorded on the install. Returns its id, or
1744
+ * undefined when none was created. `actor` null: the kernel itself (the startup reconciliation,
1745
+ * `TemplateConnectorReconciler`), which checks the template is on and holds the org lock.
1871
1746
  */
1872
- async recordOnLiveInstall(orgId, itemId, connectorId, templateId) {
1873
- await this.orgLock.lock(orgId);
1747
+ async createSwitchedOnTemplateConnectorIn(orgId, actor, platformTemplateId, opts = {}) {
1748
+ const row = await this.db
1749
+ .selectFrom("platform_connector_templates as t")
1750
+ .innerJoin("plugin_installs as a", (j) => j
1751
+ .onRef("a.item_id", "=", "t.catalog_item_id")
1752
+ .on("a.org_id", "=", orgId)
1753
+ .on("a.status", "=", "installed"))
1754
+ .select(["t.template_id", "t.catalog_item_id", "t.file", "a.version"])
1755
+ .where("t.id", "=", platformTemplateId)
1756
+ .where("t.deleted_at", "is", null)
1757
+ .executeTakeFirst();
1758
+ if (row?.catalog_item_id == null)
1759
+ return undefined;
1760
+ const itemId = row.catalog_item_id;
1761
+ if ((await this.liveTemplateConnector(orgId, itemId, row.template_id)) !== undefined) {
1762
+ return undefined;
1763
+ }
1764
+ const ct = { id: row.template_id, file: row.file };
1765
+ const ci = this.planConnector(actor, { itemId, version: row.version }, ct, "", undefined);
1766
+ const connectorId = await this.connectors.createDeferredIn(orgId, actor, ci, opts);
1767
+ await this.recordTemplateConnectorIn(orgId, itemId, connectorId, ct.id, ["installed"]);
1768
+ return connectorId;
1769
+ }
1770
+ /**
1771
+ * Records a connector made from one of the item's connector templates on the org's install of
1772
+ * the item whose status is one of `statuses` (`created`: the plugin made it, so an uninstall and
1773
+ * upgrades see it), in the caller's transaction. True when such an install exists.
1774
+ */
1775
+ async recordTemplateConnectorIn(orgId, itemId, connectorId, templateId, statuses) {
1874
1776
  const install = await this.db
1875
1777
  .selectFrom("plugin_installs")
1876
1778
  .select("id")
1877
1779
  .where("org_id", "=", orgId)
1878
1780
  .where("item_id", "=", itemId)
1879
- .where("status", "=", "installed")
1781
+ .where("status", "in", [...statuses])
1880
1782
  .executeTakeFirst();
1881
1783
  if (!install)
1882
- return;
1784
+ return false;
1883
1785
  await this.db
1884
1786
  .insertInto("plugin_install_components")
1885
1787
  .values({
@@ -1892,6 +1794,22 @@ let PluginInstaller = class PluginInstaller {
1892
1794
  })
1893
1795
  .onConflict((oc) => oc.columns(["install_id", "kind", "ref"]).doNothing())
1894
1796
  .execute();
1797
+ return true;
1798
+ }
1799
+ /**
1800
+ * Records a connector made from a plugin's template on the org's live install of that plugin,
1801
+ * when there is one, under the org lock (so an uninstall in between is seen).
1802
+ */
1803
+ async recordOnLiveInstall(orgId, itemId, connectorId, templateId) {
1804
+ await this.orgLock.lock(orgId);
1805
+ await this.recordTemplateConnectorIn(orgId, itemId, connectorId, templateId, ["installed"]);
1806
+ }
1807
+ /** The `connector@1` implementations loaded on this replica, by extension and kind. */
1808
+ loadedConnectors() {
1809
+ return this.registry
1810
+ .list("connector")
1811
+ .map((e) => ({ plugin: e.plugin, kind: e.impl?.kind }))
1812
+ .filter((c) => typeof c.kind === "string");
1895
1813
  }
1896
1814
  /** The connector kinds an extension provides (the `connector@1` implementations loaded on this replica). */
1897
1815
  connectorKindsOf(plugin) {
@@ -2079,8 +1997,11 @@ __decorate([
2079
1997
  Transactional({ propagation: "mandatory" })
2080
1998
  ], PluginInstaller.prototype, "decideRemovalIn", null);
2081
1999
  __decorate([
2082
- Transactional({ propagation: "requires_new" })
2083
- ], PluginInstaller.prototype, "recordConnector", null);
2000
+ Transactional({ propagation: "mandatory" })
2001
+ ], PluginInstaller.prototype, "createSwitchedOnTemplateConnectorIn", null);
2002
+ __decorate([
2003
+ Transactional({ propagation: "mandatory" })
2004
+ ], PluginInstaller.prototype, "recordTemplateConnectorIn", null);
2084
2005
  __decorate([
2085
2006
  Transactional()
2086
2007
  ], PluginInstaller.prototype, "recordOnLiveInstall", null);
@@ -2095,7 +2016,8 @@ PluginInstaller = __decorate([
2095
2016
  __param(6, Inject(KernelConfigService)),
2096
2017
  __param(7, Inject(ConnectorsService)),
2097
2018
  __param(8, Inject(KERNEL_LOGGER)),
2098
- __param(9, Inject(TransactionHost))
2019
+ __param(9, Inject(OutboxService)),
2020
+ __param(10, Inject(TransactionHost))
2099
2021
  ], PluginInstaller);
2100
2022
  export { PluginInstaller };
2101
2023
  /**