@capybara-hq/kernel 0.1.0-rc.84 → 0.1.0-rc.86

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 (157) 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/job-ids.d.ts +29 -0
  15. package/dist/catalog/job-ids.js +29 -0
  16. package/dist/catalog/jobs.d.ts +12 -3
  17. package/dist/catalog/jobs.js +28 -7
  18. package/dist/catalog/marketplaces.service.d.ts +1 -1
  19. package/dist/catalog/org-catalog.controller.d.ts +2 -30
  20. package/dist/catalog/org-catalog.controller.js +3 -29
  21. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  22. package/dist/catalog/org-catalog.schemas.js +9 -23
  23. package/dist/catalog/org-catalog.service.js +14 -23
  24. package/dist/catalog/plugin-import.d.ts +21 -0
  25. package/dist/catalog/plugin-import.js +33 -3
  26. package/dist/catalog/plugin-install.d.ts +69 -76
  27. package/dist/catalog/plugin-install.js +156 -234
  28. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  29. package/dist/catalog/plugin-upgrade.js +222 -43
  30. package/dist/catalog/scope-sync.d.ts +22 -20
  31. package/dist/catalog/scope-sync.js +57 -42
  32. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  33. package/dist/catalog/template-connector-ensure.js +285 -0
  34. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  35. package/dist/catalog/template-connector-jobs.js +54 -0
  36. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  37. package/dist/catalog/template-connector-reconcile.js +114 -0
  38. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  39. package/dist/catalog/template-connectors.processor.js +101 -0
  40. package/dist/channels/cards.d.ts +7 -3
  41. package/dist/channels/cards.js +9 -4
  42. package/dist/channels/phrases.d.ts +10 -0
  43. package/dist/channels/phrases.js +10 -0
  44. package/dist/config/docs.js +1 -1
  45. package/dist/config/schema.d.ts +3 -0
  46. package/dist/config/schema.js +18 -12
  47. package/dist/ctx/create-ctx.d.ts +10 -1
  48. package/dist/ctx/create-ctx.js +42 -2
  49. package/dist/db/kernel-schema.d.ts +2 -1
  50. package/dist/device-access/device-access.module.d.ts +7 -0
  51. package/dist/device-access/device-access.module.js +41 -0
  52. package/dist/device-access/device-access.service.d.ts +142 -0
  53. package/dist/device-access/device-access.service.js +464 -0
  54. package/dist/device-access/token.d.ts +6 -0
  55. package/dist/device-access/token.js +6 -0
  56. package/dist/device-access/viewer-routes.d.ts +45 -0
  57. package/dist/device-access/viewer-routes.js +81 -0
  58. package/dist/device-access/viewer.d.ts +244 -0
  59. package/dist/device-access/viewer.js +844 -0
  60. package/dist/dial-in/access.d.ts +19 -0
  61. package/dist/dial-in/access.js +23 -0
  62. package/dist/dial-in/gateway.d.ts +48 -6
  63. package/dist/dial-in/gateway.js +145 -10
  64. package/dist/dial-in/keys.d.ts +7 -0
  65. package/dist/dial-in/keys.js +7 -0
  66. package/dist/dial-in/routes.d.ts +11 -3
  67. package/dist/dial-in/routes.js +15 -4
  68. package/dist/dial-in/streams.d.ts +58 -0
  69. package/dist/dial-in/streams.js +283 -0
  70. package/dist/errors.d.ts +2 -0
  71. package/dist/errors.js +2 -0
  72. package/dist/extensions/host.d.ts +13 -1
  73. package/dist/extensions/host.js +20 -1
  74. package/dist/extensions/org-config.d.ts +6 -1
  75. package/dist/extensions/org-config.js +15 -2
  76. package/dist/extensions/permission-set.d.ts +15 -1
  77. package/dist/extensions/permission-set.js +13 -1
  78. package/dist/extensions/permission-view.d.ts +6 -4
  79. package/dist/extensions/permission-view.js +6 -1
  80. package/dist/git/gateway.js +3 -1
  81. package/dist/http/error.filter.js +2 -0
  82. package/dist/http/gateway-routes.d.ts +8 -4
  83. package/dist/http/gateway-routes.js +4 -3
  84. package/dist/infra/lock/lock.service.d.ts +5 -1
  85. package/dist/infra/lock/lock.service.js +10 -4
  86. package/dist/infra/outbox/registry.d.ts +28 -0
  87. package/dist/infra/outbox/registry.js +33 -0
  88. package/dist/infra/queue/queue-names.d.ts +1 -1
  89. package/dist/infra/queue/queue-names.js +2 -0
  90. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  91. package/dist/infra/throttler/named-throttlers.js +16 -0
  92. package/dist/kernel.module.js +3 -0
  93. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  94. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  95. package/dist/orgs/org-owner.d.ts +7 -0
  96. package/dist/orgs/org-owner.js +16 -0
  97. package/dist/platform/operation.d.ts +3 -4
  98. package/dist/platform/ops/connectors.ops.js +8 -1
  99. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  100. package/dist/platform/ops/org-plugins.ops.js +18 -235
  101. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  102. package/dist/platform/ops/plugins.ops.js +3 -31
  103. package/dist/roles/gateway-role.d.ts +13 -6
  104. package/dist/roles/gateway-role.js +27 -9
  105. package/dist/roles/gateway.module.d.ts +2 -1
  106. package/dist/roles/gateway.module.js +13 -3
  107. package/dist/roles/worker-role.d.ts +9 -4
  108. package/dist/roles/worker-role.js +18 -5
  109. package/dist/roles/worker.module.d.ts +1 -1
  110. package/dist/roles/worker.module.js +8 -1
  111. package/dist/sandbox/device-services.d.ts +62 -0
  112. package/dist/sandbox/device-services.js +183 -0
  113. package/dist/sandbox/leases.d.ts +18 -1
  114. package/dist/sandbox/leases.js +75 -1
  115. package/dist/sandbox/network-grants.js +5 -2
  116. package/dist/sandbox/sandbox.module.d.ts +2 -1
  117. package/dist/sandbox/sandbox.module.js +5 -2
  118. package/dist/sandbox/sandbox.service.d.ts +44 -1
  119. package/dist/sandbox/sandbox.service.js +142 -5
  120. package/dist/setup/setup-guides.service.d.ts +9 -1
  121. package/dist/setup/setup-guides.service.js +38 -8
  122. package/dist/tools/admin-connectors.d.ts +3 -2
  123. package/dist/tools/admin-connectors.js +5 -4
  124. package/dist/tools/approvals.service.d.ts +45 -20
  125. package/dist/tools/approvals.service.js +19 -9
  126. package/dist/tools/call-scope.d.ts +60 -0
  127. package/dist/tools/call-scope.js +23 -0
  128. package/dist/tools/connector-setup.d.ts +28 -0
  129. package/dist/tools/connector-setup.js +33 -0
  130. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  131. package/dist/tools/connector-tools-jobs.js +40 -0
  132. package/dist/tools/connector-tools.processor.d.ts +32 -0
  133. package/dist/tools/connector-tools.processor.js +97 -0
  134. package/dist/tools/connectors.controller.d.ts +1 -0
  135. package/dist/tools/connectors.schemas.d.ts +1 -0
  136. package/dist/tools/connectors.schemas.js +5 -0
  137. package/dist/tools/connectors.service.d.ts +138 -14
  138. package/dist/tools/connectors.service.js +410 -50
  139. package/dist/tools/credentials.d.ts +35 -0
  140. package/dist/tools/credentials.js +89 -1
  141. package/dist/tools/drift.d.ts +5 -0
  142. package/dist/tools/drift.js +21 -2
  143. package/dist/tools/editable-endpoint.d.ts +23 -0
  144. package/dist/tools/editable-endpoint.js +92 -0
  145. package/dist/tools/network-asks.d.ts +13 -0
  146. package/dist/tools/network-asks.js +26 -2
  147. package/dist/tools/oauth/flow.d.ts +1 -1
  148. package/dist/tools/oauth/flow.js +3 -2
  149. package/dist/tools/pipeline.d.ts +30 -1
  150. package/dist/tools/pipeline.js +299 -59
  151. package/dist/tools/questions.service.d.ts +24 -3
  152. package/dist/tools/questions.service.js +3 -1
  153. package/dist/tools/registry.d.ts +14 -2
  154. package/dist/tools/registry.js +27 -6
  155. package/dist/tools/tools.module.js +4 -0
  156. package/package.json +3 -3
  157. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -24,10 +24,16 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
24
24
  import { KernelDb } from "../infra/database/kernel-db.js";
25
25
  import { TransactionHost } from "../infra/database/transaction-host.js";
26
26
  import { Transactional } from "../infra/database/transactional.decorator.js";
27
+ import { LockService } from "../infra/lock/lock.service.js";
28
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
27
29
  import { OrgLock } from "../orgs/org-lock.js";
30
+ import { firstOrgOwner } from "../orgs/org-owner.js";
28
31
  import { UUID_RE } from "../ui/registry.js";
32
+ import { connectorSetup, connectorSetups } from "./connector-setup.js";
33
+ import { CONNECTOR_TOOLS_JOB, CONNECTOR_TOOLS_QUEUE, connectorToolsJobId, } from "./connector-tools-jobs.js";
29
34
  import { CredentialMissing, Credentials, isOAuth, } from "./credentials.js";
30
35
  import { snapshot, ToolDrift, toolIssue, } from "./drift.js";
36
+ import { destinationChanged, mergeEditableEndpoint } from "./editable-endpoint.js";
31
37
  import { endpointCredentialIssues, endpointView } from "./endpoint.js";
32
38
  import { deriveSlug, isValidSlug, SLUG_RULE } from "./naming.js";
33
39
  import { checkOAuthUrl, discoverMcp, OAuthSetupError, oauthHttpOptions, pickAuthMethod, registerClient, } from "./oauth/discovery.js";
@@ -115,6 +121,8 @@ let ConnectorsService = class ConnectorsService {
115
121
  config;
116
122
  drift;
117
123
  orgLock;
124
+ outbox;
125
+ locks;
118
126
  txHost;
119
127
  guides;
120
128
  constructor(kdb, registry,
@@ -124,7 +132,11 @@ let ConnectorsService = class ConnectorsService {
124
132
  */
125
133
  extensions, credentials, config, drift,
126
134
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
127
- orgLock, txHost,
135
+ orgLock,
136
+ /** Owed work: the tool listings that follow a deferred create or a setup (§5.2.1). */
137
+ outbox,
138
+ /** The cross-replica lock of a deferred connector's lazy client registration (R16). */
139
+ locks, txHost,
128
140
  /** Setup guides of connector templates (spec 2026-11-09-setup-guides-v2-design.md §11). */
129
141
  guides) {
130
142
  this.kdb = kdb;
@@ -134,6 +146,8 @@ let ConnectorsService = class ConnectorsService {
134
146
  this.config = config;
135
147
  this.drift = drift;
136
148
  this.orgLock = orgLock;
149
+ this.outbox = outbox;
150
+ this.locks = locks;
137
151
  this.txHost = txHost;
138
152
  this.guides = guides;
139
153
  }
@@ -308,8 +322,10 @@ let ConnectorsService = class ConnectorsService {
308
322
  * endpoint against the connector's schema, the credential shape, the OAuth client and the OAuth
309
323
  * URL policy. `create` runs them first; a plugin install runs them for every template before it
310
324
  * creates anything, so bad input is a 400 rather than a failed install. Returns what they parsed.
325
+ * `deferred` ({@link createDeferredIn}): an OAuth connector takes no client (an org admin saves
326
+ * it on the connector later) and needs no `http.publicUrl` yet (the connect flow requires it).
311
327
  */
312
- checkCreateInput(actorAccountId, input) {
328
+ checkCreateInput(actorAccountId, input, opts = {}) {
313
329
  const slug = this.resolveSlug(input);
314
330
  const endpoint = this.parseEndpoint(input.connector, input.endpoint);
315
331
  const auth = input.auth;
@@ -328,7 +344,10 @@ let ConnectorsService = class ConnectorsService {
328
344
  this.credentials.validate(auth, owner, credential);
329
345
  return { slug, endpoint, owner, secret: credential };
330
346
  }
331
- if (!this.config.get().http.publicUrl)
347
+ if (opts.deferred && credential !== undefined && credential !== null) {
348
+ throw fail("credential", "The OAuth client is saved on the connector once it exists");
349
+ }
350
+ if (!opts.deferred && !this.config.get().http.publicUrl)
332
351
  throw publicUrlRequired();
333
352
  const http = oauthHttpOptions(this.config.get());
334
353
  const checked = (path, url) => {
@@ -340,12 +359,15 @@ let ConnectorsService = class ConnectorsService {
340
359
  }
341
360
  };
342
361
  if (auth.type === "oauth_client") {
343
- parseOAuthClient(credential, true);
362
+ if (!opts.deferred)
363
+ parseOAuthClient(credential, true);
344
364
  checked("auth.tokenUrl", auth.tokenUrl);
345
365
  return { slug, endpoint };
346
366
  }
347
- if (auth.client === "manual")
348
- parseOAuthClient(credential, false);
367
+ if (auth.client === "manual") {
368
+ if (!opts.deferred)
369
+ parseOAuthClient(credential, false);
370
+ }
349
371
  else if (credential !== undefined) {
350
372
  throw fail("credential", "With client dcr the client is registered automatically; omit credential or use client manual");
351
373
  }
@@ -415,10 +437,59 @@ let ConnectorsService = class ConnectorsService {
415
437
  }
416
438
  /** The org-locked, re-checked insert of {@link create} (the outbound checks ran before). */
417
439
  async createIn(orgId, actorAccountId, input, actorTokenId, auditDetail, c) {
440
+ const issues = await this.writeConnectorIn(orgId, actorAccountId, input, actorTokenId, auditDetail, c);
441
+ return { connector: await this.detail(this.db, orgId, c.id, actorAccountId), issues };
442
+ }
443
+ /**
444
+ * Creates a connector without listing its tools (plugin pages spec §5.2.1 "Tool lists without
445
+ * a network call in a transaction"): for plugin installs, scope syncs and upgrades, which create
446
+ * connectors inside their own transaction. It makes no outbound call: the row is written with an
447
+ * empty tool list (`tools_synced_at` null, so the first listing counts as the install's and
448
+ * applies the template's default policies), a static credential in `input` is stored, and an
449
+ * OAuth connector takes no client (an org admin saves it, which turns the connector ready).
450
+ * When the connector is `ready` and its credential is not personal, the listing is owed in the
451
+ * same transaction (`connector-tools-list`, trigger `created`); a personal one is listed on its
452
+ * first member credential. `actorAccountId` null: the kernel itself (a scope sync); the
453
+ * connector then has no creator (`created_by` null, ruling R17) and the audit no actor. With an
454
+ * actor, `connectors.manage` is checked under the org lock. A `client: "dcr"` connector
455
+ * registers its client on the first connect ({@link clientForConnect}). Returns the id.
456
+ */
457
+ async createDeferredIn(orgId, actorAccountId, input, opts = {}) {
458
+ await this.assertKindAvailable(orgId, input.connector);
459
+ const { slug, endpoint, owner, secret } = this.checkCreateInput(actorAccountId, input, {
460
+ deferred: true,
461
+ });
462
+ const id = randomUUID();
463
+ await this.writeConnectorIn(orgId, actorAccountId, input, opts.actorTokenId, opts.auditDetail, {
464
+ id,
465
+ slug,
466
+ endpoint,
467
+ owner,
468
+ secret,
469
+ oauth: undefined,
470
+ listed: undefined,
471
+ // nobody was shown the template's guide
472
+ guideAck: null,
473
+ });
474
+ const auth = input.auth;
475
+ const personal = auth.type !== "none" && auth.ownership === "personal";
476
+ if (!personal && (await connectorSetup(this.credentials, orgId, id, auth)) === "ready") {
477
+ await this.oweToolList(orgId, id, "created");
478
+ }
479
+ return id;
480
+ }
481
+ /**
482
+ * The org-locked, re-checked insert shared by {@link createIn} and {@link createDeferredIn}
483
+ * (joins their transaction); returns the snapshot's issues.
484
+ */
485
+ async writeConnectorIn(orgId, actorAccountId, input, actorTokenId, auditDetail, c) {
418
486
  const { id, endpoint, owner, secret, oauth } = c;
419
487
  const auth = input.auth;
420
488
  const t = this.db;
421
- await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "connectors.manage");
489
+ if (actorAccountId === null)
490
+ await this.orgLock.lock(orgId);
491
+ else
492
+ await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "connectors.manage");
422
493
  if (input.template) {
423
494
  await assertItemInstallable(t, orgId, input.template.itemId, input.template.approvedBy ?? input.template.itemId);
424
495
  }
@@ -469,6 +540,7 @@ let ConnectorsService = class ConnectorsService {
469
540
  auth: JSON.stringify(auth),
470
541
  git_hosts: input.git !== undefined ? JSON.stringify(input.git.hosts) : null,
471
542
  description: ownDescription(input.description),
543
+ // null: created by the kernel as no person (ruling R17)
472
544
  created_by: actorAccountId,
473
545
  catalog_item_id: input.template?.itemId ?? null,
474
546
  catalog_version: input.template?.version ?? null,
@@ -479,8 +551,9 @@ let ConnectorsService = class ConnectorsService {
479
551
  template_tool_policies: input.template?.defaultToolPolicies
480
552
  ? JSON.stringify(input.template.defaultToolPolicies)
481
553
  : null,
482
- // 授权码连接器安装时不拍快照(A16):留空,首个快照按安装处理
483
- ...(auth.type !== "oauth_code" && { tools_synced_at: sql `now()` }),
554
+ // no listing (an authorization-code connector, A16, or a deferred create): left empty,
555
+ // the first snapshot counts as the install's
556
+ ...(c.listed !== undefined && { tools_synced_at: sql `now()` }),
484
557
  })
485
558
  .execute();
486
559
  await this.insertTools(id, rows, input.template?.defaultToolPolicies);
@@ -516,7 +589,26 @@ let ConnectorsService = class ConnectorsService {
516
589
  }),
517
590
  },
518
591
  });
519
- return { connector: await this.detail(t, orgId, id, actorAccountId), issues };
592
+ return issues;
593
+ }
594
+ /**
595
+ * Owes a listing of the connector's tools in the caller's transaction (`connector-tools-list`,
596
+ * processed by `ConnectorToolsProcessor` after the commit). `accountId`: the member whose
597
+ * credential lists a personal connector.
598
+ */
599
+ async oweToolList(orgId, connectorId, trigger, accountId) {
600
+ // the owing transaction's id: one job per owing transaction
601
+ const { rows } = await sql `SELECT pg_current_xact_id()::text AS xact`.execute(this.db);
602
+ const xact = rows[0]?.xact;
603
+ if (xact === undefined)
604
+ throw new Error("no transaction id");
605
+ await this.outbox.add({
606
+ queue: CONNECTOR_TOOLS_QUEUE,
607
+ name: CONNECTOR_TOOLS_JOB,
608
+ jobId: connectorToolsJobId(connectorId, trigger, xact, accountId),
609
+ data: { orgId, connectorId, ...(accountId !== undefined && { accountId }) },
610
+ orgId,
611
+ });
520
612
  }
521
613
  /**
522
614
  * Checks a template update before anything is written (the platform plugin update): the endpoint
@@ -556,7 +648,7 @@ let ConnectorsService = class ConnectorsService {
556
648
  * template's default policies (`template_tool_policies`) and the policies the org did not set
557
649
  * (`policy_source` `template` or `derived`): a tool the new template names takes its policy
558
650
  * (`template`), an unnamed `template` tool returns to the policy derived from its annotations,
559
- * unnamed `derived` tools and the org's own (`admin`) stay (spec §10). Tool definitions are untouched (the next refresh takes the new endpoint through drift review). With `resetCredentials` the credentials are replaced.
651
+ * unnamed `derived` tools and the org's own (`admin`) stay (spec §10). Tool definitions are untouched (the next refresh takes the new endpoint through drift review). With `resetCredentials` the credentials are replaced, and a connector that ends `ready` owes its tool list through the outbox (`template_updated`, ruling R19).
560
652
  * Audits `connector.template_applied`. Deleted / missing -> `connector.not_found`.
561
653
  */
562
654
  async applyTemplateIn(orgId, connectorId,
@@ -650,12 +742,33 @@ let ConnectorsService = class ConnectorsService {
650
742
  ...(before.use_for_git && !botCapable && { useForGit: { from: true, to: false } }),
651
743
  },
652
744
  });
745
+ // Cleared credentials under a new credential shape (ruling R19): a connector that ends ready
746
+ // (its new auth needs no org input, or the update brought it) lists its tools again through
747
+ // the outbox; one that ends needs_config owes nothing until an org admin configures it, and a
748
+ // personal one is listed on its first member credential
749
+ const personal = input.auth.type !== "none" && input.auth.ownership === "personal";
750
+ if (input.resetCredentials &&
751
+ !personal &&
752
+ (await connectorSetup(this.credentials, orgId, connectorId, input.auth)) === "ready") {
753
+ await this.oweToolList(orgId, connectorId, "template_updated");
754
+ }
755
+ }
756
+ /**
757
+ * Whether a connector of `kind` can be created in the org now: the kind is loaded on this
758
+ * replica and its providing extension (the first loaded one, as {@link kinds}) is enabled in
759
+ * the org. The create's own check ({@link assertKindAvailable}); the platform update decides its
760
+ * deferred template connectors with it, so a connector it previews as created is never refused
761
+ * at the confirm for its kind.
762
+ */
763
+ async kindAvailable(orgId, kind) {
764
+ return (this.registry.findConnector(kind) !== undefined &&
765
+ (await this.registry.connectorKindAvailable(orgId, kind)));
653
766
  }
654
767
  /** Refuses a loaded kind whose extension is not enabled in the org (the same notion as {@link kinds}). */
655
768
  async assertKindAvailable(orgId, kind) {
656
769
  if (!this.registry.findConnector(kind))
657
770
  return; // unknown kinds fail in parseEndpoint
658
- if (!(await this.registry.connectorKindAvailable(orgId, kind))) {
771
+ if (!(await this.kindAvailable(orgId, kind))) {
659
772
  throw new ApiError("connector.kind_unavailable", `Connector kind "${kind}" is not enabled for this organization; enable its plugin first`);
660
773
  }
661
774
  }
@@ -694,7 +807,7 @@ let ConnectorsService = class ConnectorsService {
694
807
  else if (input.name !== undefined) {
695
808
  slug = deriveSlug(input.name) ?? PREVIEW_SLUG;
696
809
  }
697
- // 先校验凭据形状,再做任何外连
810
+ // check the credential shape before any outbound call
698
811
  const auth = input.auth;
699
812
  const credential = input.credential ?? undefined;
700
813
  let inject;
@@ -810,16 +923,21 @@ let ConnectorsService = class ConnectorsService {
810
923
  throw notFound();
811
924
  return r;
812
925
  }
813
- summary(r) {
926
+ /** The connector's derived setup state (spec §5.2.1), from its org input's key presence. */
927
+ setupOf(orgId, r) {
928
+ return connectorSetup(this.credentials, orgId, r.id, r.auth);
929
+ }
930
+ summary(r, setup) {
814
931
  return {
815
932
  id: r.id,
816
933
  slug: r.slug,
817
934
  name: r.name,
818
935
  connector: r.connector,
819
- // 大段文本(如 OpenAPI 文档)不回显全文,见 endpoint.ts
936
+ // a large text (such as an OpenAPI document) is not echoed in full: see endpoint.ts
820
937
  endpoint: endpointView(r.endpoint),
821
938
  auth: r.auth,
822
939
  status: r.status,
940
+ setup,
823
941
  platformTemplateId: r.platform_template_id ?? null,
824
942
  catalogItemId: r.catalog_item_id ?? null,
825
943
  git: r.git_hosts !== null && r.git_hosts.length > 0 ? { hosts: r.git_hosts } : null,
@@ -852,7 +970,7 @@ let ConnectorsService = class ConnectorsService {
852
970
  .where("connector_id", "=", connectorId)
853
971
  .orderBy("name")
854
972
  .execute();
855
- const s = this.summary(r);
973
+ const s = this.summary(r, await this.setupOf(orgId, r));
856
974
  const auth = s.auth;
857
975
  const status = await this.credentials.status(orgId, connectorId, auth, viewerAccountId);
858
976
  return {
@@ -988,7 +1106,8 @@ let ConnectorsService = class ConnectorsService {
988
1106
  .orderBy("created_at")
989
1107
  .orderBy("id")
990
1108
  .execute();
991
- return rows.map((r) => this.summary(r));
1109
+ const setups = await connectorSetups(this.credentials, orgId, rows.map((r) => ({ id: r.id, auth: r.auth })));
1110
+ return rows.map((r) => this.summary(r, setups.get(r.id) ?? "needs_config"));
992
1111
  }
993
1112
  /**
994
1113
  * Where a live connector of the org takes its icon from: its platform template and its plugin
@@ -1003,7 +1122,11 @@ let ConnectorsService = class ConnectorsService {
1003
1122
  async get(orgId, connectorId, viewerAccountId) {
1004
1123
  return this.detail(this.db, orgId, connectorId, viewerAccountId);
1005
1124
  }
1006
- /** 改名、启停连接器、工具启停与默认策略、批量把无注解工具改为 allow(`connectors.manage`)。 */
1125
+ /**
1126
+ * Renames, switches on or off, sets tool status and default policies, allows unannotated tools
1127
+ * in bulk (`connectors.manage`), and changes the editable endpoint fields of a template connector
1128
+ * ({@link endpointChange}).
1129
+ */
1007
1130
  async update(orgId, connectorId, actorAccountId, patch, actorTokenId, auditDetail) {
1008
1131
  const t = this.db;
1009
1132
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "connectors.manage");
@@ -1073,13 +1196,15 @@ let ConnectorsService = class ConnectorsService {
1073
1196
  if (problems.length > 0) {
1074
1197
  throw new ApiError("validation_failed", "Request validation failed", problems);
1075
1198
  }
1199
+ const ep = patch.endpoint !== undefined ? await this.endpointChange(t, app, patch.endpoint) : undefined;
1076
1200
  const gitChanged = patch.useForGit !== undefined && patch.useForGit !== app.use_for_git;
1077
1201
  const description = patch.description !== undefined ? ownDescription(patch.description) : undefined;
1078
1202
  const descriptionChanged = description !== undefined && description !== app.description;
1079
1203
  if (patch.name !== undefined ||
1080
1204
  patch.status !== undefined ||
1081
1205
  gitChanged ||
1082
- descriptionChanged) {
1206
+ descriptionChanged ||
1207
+ ep !== undefined) {
1083
1208
  await t
1084
1209
  .updateTable("connectors")
1085
1210
  .set({
@@ -1092,6 +1217,7 @@ let ConnectorsService = class ConnectorsService {
1092
1217
  }),
1093
1218
  ...(gitChanged && { use_for_git: patch.useForGit === true }),
1094
1219
  ...(descriptionChanged && { description }),
1220
+ ...(ep !== undefined && { endpoint: JSON.stringify(ep.endpoint) }),
1095
1221
  updated_at: sql `now()`,
1096
1222
  })
1097
1223
  .where("id", "=", connectorId)
@@ -1133,6 +1259,27 @@ let ConnectorsService = class ConnectorsService {
1133
1259
  .where("name", "=", name)
1134
1260
  .execute();
1135
1261
  }
1262
+ // tokens issued for another destination, and members' own static credentials, are never sent
1263
+ // to the new one (members connect again); a client registered there (`dcr`) or whose endpoints
1264
+ // MCP discovery found there goes too (the admin saves a manual one again, discovered at the new
1265
+ // url); a manual client with fixed endpoints and the org's static credential stay (the admin
1266
+ // chose the new destination)
1267
+ const cleared = [];
1268
+ if (ep?.destinationChanged) {
1269
+ if (isOAuth(appAuth)) {
1270
+ await this.credentials.clearOAuthTokens(orgId, connectorId);
1271
+ cleared.push("tokens");
1272
+ if (appAuth.type === "oauth_code" &&
1273
+ (appAuth.client === "dcr" || appAuth.discovery === "mcp")) {
1274
+ await this.credentials.clearOAuthClient(orgId, connectorId);
1275
+ cleared.push("client");
1276
+ }
1277
+ }
1278
+ else if (appAuth.type !== "none" && appAuth.ownership === "personal") {
1279
+ await this.credentials.clearMemberCredentials(orgId, connectorId);
1280
+ cleared.push("member");
1281
+ }
1282
+ }
1136
1283
  await audit(t, {
1137
1284
  actorAccountId,
1138
1285
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -1147,10 +1294,58 @@ let ConnectorsService = class ConnectorsService {
1147
1294
  ...(descriptionChanged && { description: { from: app.description, to: description } }),
1148
1295
  ...(toolChanges.length > 0 && { tools: Object.fromEntries(toolChanges) }),
1149
1296
  ...(allowed.length > 0 && { allowedUnannotated: allowed }),
1297
+ // the changed paths, never their values (a header may carry a tenant key)
1298
+ ...(ep !== undefined && { endpoint: ep.changed }),
1299
+ // which credentials a destination change cleared, by name
1300
+ ...(cleared.length > 0 && { credentialsCleared: cleared }),
1150
1301
  },
1151
1302
  });
1303
+ if (ep !== undefined) {
1304
+ // the tools of the new endpoint: listed after the commit (no outbound call here)
1305
+ const personal = appAuth.type !== "none" && appAuth.ownership === "personal";
1306
+ if (!personal && (await this.setupOf(orgId, app)) === "ready") {
1307
+ await this.oweToolList(orgId, connectorId, "endpoint_changed");
1308
+ }
1309
+ }
1152
1310
  return this.detail(t, orgId, connectorId, actorAccountId);
1153
1311
  }
1312
+ /**
1313
+ * The endpoint a PATCH makes (under the org lock, the row locked): only a connector made from a
1314
+ * live platform connector template (else 400 at `endpoint`), only the paths that template's
1315
+ * current `editableEndpoint` lists (`mergeEditableEndpoint`, onto the stored endpoint), checked
1316
+ * again as at create (the connector's `endpointSchema`, no credential in the endpoint, a URL for
1317
+ * MCP discovery). Its URL policy is the connection's (`net`), applied when the tools are listed.
1318
+ * Undefined when nothing changes.
1319
+ */
1320
+ async endpointChange(t, app, given) {
1321
+ const template = app.platform_template_id === null
1322
+ ? undefined
1323
+ : await t
1324
+ .selectFrom("platform_connector_templates")
1325
+ .select("file")
1326
+ .where("id", "=", app.platform_template_id)
1327
+ .where("deleted_at", "is", null)
1328
+ .executeTakeFirst();
1329
+ if (template === undefined) {
1330
+ throw fail("endpoint", "Only a connector made from a connector template has editable endpoint fields; create a new connector for another endpoint");
1331
+ }
1332
+ const file = template.file;
1333
+ const merged = mergeEditableEndpoint(app.endpoint, file.template?.editableEndpoint ?? [], given, "");
1334
+ const endpoint = this.parseEndpoint(app.connector, merged.endpoint);
1335
+ const auth = app.auth;
1336
+ if (auth.type === "oauth_code" && auth.discovery === "mcp") {
1337
+ if (!isObj(endpoint) || typeof endpoint.url !== "string") {
1338
+ throw fail("endpoint.url", "MCP OAuth discovery needs an endpoint URL");
1339
+ }
1340
+ }
1341
+ if (JSON.stringify(endpoint) === JSON.stringify(app.endpoint))
1342
+ return undefined;
1343
+ return {
1344
+ endpoint,
1345
+ changed: merged.changed,
1346
+ destinationChanged: destinationChanged(app.endpoint, endpoint),
1347
+ };
1348
+ }
1154
1349
  /**
1155
1350
  * The read-only checks of {@link setGitPushPolicy} (the Platform operation's precheck): the
1156
1351
  * connector exists (`connector.not_found`) and declares git hosts (400 on `policy`); with
@@ -1358,21 +1553,7 @@ let ConnectorsService = class ConnectorsService {
1358
1553
  async refreshIn(orgId, connectorId, actorAccountId, actorTokenId, opts, rows, issues) {
1359
1554
  const t = this.db;
1360
1555
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, opts.trigger === "first_connect" ? "connectors.use" : "connectors.manage");
1361
- const locked = await this.row(t, orgId, connectorId, true);
1362
- const changes = await this.drift.apply(locked, rows);
1363
- // 首个快照(授权码连接器首个成员连接后):按目录模板的 defaultToolPolicies 设默认策略(policy_source 'template')
1364
- const templatePolicies = locked.template_tool_policies;
1365
- if (locked.tools_synced_at === null && templatePolicies) {
1366
- for (const [name, policy] of Object.entries(templatePolicies)) {
1367
- await t
1368
- .updateTable("connector_tools")
1369
- .set({ default_policy: policy, policy_source: "template" })
1370
- .where("connector_id", "=", connectorId)
1371
- .where("name", "=", name)
1372
- .where("policy_source", "=", "derived")
1373
- .execute();
1374
- }
1375
- }
1556
+ const changes = await this.drift.apply(await this.row(t, orgId, connectorId, true), rows);
1376
1557
  await audit(t, {
1377
1558
  actorAccountId,
1378
1559
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -1388,11 +1569,90 @@ let ConnectorsService = class ConnectorsService {
1388
1569
  };
1389
1570
  }
1390
1571
  /**
1391
- * 复核一个待复核的工具(`connectors.manage`,spec 7.3)。`approve`:采用待复核的新定义(若有)并启用,
1392
- * `reviewed_at` 记为现在;默认策略按新定义的注解重新推导,除非管理员设过(`policy_source = admin`)且来源没变。
1393
- * `reject`:停用,丢弃待复核的新定义、保留旧定义;从未复核过的工具被拒后 `reviewed_at` 仍为空(仍可再批准)。
1394
- * 工具不存在 → 404 `connector.tool_not_found`;不可复核(已复核且无待复核定义,或已消失)→ 409 `connector.tool_not_pending`;新定义不合规(如 key 不合法)不能通过 → `validation_failed`。
1395
- * 采用新定义即换了指纹:旧的「以后都允许」/「本会话都允许」授权按指纹比对自然失效(D8)。审计 `connector.tool_reviewed`。
1572
+ * The consumer of a `connector-tools-list` job (`ConnectorToolsProcessor`, after the commit
1573
+ * that owed it): lists the connector's tools as {@link refresh} does and stores them with the
1574
+ * same compare-and-write, as the kernel itself (audit `connector.tools_refreshed` without an
1575
+ * actor). Idempotent: listing again compares against the stored snapshot and changes nothing.
1576
+ * Skipped (nothing written) when the connector is gone, disabled or `needs_config`, or the
1577
+ * credential to list with is missing (a later save owes a new job); an outbound failure throws,
1578
+ * so the queue retries it, and leaves the connector `ready` without tools (the drift scan
1579
+ * lists a connector without a snapshot too).
1580
+ */
1581
+ async listToolsForJob(data) {
1582
+ const { orgId, connectorId, accountId } = data;
1583
+ const app = await this.db
1584
+ .selectFrom("connectors")
1585
+ .selectAll()
1586
+ .where("id", "=", connectorId)
1587
+ .where("org_id", "=", orgId)
1588
+ .where("deleted_at", "is", null)
1589
+ .executeTakeFirst();
1590
+ if (app?.status !== "active")
1591
+ return "skipped";
1592
+ const auth = app.auth;
1593
+ const personal = auth.type !== "none" && auth.ownership === "personal";
1594
+ if (personal && accountId === undefined)
1595
+ return "skipped";
1596
+ if ((await this.setupOf(orgId, app)) === "needs_config")
1597
+ return "skipped";
1598
+ // a personal credential is that member's; an org credential needs an account id only
1599
+ // nominally: the creator, else the org's owner
1600
+ const as = accountId ?? app.created_by ?? (await firstOrgOwner(this.db, orgId));
1601
+ if (as === undefined)
1602
+ return "skipped";
1603
+ let listed;
1604
+ try {
1605
+ listed = await this.drift.listTools(orgId, app.connector, app.endpoint, () => this.credentials.injection(orgId, connectorId, auth, as), { connectorId, job: CONNECTOR_TOOLS_JOB }, (last) => this.credentials.onUnauthorized(orgId, connectorId, auth, as, last));
1606
+ }
1607
+ catch (e) {
1608
+ if (e instanceof CredentialMissing)
1609
+ return "skipped";
1610
+ throw e;
1611
+ }
1612
+ const { rows } = snapshot(app.slug, listed.specs, listed.resources);
1613
+ return (await this.storeListedIn(orgId, connectorId, rows, accountId)) ? "listed" : "skipped";
1614
+ }
1615
+ /**
1616
+ * The org-locked write of {@link listToolsForJob}; false (nothing written) when the org or the
1617
+ * connector is gone, disabled or `needs_config` by now.
1618
+ */
1619
+ async storeListedIn(orgId, connectorId, rows, accountId) {
1620
+ const t = this.db;
1621
+ if (!(await this.orgLock.tryLock(orgId)))
1622
+ return false;
1623
+ const locked = await t
1624
+ .selectFrom("connectors")
1625
+ .selectAll()
1626
+ .where("id", "=", connectorId)
1627
+ .where("org_id", "=", orgId)
1628
+ .where("deleted_at", "is", null)
1629
+ .forUpdate()
1630
+ .executeTakeFirst();
1631
+ // switched off or lost its input since the listing: write nothing (a later save owes a job)
1632
+ if (locked?.status !== "active")
1633
+ return false;
1634
+ if ((await this.setupOf(orgId, locked)) !== "ready")
1635
+ return false;
1636
+ const changes = await this.drift.apply(locked, rows);
1637
+ await audit(t, {
1638
+ orgId,
1639
+ action: "connector.tools_refreshed",
1640
+ target: connectorId,
1641
+ detail: { ...changes, trigger: "job", ...(accountId !== undefined && { accountId }) },
1642
+ });
1643
+ return true;
1644
+ }
1645
+ /**
1646
+ * Reviews a tool pending review (`connectors.manage`, spec 7.3). `approve`: adopts the pending
1647
+ * definition (if any) and enables it, `reviewed_at` set to now; the default policy is derived
1648
+ * again from the new definition's annotations unless an admin set it (`policy_source = admin`)
1649
+ * and the source did not change. `reject`: disables it, drops the pending definition and keeps
1650
+ * the old one; a never-reviewed tool keeps `reviewed_at` empty after a rejection (it can still
1651
+ * be approved). A missing tool -> 404 `connector.tool_not_found`; not reviewable (reviewed with
1652
+ * nothing pending, or gone) -> 409 `connector.tool_not_pending`; a non-compliant new definition
1653
+ * (such as an invalid key) cannot pass -> `validation_failed`. Adopting a new definition changes
1654
+ * the fingerprint: earlier "always allow" / "allow for this conversation" grants stop matching
1655
+ * (D8). Audits `connector.tool_reviewed`.
1396
1656
  */
1397
1657
  async reviewTool(orgId, connectorId, name, action, actorAccountId, actorTokenId) {
1398
1658
  const t = this.db;
@@ -1479,7 +1739,7 @@ let ConnectorsService = class ConnectorsService {
1479
1739
  const app = await this.row(this.db, orgId, connectorId);
1480
1740
  const auth = app.auth;
1481
1741
  if (isOAuth(auth)) {
1482
- await this.rotateOAuthClient(orgId, connectorId, actorAccountId, auth, value, actorTokenId, auditDetail);
1742
+ await this.rotateOAuthClient(orgId, connectorId, actorAccountId, auth, app.endpoint, value, actorTokenId, auditDetail);
1483
1743
  return;
1484
1744
  }
1485
1745
  }
@@ -1489,11 +1749,20 @@ let ConnectorsService = class ConnectorsService {
1489
1749
  async setCredentialIn(orgId, connectorId, actorAccountId, ownership, value, actorTokenId, auditDetail) {
1490
1750
  const t = this.db;
1491
1751
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, ownership === "org" ? "connectors.manage" : "connectors.use");
1492
- const app = await this.row(t, orgId, connectorId);
1752
+ const app = await this.row(t, orgId, connectorId, true);
1493
1753
  const auth = app.auth;
1494
1754
  const owner = ownership === "org" ? { kind: "org" } : { kind: "user", accountId: actorAccountId };
1495
1755
  this.credentials.validate(auth, owner, value);
1756
+ const before = await this.setupOf(orgId, app);
1496
1757
  await this.credentials.setStatic(orgId, connectorId, auth, owner, value);
1758
+ if (ownership === "org" && before === "needs_config") {
1759
+ // the org credential it lacked: now ready, its tools follow (§5.2.1)
1760
+ await this.oweToolList(orgId, connectorId, "configured");
1761
+ }
1762
+ else if (ownership === "personal" && app.tools_synced_at === null) {
1763
+ // a personal connector with no tool list yet: the member's credential lists it
1764
+ await this.oweToolList(orgId, connectorId, "connected", actorAccountId);
1765
+ }
1497
1766
  await audit(t, {
1498
1767
  actorAccountId,
1499
1768
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -1504,19 +1773,27 @@ let ConnectorsService = class ConnectorsService {
1504
1773
  });
1505
1774
  }
1506
1775
  /**
1507
- * 轮换 OAuth 客户端(Ruling A18,组织凭据接口,`connectors.manage`):值为 `{ clientId, clientSecret }`。
1508
- * 客户端凭据连接器先用新客户端取一次 token 验证(失败 → 502 `connector.connect_failed`,什么都不改),再替换客户端并以
1509
- * 新 token 替换缓存的组织 token;授权码连接器只限手填 client,只替换客户端(成员的 token 保留,之后刷新若得到
1510
- * invalid_client 会作废)。审计只记类型与归属。
1776
+ * Rotates the OAuth client (Ruling A18, the org credential route, `connectors.manage`): the
1777
+ * value is `{ clientId, clientSecret }`. A client credentials connector first fetches a token
1778
+ * with the new client to check it (failure -> 502 `connector.connect_failed`, nothing changed),
1779
+ * then replaces the client and the cached org token with the new one; an authorization-code
1780
+ * connector (manual client only) replaces only the client (members' tokens stay, and a later
1781
+ * refresh answered `invalid_client` drops them). The audit records the type and ownership only.
1782
+ * A connector with no client yet (`needs_config`, plugin pages spec §5.2.1) gets its first one
1783
+ * set up as a create does (the client credentials token, or the authorization-code endpoints
1784
+ * from discovery or the auth's URLs), outside any transaction.
1511
1785
  */
1512
- async rotateOAuthClient(orgId, connectorId, actorAccountId, auth, value, actorTokenId, auditDetail) {
1786
+ async rotateOAuthClient(orgId, connectorId, actorAccountId, auth, endpoint, value, actorTokenId, auditDetail) {
1513
1787
  if (auth.type === "oauth_code" && auth.client !== "manual") {
1514
1788
  throw fail("auth.client", "The OAuth client of this connector was registered automatically and cannot be replaced");
1515
1789
  }
1516
1790
  const next = parseOAuthClient(value, auth.type === "oauth_client", "");
1517
1791
  const current = await this.credentials.oauthClient(orgId, connectorId);
1518
1792
  if (!current) {
1519
- throw new ApiError("connector.connect_failed", "The connector has no registered OAuth client; reinstall it");
1793
+ // a dynamic registration is refused above, so the public URL is never used here
1794
+ const first = await this.prepareOAuth(auth, endpoint, next, "");
1795
+ await this.storeOAuthClient(orgId, connectorId, actorAccountId, auth, first.client, first.tokens, actorTokenId, auditDetail);
1796
+ return;
1520
1797
  }
1521
1798
  const client = { ...current, clientId: next.clientId };
1522
1799
  delete client.clientSecret;
@@ -1544,10 +1821,16 @@ let ConnectorsService = class ConnectorsService {
1544
1821
  async storeOAuthClient(orgId, connectorId, actorAccountId, auth, client, tokens, actorTokenId, auditDetail) {
1545
1822
  const t = this.db;
1546
1823
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "connectors.manage");
1547
- await this.row(t, orgId, connectorId, true);
1824
+ const app = await this.row(t, orgId, connectorId, true);
1825
+ const before = await this.setupOf(orgId, app);
1548
1826
  await this.credentials.setOAuthClient(orgId, connectorId, client);
1549
1827
  if (tokens)
1550
1828
  await this.credentials.setOAuthTokens(orgId, connectorId, { kind: "org" }, tokens);
1829
+ // the client it lacked: now ready; a client credentials connector lists its tools with the
1830
+ // org token (an authorization-code one waits for a member's first connection, A16)
1831
+ if (before === "needs_config" && auth.ownership === "org") {
1832
+ await this.oweToolList(orgId, connectorId, "configured");
1833
+ }
1551
1834
  await audit(t, {
1552
1835
  actorAccountId,
1553
1836
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -1557,6 +1840,66 @@ let ConnectorsService = class ConnectorsService {
1557
1840
  detail: { ...auditDetail, type: auth.type, ownership: "org" },
1558
1841
  });
1559
1842
  }
1843
+ /**
1844
+ * The OAuth client a member's connect starts with (`OAuthFlow.start`): the stored one, else, for
1845
+ * an authorization-code connector with `client: "dcr"` created without one
1846
+ * ({@link createDeferredIn}, plugin pages spec §5.2.1, ruling R16), one registered now: discovery
1847
+ * and dynamic registration run once across replicas under the lock
1848
+ * `connector-dcr:<connectorId>` (re-read inside it, never inside a transaction), and the client
1849
+ * is stored unless another registration stored one first. Null: no client and none to register
1850
+ * (a manual client an org admin has not saved). An outbound failure is 502
1851
+ * `connector.connect_failed`.
1852
+ */
1853
+ async clientForConnect(orgId, connectorId, accountId) {
1854
+ const existing = await this.credentials.oauthClient(orgId, connectorId);
1855
+ if (existing)
1856
+ return existing;
1857
+ const app = await this.row(this.db, orgId, connectorId);
1858
+ const auth = app.auth;
1859
+ if (auth.type !== "oauth_code" || auth.client !== "dcr")
1860
+ return null;
1861
+ const publicUrl = this.config.get().http.publicUrl;
1862
+ if (!publicUrl)
1863
+ throw publicUrlRequired();
1864
+ return this.locks.run(`connector-dcr:${connectorId}`,
1865
+ // one registration (discovery + DCR, each bounded by the 30 s OAuth timeout) per holder
1866
+ { ttlMs: 90_000, waitMs: 90_000 }, async () => {
1867
+ const again = await this.credentials.oauthClient(orgId, connectorId);
1868
+ if (again)
1869
+ return again;
1870
+ const { client } = await this.prepareOAuth(auth, app.endpoint, undefined, publicUrl);
1871
+ const discovered = isObj(app.endpoint) ? app.endpoint.url : undefined;
1872
+ return this.storeRegisteredClientIn(orgId, connectorId, accountId, client, discovered);
1873
+ });
1874
+ }
1875
+ /**
1876
+ * The org-locked write of {@link clientForConnect}: the first stored client wins. Re-checked
1877
+ * under the row lock: a connector whose auth stopped being `oauth_code` with `client: "dcr"`
1878
+ * meanwhile (a template update), or whose endpoint URL is no longer the one `discoveredAt`
1879
+ * registered with (an admin's edit), stores nothing and gets null.
1880
+ */
1881
+ async storeRegisteredClientIn(orgId, connectorId, accountId, client, discoveredAt) {
1882
+ await this.orgLock.lock(orgId);
1883
+ const locked = await this.row(this.db, orgId, connectorId, true);
1884
+ const stored = await this.credentials.oauthClient(orgId, connectorId);
1885
+ if (stored)
1886
+ return stored;
1887
+ const auth = locked.auth;
1888
+ if (auth.type !== "oauth_code" || auth.client !== "dcr")
1889
+ return null;
1890
+ if ((isObj(locked.endpoint) ? locked.endpoint.url : undefined) !== discoveredAt)
1891
+ return null;
1892
+ await this.credentials.setOAuthClient(orgId, connectorId, client);
1893
+ await audit(this.db, {
1894
+ actorAccountId: accountId,
1895
+ orgId,
1896
+ // the registered client is the connector's org-level input
1897
+ action: "connector.credential.set",
1898
+ target: connectorId,
1899
+ detail: { type: "oauth_code", ownership: "org", registered: "dcr" },
1900
+ });
1901
+ return client;
1902
+ }
1560
1903
  /** 删除发起人自己的个人凭据(`connectors.use`);本来就没有也成功。 */
1561
1904
  async clearMyCredential(orgId, connectorId, actorAccountId, actorTokenId, auditDetail) {
1562
1905
  const t = this.db;
@@ -1580,6 +1923,15 @@ let ConnectorsService = class ConnectorsService {
1580
1923
  __decorate([
1581
1924
  Transactional()
1582
1925
  ], ConnectorsService.prototype, "createIn", null);
1926
+ __decorate([
1927
+ Transactional()
1928
+ ], ConnectorsService.prototype, "createDeferredIn", null);
1929
+ __decorate([
1930
+ Transactional({ propagation: "mandatory" })
1931
+ ], ConnectorsService.prototype, "writeConnectorIn", null);
1932
+ __decorate([
1933
+ Transactional({ propagation: "mandatory" })
1934
+ ], ConnectorsService.prototype, "oweToolList", null);
1583
1935
  __decorate([
1584
1936
  Transactional({ propagation: "mandatory" })
1585
1937
  ], ConnectorsService.prototype, "applyTemplateIn", null);
@@ -1613,6 +1965,9 @@ __decorate([
1613
1965
  __decorate([
1614
1966
  Transactional()
1615
1967
  ], ConnectorsService.prototype, "refreshIn", null);
1968
+ __decorate([
1969
+ Transactional()
1970
+ ], ConnectorsService.prototype, "storeListedIn", null);
1616
1971
  __decorate([
1617
1972
  Transactional()
1618
1973
  ], ConnectorsService.prototype, "reviewTool", null);
@@ -1622,6 +1977,9 @@ __decorate([
1622
1977
  __decorate([
1623
1978
  Transactional()
1624
1979
  ], ConnectorsService.prototype, "storeOAuthClient", null);
1980
+ __decorate([
1981
+ Transactional()
1982
+ ], ConnectorsService.prototype, "storeRegisteredClientIn", null);
1625
1983
  __decorate([
1626
1984
  Transactional()
1627
1985
  ], ConnectorsService.prototype, "clearMyCredential", null);
@@ -1634,7 +1992,9 @@ ConnectorsService = __decorate([
1634
1992
  __param(4, Inject(KernelConfigService)),
1635
1993
  __param(5, Inject(ToolDrift)),
1636
1994
  __param(6, Inject(OrgLock)),
1637
- __param(7, Inject(TransactionHost)),
1638
- __param(8, Inject(PluginGuides))
1995
+ __param(7, Inject(OutboxService)),
1996
+ __param(8, Inject(LockService)),
1997
+ __param(9, Inject(TransactionHost)),
1998
+ __param(10, Inject(PluginGuides))
1639
1999
  ], ConnectorsService);
1640
2000
  export { ConnectorsService };