@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
@@ -1,4 +1,4 @@
1
- import type { PluginManifest } from "@capybara-hq/plugin-sdk";
1
+ import type { ConnectorTemplateFile, PluginManifest } from "@capybara-hq/plugin-sdk";
2
2
  import { ExtensionAdminOps } from "../extensions/admin-ops.js";
3
3
  import { ExtensionBlobs } from "../extensions/blobs.js";
4
4
  import { PluginGuides, type TemplateGuideChange } from "../extensions/plugin-guides.js";
@@ -9,10 +9,12 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
9
9
  import { KernelDb } from "../infra/database/kernel-db.js";
10
10
  import { TransactionHost } from "../infra/database/transaction-host.js";
11
11
  import { LockService } from "../infra/lock/lock.service.js";
12
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
12
13
  import type { KernelLogger } from "../log.js";
13
14
  import { OrgLock } from "../orgs/org-lock.js";
14
15
  import { StorageService } from "../storage/storage.service.js";
15
16
  import { type ThemePreview } from "../themes/theme-usage.js";
17
+ import { type ConnectorSetup } from "../tools/connector-setup.js";
16
18
  import { ConnectorsService } from "../tools/connectors.service.js";
17
19
  import { type CatalogVersionFiles } from "./catalog-content.js";
18
20
  import { type ComponentKind } from "./component-state.js";
@@ -70,11 +72,27 @@ export interface PlatformUpdateConnectorOrg {
70
72
  credentialsReset: boolean;
71
73
  }[];
72
74
  /**
73
- * Templates the update turns on in the org where the plugin is on: added ones, and ones the
74
- * target no longer ships off (`defaultEnabled`) without an org switch. Their connectors need the
75
- * org's input (endpoint, credentials), so the update creates none.
75
+ * The connectors the update creates in the org where the plugin is on (plugin pages spec
76
+ * §5.2.3): one per template it turns on there (added ones, and ones the target no longer ships
77
+ * off without an org switch) that has no live connector in the org yet, and whose connector
78
+ * extension is on in the org. `setup`: the state the connector starts in, `needs_config` when
79
+ * its template needs an org credential or OAuth client ({@link setupNeed}).
76
80
  */
77
- needsConfig: string[];
81
+ created: {
82
+ templateId: string;
83
+ displayName: ConnectorTemplateFile["displayName"];
84
+ setup: ConnectorSetup;
85
+ }[];
86
+ /**
87
+ * Templates turned on in the org whose connector the update does not create (ruling R27): the
88
+ * connector extension of their `kind` is not on in the org (or not loaded yet). The update owes
89
+ * the org's template connector ensure, which creates each once its connector plugin is on there.
90
+ */
91
+ deferred: {
92
+ templateId: string;
93
+ displayName: ConnectorTemplateFile["displayName"];
94
+ kind: string;
95
+ }[];
78
96
  /**
79
97
  * Templates the target ships off (`defaultEnabled: false`) that were on in the org only by
80
98
  * default (no org switch): they turn off there, with the agents using them; the connectors made
@@ -111,6 +129,20 @@ export interface PlatformUpdatePreview {
111
129
  needsApproval: boolean;
112
130
  } | null;
113
131
  connectorOrgs: PlatformUpdateConnectorOrg[];
132
+ /**
133
+ * The orgs where the scope sync owed with the update will install the plugin (plugin pages spec
134
+ * §5.2.3): its scope wants it on there and the org has no live install (one that waited for
135
+ * connector input before installs took none). `failing`: the scope sync's last attempt there
136
+ * failed (an open `plugin_scope_sync_failures` row), `lastFailure` its message. Sorted by org
137
+ * id. Hashed by org id and `failing` only. An owner's preview ({@link
138
+ * PlatformPluginUpdater.previewForOwner}) drops both for orgs other than the owner.
139
+ */
140
+ scopeInstalls: {
141
+ orgId: string;
142
+ orgName: string;
143
+ failing?: true;
144
+ lastFailure?: string;
145
+ }[];
114
146
  /**
115
147
  * Connector templates whose setup guide the update changes (code blocks or checks of the admin
116
148
  * text): "the setup guide of template X changed; org admins of N orgs will be asked to update
@@ -168,9 +200,10 @@ export type UpdateTarget = VersionRow;
168
200
  * components updated on their own, components with their own scope and the orgs whose linked
169
201
  * copy is pinned; lists removed components agents still use (they stay, spec §7.3), the org
170
202
  * connectors made from changed templates (all orgs, ruling E2; `credentialsReset` when the
171
- * credential shape changed), the templates it turns on that will need an org's input (added, or
172
- * no longer shipped off) and those it turns off (now shipped off, on only by default), the
173
- * deployment's extension move, and a `diffHash`. Refused: same version, a disabled or deleted
203
+ * credential shape changed), the connectors it creates from the templates it turns on (added,
204
+ * or no longer shipped off; plugin pages spec §5.2.3) with the setup state each starts in, the
205
+ * templates it turns off (now shipped off, on only by default), the orgs where the scope sync
206
+ * owed with it will install the plugin, the deployment's extension move, and a `diffHash`. Refused: same version, a disabled or deleted
174
207
  * item, a target without the extension the deployment runs for it or moving a config-declared
175
208
  * one, a template moving to another connector, a plugin another platform plugin depends on
176
209
  * outside its range, and an added skill whose name is taken where the plugin is on (rule 10).
@@ -183,11 +216,19 @@ export type UpdateTarget = VersionRow;
183
216
  * unpinned linked copies go with it; pinned copies keep their own version; a removed connector
184
217
  * template leaves its connectors as the orgs' own), clears the pins of linked copies, fans
185
218
  * changed templates out to every connector made from them (`applyTemplateIn`, under each org's
186
- * row lock, credentials cleared only for a changed credential shape), moves every org install to the version and audits
219
+ * row lock, credentials cleared only for a changed credential shape), creates the connectors of
220
+ * the templates it turns on (`ConnectorsService.createDeferredIn`, no outbound call, those orgs
221
+ * locked with the others), moves every org install to the version and audits
187
222
  * `plugin.platform_updated`; the scope sync of the item and its dependencies is owed in that
188
223
  * transaction (orgs get new dependencies by rule 9). A failure rolls the transaction back and
189
224
  * puts the extension back where it was (audit `plugin.platform_update_failed`, 502
190
225
  * `plugin.upgrade_failed`); files copied to `deployment/platform/` stay unreferenced.
226
+ * Transaction size: the whole fan-out (every changed template's connectors and every created
227
+ * connector, in every org where the plugin is on) is one transaction holding every touched org's
228
+ * row lock, with no batching; it grows with orgs x templates, so a deployment with very many orgs
229
+ * sees one long transaction (and other writes to those orgs waiting) per update. Deferred
230
+ * connectors (ruling R27) add one outbox row per org and no connector rows. Builtin plugins get no
231
+ * created connectors (ruling R28).
191
232
  * Storage is never read or written inside the transaction: the target's contents (and the
192
233
  * extension package, for `needsApproval`) are read and the platform files copied
193
234
  * (`PlatformComponents.prepareSync`) after the Redis lock is taken and before the transaction,
@@ -220,13 +261,17 @@ export declare class PlatformPluginUpdater {
220
261
  private readonly log;
221
262
  /** The connector template guides an update changes (the preview's `guideChanges`). */
222
263
  private readonly guides;
264
+ /** Owes the template connector ensure of the orgs with a deferred connector (ruling R27). */
265
+ private readonly outbox;
223
266
  constructor(kdb: KernelDb, txHost: TransactionHost, adminLock: SuperAdminLock, itemLock: CatalogItemLock, orgLock: OrgLock, locks: LockService, storage: StorageService, registry: ExtensionRegistry, ops: ExtensionAdminOps,
224
267
  /** Reads the target's extension package (its permissions, for `needsApproval`). */
225
268
  blobs: ExtensionBlobs, config: KernelConfigService, platform: PlatformComponents,
226
269
  /** Template dependencies (the deployed connector kinds). */
227
270
  installer: PluginInstaller, connectors: ConnectorsService, sync: PluginScopeSync, log: KernelLogger,
228
271
  /** The connector template guides an update changes (the preview's `guideChanges`). */
229
- guides: Pick<PluginGuides, "templateGuideChanges">);
272
+ guides: Pick<PluginGuides, "templateGuideChanges">,
273
+ /** Owes the template connector ensure of the orgs with a deferred connector (ruling R27). */
274
+ outbox: Pick<OutboxService, "add">);
230
275
  private get db();
231
276
  /** The update preview (see the class comment); writes nothing. */
232
277
  preview(itemId: string, version: string): Promise<PlatformUpdatePreview>;
@@ -250,7 +295,8 @@ export declare class PlatformPluginUpdater {
250
295
  previewForOwner(orgId: string, itemId: string, version: string, staged?: UpdateTarget): Promise<PlatformUpdatePreview>;
251
296
  /**
252
297
  * Locks, in sorted order and before the item (ruling P3-50), every live org the update may
253
- * write in: the orgs with connectors made from the plugin's connector templates and the item's
298
+ * write in: the orgs with connectors made from the plugin's connector templates, the orgs the
299
+ * update creates connectors in (`creating`, from the diff before the transaction) and the item's
254
300
  * owner org. `acting`: the owner org an owner update acts for, locked with its admin re-checked
255
301
  * (`catalog.upload`; deleted -> 404 `org.not_found`). Returns the live orgs locked; another
256
302
  * deleted one is skipped.
@@ -338,6 +384,14 @@ export declare class PlatformPluginUpdater {
338
384
  * are the org's) when the credential shape changed.
339
385
  */
340
386
  private prepare;
387
+ /**
388
+ * Creates the connector of a template the update turns on in an org, in the update's
389
+ * transaction (the org row locked): as an install creates it (`PluginInstaller.planConnector`,
390
+ * `ConnectorsService.createDeferredIn`: no outbound call, `needs_config` when the template needs
391
+ * an org credential or OAuth client), by the kernel itself, and recorded on the org's live
392
+ * install of the plugin when there is one (a builtin plugin has none).
393
+ */
394
+ private createTemplateConnectorIn;
341
395
  /**
342
396
  * Computes an update (see the class comment). `target`: the target read from an org's staging
343
397
  * instead of `catalog_item_versions` (pre-flight F3). `owner`: an owner update (P3-12): the item
@@ -372,6 +426,12 @@ export declare class PlatformPluginUpdater {
372
426
  private liveComponents;
373
427
  /** The `themes` block of the preview: the orgs each of the removed themes `ids` is on in. */
374
428
  private themesLost;
429
+ /**
430
+ * {@link PlatformUpdatePreview.scopeInstalls}: the live orgs without a live install (`onOrgs`
431
+ * are those with one) whose scope wants the plugin on, as the scope sync decides it
432
+ * (`wantedOn`). None for a builtin plugin (on everywhere without an install) or one not usable.
433
+ */
434
+ private scopeInstallsOf;
375
435
  /** The orgs where the plugin is on: a live install (builtin: every live org). */
376
436
  private pluginOrgs;
377
437
  private liveOrgs;
@@ -30,12 +30,14 @@ import { KernelDb } from "../infra/database/kernel-db.js";
30
30
  import { TransactionHost } from "../infra/database/transaction-host.js";
31
31
  import { Transactional } from "../infra/database/transactional.decorator.js";
32
32
  import { LockService } from "../infra/lock/lock.service.js";
33
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
33
34
  import { KERNEL_LOGGER } from "../infra/tokens.js";
34
35
  import { OrgLock } from "../orgs/org-lock.js";
35
36
  import { packagePath } from "../packages/tgz.js";
36
37
  import { StorageService } from "../storage/storage.service.js";
37
38
  import { assertNotPlatformDefault, pickedByIn, themesPreview, } from "../themes/theme-usage.js";
38
39
  import { canonicalJson } from "../tools/canonical-json.js";
40
+ import { setupNeed } from "../tools/connector-setup.js";
39
41
  import { ConnectorsService } from "../tools/connectors.service.js";
40
42
  import { dirDigest, getPath, readCatalogAgentTemplates, readCatalogTemplates, readCatalogThemes, setPath, skillFilesDigest, templatePluginProblem, themeAssetsDigest, } from "./catalog-content.js";
41
43
  import { markVersionApplied, versionUsable } from "./catalog-items.js";
@@ -43,10 +45,12 @@ import { agentsUsing, clashingOrgSkills, clashingPlatformSkills, componentOn, co
43
45
  import { credentialKey } from "./credential-key.js";
44
46
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
45
47
  import { CatalogItemLock } from "./locks.js";
46
- import { itemPendingError, itemRemovedError } from "./ownership.js";
48
+ import { isUsable, itemPendingError, itemRemovedError } from "./ownership.js";
47
49
  import { PlanStale, PlatformComponents } from "./platform-components.js";
48
50
  import { catalogSkillNames, PluginInstaller } from "./plugin-install.js";
51
+ import { wantedOn } from "./scope.js";
49
52
  import { PluginScopeSync } from "./scope-sync.js";
53
+ import { oweTemplateConnectors } from "./template-connector-jobs.js";
50
54
  import { compareVersions, satisfiesRange } from "./versions.js";
51
55
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
52
56
  const sha256 = (s) => createHash("sha256").update(s).digest("hex");
@@ -77,9 +81,10 @@ const filesDigest = (row) => skillFilesDigest(row.files.map((f) => ({ path: f.pa
77
81
  * components updated on their own, components with their own scope and the orgs whose linked
78
82
  * copy is pinned; lists removed components agents still use (they stay, spec §7.3), the org
79
83
  * connectors made from changed templates (all orgs, ruling E2; `credentialsReset` when the
80
- * credential shape changed), the templates it turns on that will need an org's input (added, or
81
- * no longer shipped off) and those it turns off (now shipped off, on only by default), the
82
- * deployment's extension move, and a `diffHash`. Refused: same version, a disabled or deleted
84
+ * credential shape changed), the connectors it creates from the templates it turns on (added,
85
+ * or no longer shipped off; plugin pages spec §5.2.3) with the setup state each starts in, the
86
+ * templates it turns off (now shipped off, on only by default), the orgs where the scope sync
87
+ * owed with it will install the plugin, the deployment's extension move, and a `diffHash`. Refused: same version, a disabled or deleted
83
88
  * item, a target without the extension the deployment runs for it or moving a config-declared
84
89
  * one, a template moving to another connector, a plugin another platform plugin depends on
85
90
  * outside its range, and an added skill whose name is taken where the plugin is on (rule 10).
@@ -92,11 +97,19 @@ const filesDigest = (row) => skillFilesDigest(row.files.map((f) => ({ path: f.pa
92
97
  * unpinned linked copies go with it; pinned copies keep their own version; a removed connector
93
98
  * template leaves its connectors as the orgs' own), clears the pins of linked copies, fans
94
99
  * changed templates out to every connector made from them (`applyTemplateIn`, under each org's
95
- * row lock, credentials cleared only for a changed credential shape), moves every org install to the version and audits
100
+ * row lock, credentials cleared only for a changed credential shape), creates the connectors of
101
+ * the templates it turns on (`ConnectorsService.createDeferredIn`, no outbound call, those orgs
102
+ * locked with the others), moves every org install to the version and audits
96
103
  * `plugin.platform_updated`; the scope sync of the item and its dependencies is owed in that
97
104
  * transaction (orgs get new dependencies by rule 9). A failure rolls the transaction back and
98
105
  * puts the extension back where it was (audit `plugin.platform_update_failed`, 502
99
106
  * `plugin.upgrade_failed`); files copied to `deployment/platform/` stay unreferenced.
107
+ * Transaction size: the whole fan-out (every changed template's connectors and every created
108
+ * connector, in every org where the plugin is on) is one transaction holding every touched org's
109
+ * row lock, with no batching; it grows with orgs x templates, so a deployment with very many orgs
110
+ * sees one long transaction (and other writes to those orgs waiting) per update. Deferred
111
+ * connectors (ruling R27) add one outbox row per org and no connector rows. Builtin plugins get no
112
+ * created connectors (ruling R28).
100
113
  * Storage is never read or written inside the transaction: the target's contents (and the
101
114
  * extension package, for `needsApproval`) are read and the platform files copied
102
115
  * (`PlatformComponents.prepareSync`) after the Redis lock is taken and before the transaction,
@@ -126,13 +139,16 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
126
139
  sync;
127
140
  log;
128
141
  guides;
142
+ outbox;
129
143
  constructor(kdb, txHost, adminLock, itemLock, orgLock, locks, storage, registry, ops,
130
144
  /** Reads the target's extension package (its permissions, for `needsApproval`). */
131
145
  blobs, config, platform,
132
146
  /** Template dependencies (the deployed connector kinds). */
133
147
  installer, connectors, sync, log,
134
148
  /** The connector template guides an update changes (the preview's `guideChanges`). */
135
- guides) {
149
+ guides,
150
+ /** Owes the template connector ensure of the orgs with a deferred connector (ruling R27). */
151
+ outbox) {
136
152
  this.kdb = kdb;
137
153
  this.txHost = txHost;
138
154
  this.adminLock = adminLock;
@@ -150,6 +166,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
150
166
  this.sync = sync;
151
167
  this.log = log;
152
168
  this.guides = guides;
169
+ this.outbox = outbox;
153
170
  }
154
171
  get db() {
155
172
  return this.kdb.db;
@@ -204,17 +221,21 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
204
221
  ...t,
205
222
  pickedBy: await pickedByIn(this.db, t.id, new Set([orgId])),
206
223
  })));
207
- const owned = { ...preview, ...(themes !== undefined && { themes }) };
224
+ // Other orgs' scope sync failures are theirs: the owner sees only that the scope sync will try
225
+ // to install there (their names, P3-19), not whether or why it failed. Display only as well
226
+ const scopeInstalls = preview.scopeInstalls.map((o) => o.orgId === orgId ? o : { orgId: o.orgId, orgName: o.orgName });
227
+ const owned = { ...preview, scopeInstalls, ...(themes !== undefined && { themes }) };
208
228
  return { ...owned, orgNames: await this.orgNamesOf(owned) };
209
229
  }
210
230
  /**
211
231
  * Locks, in sorted order and before the item (ruling P3-50), every live org the update may
212
- * write in: the orgs with connectors made from the plugin's connector templates and the item's
232
+ * write in: the orgs with connectors made from the plugin's connector templates, the orgs the
233
+ * update creates connectors in (`creating`, from the diff before the transaction) and the item's
213
234
  * owner org. `acting`: the owner org an owner update acts for, locked with its admin re-checked
214
235
  * (`catalog.upload`; deleted -> 404 `org.not_found`). Returns the live orgs locked; another
215
236
  * deleted one is skipped.
216
237
  */
217
- async lockUpdateOrgs(itemId, acting) {
238
+ async lockUpdateOrgs(itemId, creating, acting) {
218
239
  const item = await this.db
219
240
  .selectFrom("catalog_items")
220
241
  .select("owner_org_id")
@@ -228,7 +249,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
228
249
  .where("t.catalog_item_id", "=", itemId)
229
250
  .where("c.deleted_at", "is", null)
230
251
  .execute();
231
- const ids = new Set(made.map((r) => r.org_id));
252
+ const ids = new Set([...made.map((r) => r.org_id), ...creating]);
232
253
  if (item?.owner_org_id)
233
254
  ids.add(item.owner_org_id);
234
255
  if (acting !== undefined)
@@ -250,6 +271,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
250
271
  const ids = new Set([
251
272
  ...(p.extension?.orgs ?? []),
252
273
  ...p.connectorOrgs.map((c) => c.orgId),
274
+ ...p.scopeInstalls.map((o) => o.orgId),
253
275
  ...p.components.flatMap((c) => [...c.pinnedOrgs, ...(c.kept ?? []).map((k) => k.orgId)]),
254
276
  ...(p.themes ?? []).flatMap((t) => t.orgDefaults.map((o) => o.orgId)),
255
277
  ]);
@@ -394,7 +416,11 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
394
416
  }
395
417
  }
396
418
  step = "components";
397
- const diff = await this.commit(actor, itemId, input, opts, { contents: checked.contents, extension: ext }, prepared, owner, confirmPending);
419
+ const diff = await this.commit(actor, itemId, input, opts, {
420
+ contents: checked.contents,
421
+ extension: ext,
422
+ createOrgs: [...new Set(checked.creates.map((c) => c.orgId))],
423
+ }, prepared, owner, confirmPending);
398
424
  return {
399
425
  itemId,
400
426
  version: diff.to.version,
@@ -488,7 +514,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
488
514
  // The global lock order (ruling P3-50): the orgs (sorted; the acting owner org's admin
489
515
  // re-checked at its place), then the item, then its components; an org deletion locks its org
490
516
  // row, then the items it owns
491
- const liveOrgs = await this.lockUpdateOrgs(itemId, owner && actor !== null ? { orgId: owner.orgId, actor } : undefined);
517
+ const liveOrgs = await this.lockUpdateOrgs(itemId, pre.createOrgs, owner && actor !== null ? { orgId: owner.orgId, actor } : undefined);
492
518
  const named = await this.db
493
519
  .selectFrom("catalog_items")
494
520
  .select("name")
@@ -591,6 +617,21 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
591
617
  await this.connectors.applyTemplateIn(orgId, c.id, actor, prepared, opts.actorTokenId);
592
618
  }
593
619
  }
620
+ // Connectors of the templates the update turns on, in every org where the plugin is on (plugin
621
+ // pages spec §5.2.3): rows only, no outbound call; a ready one's tool list is owed through the
622
+ // outbox. Created by the kernel itself (no actor: the super admin need not be an org member)
623
+ for (const c of diff.creates) {
624
+ // Locked before the item (P3-50) from the diff before the transaction, which the diffHash
625
+ // check matched: the recomputed diff names only live, locked orgs (an org deleted since
626
+ // drops out of it and fails the hash check as stale), so this guards the invariant only
627
+ if (!liveOrgs.has(c.orgId))
628
+ throw stale();
629
+ await this.createTemplateConnectorIn(itemId, diff.to.version, c);
630
+ }
631
+ // A deferred connector writes nothing (ruling R27): the org's ensure creates it once its
632
+ // connector extension is on there and loaded (the job retries while it is not loaded)
633
+ for (const orgId of diff.deferredOrgs)
634
+ await oweTemplateConnectors(this.outbox, t, orgId);
594
635
  // One version for the deployment: every live org install of the plugin moves with it (one
595
636
  // still installing too; an install marked installed later records the platform version
596
637
  // current at its commit, PluginInstaller.markInstalled)
@@ -654,6 +695,9 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
654
695
  id: c.id,
655
696
  credentialsReset: c.credentialsReset,
656
697
  })),
698
+ ...(diff.deferredOrgs.length > 0 && {
699
+ deferredConnectors: diff.connectorOrgs.flatMap((o) => o.deferred.map((d) => ({ orgId: o.orgId, templateId: d.templateId, kind: d.kind }))),
700
+ }),
657
701
  ...opts.auditDetail,
658
702
  },
659
703
  });
@@ -695,6 +739,20 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
695
739
  ? { ...prepared, input: { ...prepared.input, resetCredentials: true } }
696
740
  : prepared;
697
741
  }
742
+ /**
743
+ * Creates the connector of a template the update turns on in an org, in the update's
744
+ * transaction (the org row locked): as an install creates it (`PluginInstaller.planConnector`,
745
+ * `ConnectorsService.createDeferredIn`: no outbound call, `needs_config` when the template needs
746
+ * an org credential or OAuth client), by the kernel itself, and recorded on the org's live
747
+ * install of the plugin when there is one (a builtin plugin has none).
748
+ */
749
+ async createTemplateConnectorIn(itemId, version, c) {
750
+ const ci = this.installer.planConnector(null, { itemId, version }, { id: c.templateId, file: c.file }, "", undefined);
751
+ const connectorId = await this.connectors.createDeferredIn(c.orgId, null, ci, {
752
+ auditDetail: { via: "platform_update" },
753
+ });
754
+ await this.installer.recordTemplateConnectorIn(c.orgId, itemId, connectorId, c.templateId, LIVE_INSTALL_STATUSES);
755
+ }
698
756
  /**
699
757
  * Computes an update (see the class comment). `target`: the target read from an org's staging
700
758
  * instead of `catalog_item_versions` (pre-flight F3). `owner`: an owner update (P3-12): the item
@@ -710,6 +768,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
710
768
  .select([
711
769
  "id",
712
770
  "name",
771
+ "scope",
713
772
  "disabled",
714
773
  "builtin",
715
774
  "deleted_at",
@@ -1131,7 +1190,8 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1131
1190
  c.kept = kept;
1132
1191
  }
1133
1192
  }
1134
- // The org connectors: changed templates' connectors, templates turned on (needing input) or off
1193
+ // The org connectors: changed templates' connectors, templates turned on (their connectors
1194
+ // created) or off
1135
1195
  const addedTemplates = components
1136
1196
  .filter((c) => c.kind === "connector_template" && c.change === "added")
1137
1197
  .map((c) => c.name)
@@ -1142,7 +1202,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1142
1202
  });
1143
1203
  const byOrg = new Map();
1144
1204
  const entry = (orgId) => {
1145
- const e = byOrg.get(orgId) ?? { orgId, connectors: [], needsConfig: [] };
1205
+ const e = byOrg.get(orgId) ?? { orgId, connectors: [], created: [], deferred: [] };
1146
1206
  byOrg.set(orgId, e);
1147
1207
  return e;
1148
1208
  };
@@ -1154,45 +1214,111 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1154
1214
  credentialsReset: c.credentialsReset,
1155
1215
  });
1156
1216
  }
1157
- if (addedTemplates.length > 0) {
1158
- for (const orgId of onOrgs) {
1159
- const on = await connectorTemplatesOn(db, orgId, itemId, addedTemplates);
1160
- if (on.size > 0)
1161
- entry(orgId).needsConfig.push(...on);
1162
- }
1163
- }
1164
- if (flipped.size > 0) {
1217
+ const creates = [];
1218
+ /** The orgs with a deferred connector: the update owes their template connector ensure. */
1219
+ const deferred = new Set();
1220
+ if (addedTemplates.length > 0 || flipped.size > 0) {
1221
+ // a named plugin still on in an org it no longer lists gets nothing new there (the scope
1222
+ // sync removes it)
1223
+ const listedOrgs = item.scope === "named" && !item.builtin
1224
+ ? new Set((await db
1225
+ .selectFrom("catalog_item_scope_orgs")
1226
+ .select("org_id")
1227
+ .where("item_id", "=", itemId)
1228
+ .execute()).map((r) => r.org_id))
1229
+ : undefined;
1165
1230
  const ids = [...flipped.keys()].sort();
1166
1231
  for (const orgId of onOrgs) {
1167
- const before = await connectorTemplatesOn(db, orgId, itemId, ids);
1168
- const after = await connectorTemplatesOn(db, orgId, itemId, ids, flipped);
1169
- for (const id of ids) {
1170
- const platformId = flippedIds.get(id);
1171
- if (after.has(id) && !before.has(id)) {
1172
- // connectors already made from it (it was on before) need no input
1173
- if ((await connectorsMadeFrom(db, orgId, platformId)) === 0) {
1174
- entry(orgId).needsConfig.push(id);
1232
+ if (listedOrgs !== undefined && !listedOrgs.has(orgId))
1233
+ continue;
1234
+ // a template the org already has a live connector from (one a switch-off kept) needs none
1235
+ const has = await this.installer.connectedTemplates(orgId, itemId);
1236
+ const turnedOn = [...(await connectorTemplatesOn(db, orgId, itemId, addedTemplates))];
1237
+ if (ids.length > 0) {
1238
+ const before = await connectorTemplatesOn(db, orgId, itemId, ids);
1239
+ const after = await connectorTemplatesOn(db, orgId, itemId, ids, flipped);
1240
+ for (const id of ids) {
1241
+ const platformId = flippedIds.get(id);
1242
+ if (after.has(id) && !before.has(id)) {
1243
+ turnedOn.push(id);
1244
+ }
1245
+ else if (before.has(id) && !after.has(id)) {
1246
+ const agents = await agentsUsing(db, orgId, "connector_template", [platformId]);
1247
+ const e = entry(orgId);
1248
+ e.turnedOff = [
1249
+ ...(e.turnedOff ?? []),
1250
+ {
1251
+ templateId: id,
1252
+ agents: agents.map((a) => ({ id: a.id, name: a.name })),
1253
+ connectorsKept: await connectorsMadeFrom(db, orgId, platformId),
1254
+ },
1255
+ ];
1175
1256
  }
1176
1257
  }
1177
- else if (before.has(id) && !after.has(id)) {
1178
- const agents = await agentsUsing(db, orgId, "connector_template", [platformId]);
1179
- const e = entry(orgId);
1180
- e.turnedOff = [
1181
- ...(e.turnedOff ?? []),
1182
- {
1183
- templateId: id,
1184
- agents: agents.map((a) => ({ id: a.id, name: a.name })),
1185
- connectorsKept: await connectorsMadeFrom(db, orgId, platformId),
1186
- },
1187
- ];
1258
+ }
1259
+ // A builtin plugin gets no connectors from an update until a design covers builtin
1260
+ // template connectors (ruling R28): it is on everywhere without an install
1261
+ if (item.builtin)
1262
+ continue;
1263
+ for (const id of turnedOn.sort()) {
1264
+ if (has.has(id))
1265
+ continue;
1266
+ const file = toTemplates.find((x) => x.id === id)?.file;
1267
+ if (file === undefined)
1268
+ continue;
1269
+ const t = file.template;
1270
+ // Decided here, not only at the confirm (ruling R27), with the checks the confirm runs:
1271
+ // the template's connector extension loaded on this replica (planning; the bootstrap's
1272
+ // first pass runs before the extensions load) and its kind available in the org (the
1273
+ // create's own check, `ConnectorsService.kindAvailable`). Otherwise it waits; the update
1274
+ // owes the org's template connector ensure, which creates it once both hold
1275
+ if (!deps.findConnector(t.plugin, t.connector) ||
1276
+ !(await this.connectors.kindAvailable(orgId, t.connector))) {
1277
+ deferred.add(orgId);
1278
+ entry(orgId).deferred.push({
1279
+ templateId: id,
1280
+ displayName: file.displayName,
1281
+ kind: t.connector,
1282
+ });
1283
+ continue;
1188
1284
  }
1285
+ creates.push({ orgId, templateId: id, file });
1286
+ entry(orgId).created.push({
1287
+ templateId: id,
1288
+ displayName: file.displayName,
1289
+ setup: setupNeed(t.auth) === undefined
1290
+ ? "ready"
1291
+ : "needs_config",
1292
+ });
1293
+ }
1294
+ }
1295
+ // the connectors as the confirm plans them, checked now: a refusal shows in the preview as
1296
+ // a readable target refusal
1297
+ for (const id of new Set(creates.map((c) => c.templateId))) {
1298
+ const file = creates.find((c) => c.templateId === id)?.file;
1299
+ try {
1300
+ this.installer.planConnector(null, { itemId, version: to.version }, { id, file }, "", undefined);
1301
+ }
1302
+ catch (e) {
1303
+ if (!(e instanceof ApiError))
1304
+ throw e;
1305
+ throw targetInvalid(`Connector template ${id} of version ${to.version} cannot become a connector (${e.message}); fix the template and import a new version`, [
1306
+ {
1307
+ reason: "template_connector_invalid",
1308
+ template: id,
1309
+ code: e.code,
1310
+ ...(e.details !== undefined && { causeDetails: e.details }),
1311
+ },
1312
+ ]);
1189
1313
  }
1190
1314
  }
1191
1315
  }
1316
+ const scopeInstalls = await this.scopeInstallsOf(item, onOrgs);
1192
1317
  const connectorOrgs = [...byOrg.values()]
1193
1318
  .map((e) => ({
1194
1319
  ...e,
1195
- needsConfig: e.needsConfig.sort(),
1320
+ created: e.created.sort((a, b) => a.templateId.localeCompare(b.templateId)),
1321
+ deferred: e.deferred.sort((a, b) => a.templateId.localeCompare(b.templateId)),
1196
1322
  connectors: e.connectors.sort((a, b) => `${a.templateId}\0${a.id}`.localeCompare(`${b.templateId}\0${b.id}`)),
1197
1323
  }))
1198
1324
  .sort((a, b) => a.orgId.localeCompare(b.orgId));
@@ -1217,6 +1343,8 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1217
1343
  reset: c.credentialsReset,
1218
1344
  })),
1219
1345
  connectorOrgs,
1346
+ // by org and failing state: an org's name or failure message changes nothing it does
1347
+ scopeInstalls: scopeInstalls.map((o) => ({ orgId: o.orgId, failing: o.failing === true })),
1220
1348
  // only when present: a diff without themes keeps the hash it had before themes
1221
1349
  ...(themes !== undefined && { themes }),
1222
1350
  }));
@@ -1228,7 +1356,10 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1228
1356
  components,
1229
1357
  extension,
1230
1358
  connectors,
1359
+ creates,
1360
+ deferredOrgs: [...deferred].sort(),
1231
1361
  connectorOrgs,
1362
+ scopeInstalls,
1232
1363
  ...(themes !== undefined && { themes }),
1233
1364
  contents,
1234
1365
  dependencies,
@@ -1441,6 +1572,52 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
1441
1572
  }
1442
1573
  return themesPreview(this.db, lost);
1443
1574
  }
1575
+ /**
1576
+ * {@link PlatformUpdatePreview.scopeInstalls}: the live orgs without a live install (`onOrgs`
1577
+ * are those with one) whose scope wants the plugin on, as the scope sync decides it
1578
+ * (`wantedOn`). None for a builtin plugin (on everywhere without an install) or one not usable.
1579
+ */
1580
+ async scopeInstallsOf(item, onOrgs) {
1581
+ if (item.builtin || !isUsable(item))
1582
+ return [];
1583
+ const [orgs, listed, switches, failures] = await Promise.all([
1584
+ this.db
1585
+ .selectFrom("orgs")
1586
+ .select(["id", "name"])
1587
+ .where("deleted_at", "is", null)
1588
+ .orderBy("id")
1589
+ .execute(),
1590
+ this.db
1591
+ .selectFrom("catalog_item_scope_orgs")
1592
+ .select("org_id")
1593
+ .where("item_id", "=", item.id)
1594
+ .execute(),
1595
+ this.db
1596
+ .selectFrom("catalog_item_org_switches")
1597
+ .select(["org_id", "enabled"])
1598
+ .where("item_id", "=", item.id)
1599
+ .execute(),
1600
+ this.db
1601
+ .selectFrom("plugin_scope_sync_failures")
1602
+ .select(["org_id", "message"])
1603
+ .where("item_id", "=", item.id)
1604
+ .execute(),
1605
+ ]);
1606
+ const failed = new Map(failures.map((r) => [r.org_id, r.message]));
1607
+ const on = new Set(onOrgs);
1608
+ const inList = new Set(listed.map((r) => r.org_id));
1609
+ const sw = new Map(switches.map((r) => [r.org_id, r.enabled]));
1610
+ return orgs
1611
+ .filter((o) => !on.has(o.id) && wantedOn(item, inList.has(o.id), sw.get(o.id) ?? null))
1612
+ .map((o) => {
1613
+ const lastFailure = failed.get(o.id);
1614
+ return {
1615
+ orgId: o.id,
1616
+ orgName: o.name,
1617
+ ...(lastFailure !== undefined && { failing: true, lastFailure }),
1618
+ };
1619
+ });
1620
+ }
1444
1621
  /** The orgs where the plugin is on: a live install (builtin: every live org). */
1445
1622
  async pluginOrgs(itemId, builtin) {
1446
1623
  if (builtin)
@@ -1497,7 +1674,8 @@ PlatformPluginUpdater = __decorate([
1497
1674
  __param(13, Inject(ConnectorsService)),
1498
1675
  __param(14, Inject(PluginScopeSync)),
1499
1676
  __param(15, Inject(KERNEL_LOGGER)),
1500
- __param(16, Inject(PluginGuides))
1677
+ __param(16, Inject(PluginGuides)),
1678
+ __param(17, Inject(OutboxService))
1501
1679
  ], PlatformPluginUpdater);
1502
1680
  export { PlatformPluginUpdater };
1503
1681
  /** The preview of a diff (without `guideChanges`, which reads PG). */
@@ -1510,6 +1688,7 @@ function previewOf(d) {
1510
1688
  components: d.components,
1511
1689
  extension: extensionView(d.extension),
1512
1690
  connectorOrgs: d.connectorOrgs,
1691
+ scopeInstalls: d.scopeInstalls,
1513
1692
  ...(d.themes !== undefined && { themes: d.themes }),
1514
1693
  diffHash: d.diffHash,
1515
1694
  };