@capybara-hq/kernel 0.1.0-rc.84 → 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 (89) 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/org-catalog.controller.d.ts +2 -30
  19. package/dist/catalog/org-catalog.controller.js +3 -29
  20. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  21. package/dist/catalog/org-catalog.schemas.js +9 -23
  22. package/dist/catalog/org-catalog.service.js +14 -23
  23. package/dist/catalog/plugin-import.d.ts +21 -0
  24. package/dist/catalog/plugin-import.js +33 -3
  25. package/dist/catalog/plugin-install.d.ts +69 -76
  26. package/dist/catalog/plugin-install.js +156 -234
  27. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  28. package/dist/catalog/plugin-upgrade.js +222 -43
  29. package/dist/catalog/scope-sync.d.ts +22 -20
  30. package/dist/catalog/scope-sync.js +57 -42
  31. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  32. package/dist/catalog/template-connector-ensure.js +285 -0
  33. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  34. package/dist/catalog/template-connector-jobs.js +54 -0
  35. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  36. package/dist/catalog/template-connector-reconcile.js +114 -0
  37. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  38. package/dist/catalog/template-connectors.processor.js +101 -0
  39. package/dist/db/kernel-schema.d.ts +2 -1
  40. package/dist/extensions/org-config.d.ts +6 -1
  41. package/dist/extensions/org-config.js +15 -2
  42. package/dist/git/gateway.js +3 -1
  43. package/dist/infra/outbox/registry.d.ts +28 -0
  44. package/dist/infra/outbox/registry.js +33 -0
  45. package/dist/infra/queue/queue-names.d.ts +1 -1
  46. package/dist/infra/queue/queue-names.js +2 -0
  47. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  48. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  49. package/dist/orgs/org-owner.d.ts +7 -0
  50. package/dist/orgs/org-owner.js +16 -0
  51. package/dist/platform/operation.d.ts +3 -4
  52. package/dist/platform/ops/connectors.ops.js +8 -1
  53. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  54. package/dist/platform/ops/org-plugins.ops.js +18 -235
  55. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  56. package/dist/platform/ops/plugins.ops.js +3 -31
  57. package/dist/roles/worker-role.d.ts +9 -4
  58. package/dist/roles/worker-role.js +18 -5
  59. package/dist/roles/worker.module.d.ts +1 -1
  60. package/dist/roles/worker.module.js +8 -1
  61. package/dist/setup/setup-guides.service.d.ts +9 -1
  62. package/dist/setup/setup-guides.service.js +38 -8
  63. package/dist/tools/admin-connectors.d.ts +3 -2
  64. package/dist/tools/admin-connectors.js +5 -4
  65. package/dist/tools/connector-setup.d.ts +28 -0
  66. package/dist/tools/connector-setup.js +33 -0
  67. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  68. package/dist/tools/connector-tools-jobs.js +40 -0
  69. package/dist/tools/connector-tools.processor.d.ts +32 -0
  70. package/dist/tools/connector-tools.processor.js +97 -0
  71. package/dist/tools/connectors.controller.d.ts +1 -0
  72. package/dist/tools/connectors.schemas.d.ts +1 -0
  73. package/dist/tools/connectors.schemas.js +5 -0
  74. package/dist/tools/connectors.service.d.ts +138 -14
  75. package/dist/tools/connectors.service.js +410 -50
  76. package/dist/tools/credentials.d.ts +35 -0
  77. package/dist/tools/credentials.js +89 -1
  78. package/dist/tools/drift.d.ts +5 -0
  79. package/dist/tools/drift.js +21 -2
  80. package/dist/tools/editable-endpoint.d.ts +23 -0
  81. package/dist/tools/editable-endpoint.js +92 -0
  82. package/dist/tools/oauth/flow.d.ts +1 -1
  83. package/dist/tools/oauth/flow.js +3 -2
  84. package/dist/tools/pipeline.js +14 -5
  85. package/dist/tools/registry.d.ts +14 -2
  86. package/dist/tools/registry.js +27 -6
  87. package/dist/tools/tools.module.js +4 -0
  88. package/package.json +2 -2
  89. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -7,6 +7,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
7
7
  import { KernelDb } from "../infra/database/kernel-db.js";
8
8
  import { LockService } from "../infra/lock/lock.service.js";
9
9
  import type { KernelLogger } from "../log.js";
10
+ import { type SetupNeed } from "./connector-setup.js";
10
11
  import { type OAuthClientRecord, type OAuthTokenRecord } from "./oauth/tokens.js";
11
12
  export type Ownership = "org" | "personal";
12
13
  /** 静态认证方式(连接器安装时选定);`headers` 的值本身就是凭据。 */
@@ -112,6 +113,21 @@ export declare class Credentials {
112
113
  validate(auth: ConnectorAuth, owner: CredentialOwner, value: unknown): asserts value is StaticSecret;
113
114
  setStatic(orgId: string, connectorId: string, auth: ConnectorAuth, owner: CredentialOwner, value: StaticSecret): Promise<void>;
114
115
  clear(orgId: string, connectorId: string, owner: CredentialOwner): Promise<void>;
116
+ /**
117
+ * Deletes a connector's OAuth tokens (the org's and every member's), keeping its client: its
118
+ * endpoint changed, so tokens issued for the old one are not sent to the new one.
119
+ */
120
+ clearOAuthTokens(orgId: string, connectorId: string): Promise<void>;
121
+ /**
122
+ * Deletes every member's own credential of a connector (static or OAuth), keeping the org's and
123
+ * the client: its endpoint's destination changed, so members' secrets never go to the new one.
124
+ */
125
+ clearMemberCredentials(orgId: string, connectorId: string): Promise<void>;
126
+ /**
127
+ * Deletes a connector's OAuth client (one registered (`dcr`) or discovered at an endpoint that
128
+ * moved).
129
+ */
130
+ clearOAuthClient(orgId: string, connectorId: string): Promise<void>;
115
131
  /** 删除某连接器的全部凭据(组织凭据与所有成员的个人凭据),连接器删除时调用。 */
116
132
  clearConnector(orgId: string, connectorId: string): Promise<void>;
117
133
  /** 删除某账号在该组织所有连接器上的个人凭据,见 {@link clearAccountCredentials}。 */
@@ -143,6 +159,25 @@ export declare class Credentials {
143
159
  }>;
144
160
  /** 只看与 auth.ownership 对应的那一条凭据是否存在(不解密);none 恒为 connected。 */
145
161
  status(orgId: string, connectorId: string, auth: ConnectorAuth, accountId: string): Promise<"connected" | "missing">;
162
+ /**
163
+ * Whether the org input a connector needs (`setupNeed`) is stored: its OAuth client for
164
+ * `client`, its org credential for `credential`. Reads the key's presence only, never decrypts.
165
+ */
166
+ hasOrgInput(orgId: string, connectorId: string, need: SetupNeed): Promise<boolean>;
167
+ /**
168
+ * The org inputs stored for several connectors at once (one query, key presence only): per
169
+ * connector id, whether its OAuth client and its org credential exist.
170
+ */
171
+ orgInputs(orgId: string, connectorIds: string[]): Promise<Map<string, Record<SetupNeed, boolean>>>;
172
+ /**
173
+ * The gate that keeps a `needs_config` connector from being called on every path (tool calls,
174
+ * `/` prompts and `@` resources, drift checks, refresh, the git gateway; spec §5.2.1): a
175
+ * connector whose auth needs an OAuth client that is not stored gets an org `CredentialMissing`
176
+ * before any token is read or presented, even when a member still holds one. A missing org
177
+ * credential needs no extra read: reading it throws the same error.
178
+ */
179
+ private requireClient;
180
+ private hasKey;
146
181
  /** 返回本次请求要注入的头 / 查询参数;缺凭据抛 CredentialMissing。 */
147
182
  injection(orgId: string, connectorId: string, auth: ConnectorAuth, accountId: string): Promise<AuthInjection>;
148
183
  /**
@@ -16,6 +16,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { LockService } from "../infra/lock/lock.service.js";
18
18
  import { KERNEL_LOGGER, KEYRING, REDIS } from "../infra/tokens.js";
19
+ import { setupNeed } from "./connector-setup.js";
19
20
  import { oauthHttpOptions } from "./oauth/discovery.js";
20
21
  import { basicClientAuth, OAuthReconnectRequired, OAuthTokens, } from "./oauth/tokens.js";
21
22
  import { injectionSecrets } from "./redact.js";
@@ -209,6 +210,39 @@ let Credentials = class Credentials {
209
210
  async clear(orgId, connectorId, owner) {
210
211
  await this.secrets().delete(orgId, keyOf(connectorId, owner));
211
212
  }
213
+ /**
214
+ * Deletes a connector's OAuth tokens (the org's and every member's), keeping its client: its
215
+ * endpoint changed, so tokens issued for the old one are not sent to the new one.
216
+ */
217
+ async clearOAuthTokens(orgId, connectorId) {
218
+ const users = userKey(connectorId, "x").slice(0, -1);
219
+ await this.db
220
+ .deleteFrom("secrets")
221
+ .where("namespace", "=", NAMESPACE)
222
+ .where("org_id", "=", orgId)
223
+ .where((eb) => eb.or([eb("key", "=", orgKey(connectorId)), eb("key", "like", `${users}%`)]))
224
+ .execute();
225
+ }
226
+ /**
227
+ * Deletes every member's own credential of a connector (static or OAuth), keeping the org's and
228
+ * the client: its endpoint's destination changed, so members' secrets never go to the new one.
229
+ */
230
+ async clearMemberCredentials(orgId, connectorId) {
231
+ const users = userKey(connectorId, "x").slice(0, -1);
232
+ await this.db
233
+ .deleteFrom("secrets")
234
+ .where("namespace", "=", NAMESPACE)
235
+ .where("org_id", "=", orgId)
236
+ .where("key", "like", `${users}%`)
237
+ .execute();
238
+ }
239
+ /**
240
+ * Deletes a connector's OAuth client (one registered (`dcr`) or discovered at an endpoint that
241
+ * moved).
242
+ */
243
+ async clearOAuthClient(orgId, connectorId) {
244
+ await this.secrets().delete(orgId, clientKey(connectorId));
245
+ }
212
246
  /** 删除某连接器的全部凭据(组织凭据与所有成员的个人凭据),连接器删除时调用。 */
213
247
  async clearConnector(orgId, connectorId) {
214
248
  const prefix = orgKey(connectorId).slice(0, -"org".length);
@@ -338,6 +372,58 @@ let Credentials = class Credentials {
338
372
  : auth.ownership === "personal"
339
373
  ? userKey(connectorId, accountId)
340
374
  : orgKey(connectorId);
375
+ return (await this.hasKey(orgId, key)) ? "connected" : "missing";
376
+ }
377
+ /**
378
+ * Whether the org input a connector needs (`setupNeed`) is stored: its OAuth client for
379
+ * `client`, its org credential for `credential`. Reads the key's presence only, never decrypts.
380
+ */
381
+ async hasOrgInput(orgId, connectorId, need) {
382
+ return this.hasKey(orgId, need === "client" ? clientKey(connectorId) : orgKey(connectorId));
383
+ }
384
+ /**
385
+ * The org inputs stored for several connectors at once (one query, key presence only): per
386
+ * connector id, whether its OAuth client and its org credential exist.
387
+ */
388
+ async orgInputs(orgId, connectorIds) {
389
+ const out = new Map(connectorIds.map((id) => [id, { client: false, credential: false }]));
390
+ if (connectorIds.length === 0)
391
+ return out;
392
+ const keys = new Map();
393
+ for (const id of connectorIds) {
394
+ keys.set(clientKey(id), [id, "client"]);
395
+ keys.set(orgKey(id), [id, "credential"]);
396
+ }
397
+ const rows = await this.db
398
+ .selectFrom("secrets")
399
+ .select("key")
400
+ .where("namespace", "=", NAMESPACE)
401
+ .where("org_id", "=", orgId)
402
+ .where("key", "in", [...keys.keys()])
403
+ .execute();
404
+ for (const r of rows) {
405
+ const hit = keys.get(r.key);
406
+ const entry = hit && out.get(hit[0]);
407
+ if (hit && entry)
408
+ entry[hit[1]] = true;
409
+ }
410
+ return out;
411
+ }
412
+ /**
413
+ * The gate that keeps a `needs_config` connector from being called on every path (tool calls,
414
+ * `/` prompts and `@` resources, drift checks, refresh, the git gateway; spec §5.2.1): a
415
+ * connector whose auth needs an OAuth client that is not stored gets an org `CredentialMissing`
416
+ * before any token is read or presented, even when a member still holds one. A missing org
417
+ * credential needs no extra read: reading it throws the same error.
418
+ */
419
+ async requireClient(orgId, connectorId, auth) {
420
+ if (setupNeed(auth) !== "client")
421
+ return;
422
+ if (!(await this.hasOrgInput(orgId, connectorId, "client"))) {
423
+ throw new CredentialMissing(connectorId, "org");
424
+ }
425
+ }
426
+ async hasKey(orgId, key) {
341
427
  const row = await this.db
342
428
  .selectFrom("secrets")
343
429
  .select("key")
@@ -345,12 +431,13 @@ let Credentials = class Credentials {
345
431
  .where("org_id", "=", orgId)
346
432
  .where("key", "=", key)
347
433
  .executeTakeFirst();
348
- return row ? "connected" : "missing";
434
+ return row !== undefined;
349
435
  }
350
436
  /** 返回本次请求要注入的头 / 查询参数;缺凭据抛 CredentialMissing。 */
351
437
  async injection(orgId, connectorId, auth, accountId) {
352
438
  if (auth.type === "none")
353
439
  return { headers: {} };
440
+ await this.requireClient(orgId, connectorId, auth);
354
441
  const owner = ownerOf(auth, accountId);
355
442
  if (isOAuth(auth)) {
356
443
  const token = await this.oauthCall(connectorId, auth, () => this.oauth().accessToken(orgId, connectorId, auth, owner));
@@ -396,6 +483,7 @@ let Credentials = class Credentials {
396
483
  if (auth.type === "none" || auth.type === "headers") {
397
484
  throw new Error(`credentials: auth type ${auth.type} cannot authenticate git`);
398
485
  }
486
+ await this.requireClient(orgId, connectorId, auth);
399
487
  const owner = ownerOf(auth, accountId);
400
488
  let user = username;
401
489
  let password;
@@ -105,10 +105,15 @@ export declare class ToolDrift {
105
105
  /**
106
106
  * 把新快照与当前工具行比对并写入(调用方已在事务内锁住连接器行:`mandatory`);返回按名排序的变化。
107
107
  * 规则见文件头。待复核的新定义也写进 `tool_specs`(内容寻址,只增不改)。
108
+ * The first snapshot (`tools_synced_at` null: an authorization-code connector's first member
109
+ * connection, a deferred create's first listing, whichever of the tools job, a refresh or the
110
+ * drift scan writes it) also sets the template's default policies (`policy_source 'template'`)
111
+ * on the tools whose policy is still derived.
108
112
  */
109
113
  apply(app: {
110
114
  id: string;
111
115
  tools_synced_at: Date | null;
116
+ template_tool_policies?: Record<string, "allow" | "ask" | "deny"> | null;
112
117
  }, rows: SnapshotRow[]): Promise<DriftChanges>;
113
118
  /**
114
119
  * 后台检查一个连接器(维护队列的 worker 上执行,没有发起人):拉工具清单 → 比对写入 → 有变化记审计
@@ -19,6 +19,7 @@ import { asPlatform } from "../infra/database/org-scope.js";
19
19
  import { TransactionHost } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { firstOrgOwner } from "../orgs/org-owner.js";
22
23
  import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
24
  import { HIDDEN_FORMAT_RE } from "../text.js";
24
25
  import { CredentialMissing, Credentials, isOAuth } from "./credentials.js";
@@ -260,6 +261,10 @@ let ToolDrift = class ToolDrift {
260
261
  /**
261
262
  * 把新快照与当前工具行比对并写入(调用方已在事务内锁住连接器行:`mandatory`);返回按名排序的变化。
262
263
  * 规则见文件头。待复核的新定义也写进 `tool_specs`(内容寻址,只增不改)。
264
+ * The first snapshot (`tools_synced_at` null: an authorization-code connector's first member
265
+ * connection, a deferred create's first listing, whichever of the tools job, a refresh or the
266
+ * drift scan writes it) also sets the template's default policies (`policy_source 'template'`)
267
+ * on the tools whose policy is still derived.
263
268
  */
264
269
  // org-filter: app is the connector row the caller read with its org filter and holds locked
265
270
  // FOR UPDATE (applyChecked, ConnectorsService's refresh); connector_tools has no org column
@@ -397,6 +402,18 @@ let ToolDrift = class ToolDrift {
397
402
  .where("name", "in", removed)
398
403
  .execute();
399
404
  }
405
+ const templatePolicies = app.template_tool_policies;
406
+ if (app.tools_synced_at === null && templatePolicies) {
407
+ for (const [name, policy] of Object.entries(templatePolicies)) {
408
+ await t
409
+ .updateTable("connector_tools")
410
+ .set({ default_policy: policy, policy_source: "template" })
411
+ .where("connector_id", "=", app.id)
412
+ .where("name", "=", name)
413
+ .where("policy_source", "=", "derived")
414
+ .execute();
415
+ }
416
+ }
400
417
  const any = added.length + changed.length + removed.length > 0;
401
418
  await t
402
419
  .updateTable("connectors")
@@ -447,9 +464,11 @@ let ToolDrift = class ToolDrift {
447
464
  const auth = app.auth;
448
465
  const personal = auth.type !== "none" && !isOAuth(auth) && auth.ownership === "personal";
449
466
  const personalOAuth = auth.type === "oauth_code";
467
+ // an org credential needs an account id only nominally: the creator, else the org's owner
468
+ const orgActor = async () => app.created_by ?? (await firstOrgOwner(this.db.db, orgId));
450
469
  const accounts = personal || personalOAuth
451
470
  ? await this.credentials.personalHolders(orgId, connectorId, PERSONAL_CANDIDATES)
452
- : [app.created_by];
471
+ : [await orgActor()].filter((a) => a !== undefined);
453
472
  if (accounts.length === 0) {
454
473
  log.info("tool drift check skipped: no member credential", { orgId, connectorId });
455
474
  return { status: "skipped", reason: "no_credential" };
@@ -486,7 +505,7 @@ let ToolDrift = class ToolDrift {
486
505
  const t = this.db.db;
487
506
  const locked = await t
488
507
  .selectFrom("connectors")
489
- .select(["id", "tools_synced_at"])
508
+ .select(["id", "tools_synced_at", "template_tool_policies"])
490
509
  .where("id", "=", connectorId)
491
510
  .where("org_id", "=", orgId)
492
511
  .where("deleted_at", "is", null)
@@ -0,0 +1,23 @@
1
+ /** Every leaf dot path of an object (arrays and non-object values are leaves). */
2
+ export declare function leafPaths(v: Record<string, unknown>, base?: string): string[];
3
+ /** The value at a dot path of `v` (own keys only), undefined when absent. */
4
+ export declare function getPath(v: unknown, path: string): unknown;
5
+ /** Sets the value at a dot path of `obj`, creating the objects on the way. */
6
+ export declare function setPath(obj: Record<string, unknown>, path: string, value: unknown): void;
7
+ /**
8
+ * `base` (a copy) with the fields of `given` merged in, each only at a path listed in `editable`
9
+ * or under one; any other path -> 400 `validation_failed` at `<at>.endpoint.<path>` ("set by the
10
+ * template"; `at` empty: `endpoint.<path>`), an unsafe key or a non-object `given` too. Returns the merged endpoint and the
11
+ * editable paths `given` set (its leaves, for an audit that names paths, never values).
12
+ */
13
+ export declare function mergeEditableEndpoint(base: unknown, editable: readonly string[], given: unknown, at: string): {
14
+ endpoint: Record<string, unknown>;
15
+ changed: string[];
16
+ };
17
+ /**
18
+ * Whether going from endpoint `before` to `after` may send requests somewhere else: any
19
+ * difference outside {@link SAME_DESTINATION_FIELDS} (a URL, a base URL, a region, a tenant host,
20
+ * a record whose keys hold dots, …), compared as whole values with those top-level keys left out.
21
+ * Credentials held for `before` are then never sent to `after`.
22
+ */
23
+ export declare function destinationChanged(before: unknown, after: unknown): boolean;
@@ -0,0 +1,92 @@
1
+ import { ApiError } from "../errors.js";
2
+ // The endpoint fields an org may change on a connector made from a connector template (the
3
+ // template's `editableEndpoint`): shared by creating one more connector from the template
4
+ // (`templateConnectorInput`) and by editing a template connector (`ConnectorsService.update`).
5
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6
+ const UNSAFE_KEYS = new Set(["__proto__", "prototype", "constructor"]);
7
+ const fail = (path, message) => new ApiError("validation_failed", "Request validation failed", [{ path, message }]);
8
+ /** Every leaf dot path of an object (arrays and non-object values are leaves). */
9
+ export function leafPaths(v, base = "") {
10
+ const out = [];
11
+ for (const [k, x] of Object.entries(v)) {
12
+ const p = base ? `${base}.${k}` : k;
13
+ if (isObj(x) && Object.keys(x).length > 0)
14
+ out.push(...leafPaths(x, p));
15
+ else
16
+ out.push(p);
17
+ }
18
+ return out;
19
+ }
20
+ /** The value at a dot path of `v` (own keys only), undefined when absent. */
21
+ export function getPath(v, path) {
22
+ let node = v;
23
+ for (const seg of path.split(".")) {
24
+ if (!isObj(node) || !Object.hasOwn(node, seg))
25
+ return undefined;
26
+ node = node[seg];
27
+ }
28
+ return node;
29
+ }
30
+ /** Sets the value at a dot path of `obj`, creating the objects on the way. */
31
+ export function setPath(obj, path, value) {
32
+ const segs = path.split(".");
33
+ let node = obj;
34
+ for (const seg of segs.slice(0, -1)) {
35
+ if (!isObj(node[seg]))
36
+ node[seg] = {};
37
+ node = node[seg];
38
+ }
39
+ node[segs[segs.length - 1]] = value;
40
+ }
41
+ /**
42
+ * `base` (a copy) with the fields of `given` merged in, each only at a path listed in `editable`
43
+ * or under one; any other path -> 400 `validation_failed` at `<at>.endpoint.<path>` ("set by the
44
+ * template"; `at` empty: `endpoint.<path>`), an unsafe key or a non-object `given` too. Returns the merged endpoint and the
45
+ * editable paths `given` set (its leaves, for an audit that names paths, never values).
46
+ */
47
+ export function mergeEditableEndpoint(base, editable, given, at) {
48
+ const endpoint = structuredClone(isObj(base) ? base : {});
49
+ const root = at === "" ? "endpoint" : `${at}.endpoint`;
50
+ if (!isObj(given))
51
+ throw fail(root, "Expected an object");
52
+ const leaves = leafPaths(given);
53
+ for (const p of leaves) {
54
+ if (p.split(".").some((s) => UNSAFE_KEYS.has(s))) {
55
+ throw fail(`${root}.${p}`, "Invalid key");
56
+ }
57
+ if (!editable.some((e) => p === e || p.startsWith(`${e}.`))) {
58
+ throw fail(`${root}.${p}`, "This endpoint field is set by the template and cannot be changed");
59
+ }
60
+ }
61
+ for (const e of editable) {
62
+ const v = getPath(given, e);
63
+ if (v !== undefined)
64
+ setPath(endpoint, e, v);
65
+ }
66
+ return { endpoint, changed: leaves };
67
+ }
68
+ /**
69
+ * Endpoint fields whose change leaves requests going to the same place (top-level keys; their
70
+ * sub-paths too). Any other changed field may move the destination.
71
+ */
72
+ const SAME_DESTINATION_FIELDS = new Set(["headers"]);
73
+ /** JSON with object keys sorted at every level: equal values give equal text. */
74
+ function stableJson(v) {
75
+ if (Array.isArray(v))
76
+ return `[${v.map(stableJson).join(",")}]`;
77
+ if (isObj(v)) {
78
+ const keys = Object.keys(v).sort();
79
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableJson(v[k])}`).join(",")}}`;
80
+ }
81
+ return JSON.stringify(v) ?? "null";
82
+ }
83
+ /**
84
+ * Whether going from endpoint `before` to `after` may send requests somewhere else: any
85
+ * difference outside {@link SAME_DESTINATION_FIELDS} (a URL, a base URL, a region, a tenant host,
86
+ * a record whose keys hold dots, …), compared as whole values with those top-level keys left out.
87
+ * Credentials held for `before` are then never sent to `after`.
88
+ */
89
+ export function destinationChanged(before, after) {
90
+ const rest = (e) => Object.fromEntries(Object.entries(isObj(e) ? e : {}).filter(([k]) => !SAME_DESTINATION_FIELDS.has(k)));
91
+ return stableJson(rest(before)) !== stableJson(rest(after));
92
+ }
@@ -32,7 +32,7 @@ export declare class OAuthFlow {
32
32
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
33
33
  orgLock: Pick<OrgLock, "lockAndAuthorize">, redis: Pick<Redis, "set" | "getdel">, credentials: Credentials, config: Pick<KernelConfigService, "get">, log: Logger,
34
34
  /** A member's first connection without a tool snapshot refreshes the tools (A16). */
35
- connectors: Pick<ConnectorsService, "refresh">, txHost: TransactionHost);
35
+ connectors: Pick<ConnectorsService, "refresh" | "clientForConnect">, txHost: TransactionHost);
36
36
  /** 某成员首次成功连接、而连接器还没有工具快照时(A16:用该成员的 token 刷新工具清单)。 */
37
37
  private onFirstConnect;
38
38
  private app;
@@ -98,9 +98,10 @@ let OAuthFlow = class OAuthFlow {
98
98
  { path: "status", message: "The connector is disabled; ask an administrator to enable it" },
99
99
  ]);
100
100
  }
101
- const client = await this.credentials.oauthClient(orgId, connectorId);
101
+ // a dcr connector created without a client registers it now (once across replicas, R16)
102
+ const client = await this.connectors.clientForConnect(orgId, connectorId, accountId);
102
103
  if (!client?.authorizationEndpoint) {
103
- throw new ApiError("connector.connect_failed", "The connector has no registered OAuth client; ask an administrator to reinstall it");
104
+ throw new ApiError("connector.connect_failed", "This connector needs to be configured by an organization admin before members can connect it.");
104
105
  }
105
106
  const state = b64url();
106
107
  const verifier = b64url();
@@ -207,7 +207,11 @@ export const hookDeniedText = (plugin, reason) => `Tool call blocked by the "${p
207
207
  const invalidFormText = (key, problems) => `Tool ${key} returned an invalid input form: ${problems.join("; ")}.`;
208
208
  const stateTooLargeText = (key) => `Tool ${key} returned input state larger than ${MAX_INPUT_STATE_BYTES / 1024} KB.`;
209
209
  const personalMissingText = (connectorName) => `The user has not connected ${connectorName}. A connect card was shown; ask the user to connect, then retry.`;
210
- const orgMissingText = (connectorName) => `${connectorName} has no organization credential configured; ask an organization admin to set it up.`;
210
+ /**
211
+ * A connector lacking its org input (`needs_config`, plugin pages spec §5.2.1): `Credentials`
212
+ * throws an org `CredentialMissing` before any credential is presented, so the call never opens.
213
+ */
214
+ const ORG_MISSING_TEXT = "This connector needs to be configured by an organization admin before it can be used.";
211
215
  /** Optional provider: the pipeline's {@link ToolPipelineHooks} (tests). */
212
216
  export const TOOL_PIPELINE_HOOKS = Symbol("TOOL_PIPELINE_HOOKS");
213
217
  /** Review usage and hooks retain the same tree ancestry on both review routes. */
@@ -730,8 +734,11 @@ let ToolPipeline = class ToolPipeline {
730
734
  };
731
735
  const tool = resolved.tools.find((t) => t.key === call.name);
732
736
  if (!tool) {
737
+ // a hidden `<prefix>__*` ref covers every tool of that source (a disabled or needs_config
738
+ // connector), so a call of one of them gets the reason, not "unknown tool"
739
+ const covers = (ref) => ref === call.name || (ref.endsWith("__*") && call.name.startsWith(ref.slice(0, -1)));
733
740
  const why = resolved.unavailable.find((u) => u.ref === call.name) ??
734
- resolved.hidden?.find((u) => u.ref === call.name);
741
+ resolved.hidden?.find((u) => covers(u.ref));
735
742
  if (why)
736
743
  return fail(unavailableText(call.name, why.reason));
737
744
  let keys = resolved.tools.map((t) => t.key);
@@ -2477,15 +2484,17 @@ let ToolPipeline = class ToolPipeline {
2477
2484
  connectorSlug: app.slug,
2478
2485
  message: personalMissingText(app.name),
2479
2486
  }
2480
- : { kind: "error", message: orgMissingText(app.name) };
2481
- // 先取一次凭据:缺凭据在打开会话之前就确定,不依赖连接器把 CredentialMissing 原样抛出。
2487
+ : { kind: "error", message: ORG_MISSING_TEXT };
2488
+ // Read the credential once first: a missing one (or a needs_config connector) is settled before
2489
+ // any session opens, without relying on the connector to rethrow CredentialMissing.
2482
2490
  try {
2483
2491
  await getAuth();
2484
2492
  }
2485
2493
  catch (e) {
2486
2494
  if (e instanceof CredentialMissing)
2487
2495
  return missing(e);
2488
- // 取 token 时授权服务器暂时不可用(OAuth):给模型可执行的说明,不让整轮失败
2496
+ // the authorization server is briefly unavailable for the token (OAuth): an actionable
2497
+ // message for the model instead of failing the whole turn
2489
2498
  if (e instanceof ToolError)
2490
2499
  return { kind: "error", message: e.message };
2491
2500
  throw e;
@@ -12,6 +12,7 @@ import type { PersonFieldSpec } from "../platform/person-fields.js";
12
12
  import type { ConversationKindForHooks } from "../runtime/hook-calls.js";
13
13
  import type { ExecutionClaim } from "../runtime/run-execution.js";
14
14
  import { BuiltinTools } from "./builtins/builtin-tools.js";
15
+ import { Credentials } from "./credentials.js";
15
16
  import { OrgToolSwitches } from "./org-tool-switches.js";
16
17
  export { BUILTIN_TOOL_NAMES } from "./builtin-names.js";
17
18
  export { canonicalJson } from "./canonical-json.js";
@@ -347,8 +348,9 @@ export interface AgentTools {
347
348
  * the org (`extension_org_configs.enabled`; required bootstrap plugins and builtin plugins'
348
349
  * extensions are enabled in every org, `enabled.ts`), whose effective config for the org is valid (layering spec A §6) and that the
349
350
  * org did not switch off (§7: the org's switch wins);
350
- * - connector tools: every enabled tool of every live, active connector of the org whose
351
- * connector extension is installed, with a valid key.
351
+ * - connector tools: every enabled tool of every live, active, `ready` connector of the org
352
+ * (a `needs_config` one offers none, plugin pages spec §5.2.1) whose connector extension is
353
+ * installed, with a valid key.
352
354
  * What cannot be offered goes to `hidden` with the reason; nothing is reported to the model as
353
355
  * unavailable except two sources with one key (the first wins).
354
356
  */
@@ -366,6 +368,11 @@ export declare class ToolRegistry {
366
368
  private readonly effective;
367
369
  /** The org's switches of single extension tools (layering spec A §7). */
368
370
  private readonly switches;
371
+ /**
372
+ * The org inputs connectors need (plugin pages spec §5.2.1): a `needs_config` connector
373
+ * offers no tools.
374
+ */
375
+ private readonly credentials;
369
376
  /**
370
377
  * `tools.searchThreshold*` and the sub-agent limits. Absent (some tests): `ToolSearch` is never
371
378
  * offered and the sub-agent limits are the schema defaults.
@@ -383,6 +390,11 @@ export declare class ToolRegistry {
383
390
  effective: Pick<EffectiveConfigs, "get">,
384
391
  /** The org's switches of single extension tools (layering spec A §7). */
385
392
  switches: Pick<OrgToolSwitches, "offKeys">,
393
+ /**
394
+ * The org inputs connectors need (plugin pages spec §5.2.1): a `needs_config` connector
395
+ * offers no tools.
396
+ */
397
+ credentials: Pick<Credentials, "orgInputs">,
386
398
  /**
387
399
  * `tools.searchThreshold*` and the sub-agent limits. Absent (some tests): `ToolSearch` is never
388
400
  * offered and the sub-agent limits are the schema defaults.
@@ -24,6 +24,8 @@ import { AGENT_BUILTIN_NAMES, AGENT_TOOL, BASH_COMPANION_TOOLS, BUILTIN, SEND_ME
24
24
  import { agentToolSpec } from "./builtins/agent.js";
25
25
  import { BuiltinTools } from "./builtins/builtin-tools.js";
26
26
  import { canonicalJson } from "./canonical-json.js";
27
+ import { connectorSetups } from "./connector-setup.js";
28
+ import { Credentials } from "./credentials.js";
27
29
  import { toolKeyIssue } from "./naming.js";
28
30
  import { OrgToolSwitches, toolTurnedOffReason } from "./org-tool-switches.js";
29
31
  export { BUILTIN_TOOL_NAMES } from "./builtin-names.js";
@@ -98,8 +100,9 @@ const builtinTool = (b, spec) => ({
98
100
  * the org (`extension_org_configs.enabled`; required bootstrap plugins and builtin plugins'
99
101
  * extensions are enabled in every org, `enabled.ts`), whose effective config for the org is valid (layering spec A §6) and that the
100
102
  * org did not switch off (§7: the org's switch wins);
101
- * - connector tools: every enabled tool of every live, active connector of the org whose
102
- * connector extension is installed, with a valid key.
103
+ * - connector tools: every enabled tool of every live, active, `ready` connector of the org
104
+ * (a `needs_config` one offers none, plugin pages spec §5.2.1) whose connector extension is
105
+ * installed, with a valid key.
103
106
  * What cannot be offered goes to `hidden` with the reason; nothing is reported to the model as
104
107
  * unavailable except two sources with one key (the first wins).
105
108
  */
@@ -110,6 +113,7 @@ let ToolRegistry = class ToolRegistry {
110
113
  builtinTools;
111
114
  effective;
112
115
  switches;
116
+ credentials;
113
117
  config;
114
118
  constructor(db,
115
119
  /** Extension tools and the organization's enabled extensions. */
@@ -123,6 +127,11 @@ let ToolRegistry = class ToolRegistry {
123
127
  effective,
124
128
  /** The org's switches of single extension tools (layering spec A §7). */
125
129
  switches,
130
+ /**
131
+ * The org inputs connectors need (plugin pages spec §5.2.1): a `needs_config` connector
132
+ * offers no tools.
133
+ */
134
+ credentials,
126
135
  /**
127
136
  * `tools.searchThreshold*` and the sub-agent limits. Absent (some tests): `ToolSearch` is never
128
137
  * offered and the sub-agent limits are the schema defaults.
@@ -134,6 +143,7 @@ let ToolRegistry = class ToolRegistry {
134
143
  this.builtinTools = builtinTools;
135
144
  this.effective = effective;
136
145
  this.switches = switches;
146
+ this.credentials = credentials;
137
147
  this.config = config;
138
148
  }
139
149
  /** The kernel's builtin tools (`ToolSearch` is added by {@link forAgent}, not by definitions). */
@@ -458,8 +468,10 @@ let ToolRegistry = class ToolRegistry {
458
468
  });
459
469
  }
460
470
  }
461
- // connector tools: the org's live connectors
462
- for (const app of await this.loadOrgConnectors(orgId, { includeDeleted: false })) {
471
+ // connector tools: the org's live connectors, none from one that needs an org admin's input
472
+ const apps = await this.loadOrgConnectors(orgId, { includeDeleted: false });
473
+ const setups = await connectorSetups(this.credentials, orgId, apps);
474
+ for (const app of apps) {
463
475
  if (disabled.some((r) => r.kind === "connector" && r.connectorId === app.id && r.tools === "all")) {
464
476
  continue;
465
477
  }
@@ -468,6 +480,13 @@ let ToolRegistry = class ToolRegistry {
468
480
  hidden.push({ ref: all, reason: `App ${app.slug} is disabled` });
469
481
  continue;
470
482
  }
483
+ if (setups.get(app.id) !== "ready") {
484
+ hidden.push({
485
+ ref: all,
486
+ reason: `Connector ${app.slug} needs to be configured by an organization admin`,
487
+ });
488
+ continue;
489
+ }
471
490
  if (!this.findConnector(app.connector)) {
472
491
  hidden.push({
473
492
  ref: all,
@@ -536,7 +555,7 @@ let ToolRegistry = class ToolRegistry {
536
555
  async loadOrgConnectors(orgId, _opts) {
537
556
  const apps = await this.db
538
557
  .selectFrom("connectors")
539
- .select(["id", "slug", "connector", "status"])
558
+ .select(["id", "slug", "connector", "auth", "status"])
540
559
  .where("org_id", "=", orgId)
541
560
  .where("deleted_at", "is", null)
542
561
  .orderBy("slug")
@@ -563,6 +582,7 @@ let ToolRegistry = class ToolRegistry {
563
582
  id: a.id,
564
583
  slug: a.slug,
565
584
  connector: a.connector,
585
+ auth: a.auth,
566
586
  status: a.status,
567
587
  tools: toolRows
568
588
  .filter((t) => t.connector_id === a.id)
@@ -586,7 +606,8 @@ ToolRegistry = __decorate([
586
606
  __param(3, Inject(BuiltinTools)),
587
607
  __param(4, Inject(EffectiveConfigs)),
588
608
  __param(5, Inject(OrgToolSwitches)),
589
- __param(6, Inject(KernelConfigService))
609
+ __param(6, Inject(Credentials)),
610
+ __param(7, Inject(KernelConfigService))
590
611
  ], ToolRegistry);
591
612
  export { ToolRegistry };
592
613
  /**
@@ -40,6 +40,7 @@ import { ScheduleToolsPort, ScheduleUpdates } from "./builtins/schedules.js";
40
40
  import { WebPages } from "./builtins/web/page-cache.js";
41
41
  import { ConnectorAccountPolicies } from "./connector-account-policies.js";
42
42
  import { ConnectorContent } from "./connector-content.js";
43
+ import { ConnectorToolsQueueModule } from "./connector-tools-jobs.js";
43
44
  import { ConnectorsService } from "./connectors.service.js";
44
45
  import { CredentialsModule } from "./credentials.module.js";
45
46
  import { ToolDrift } from "./drift.js";
@@ -101,6 +102,9 @@ ToolsModule = __decorate([
101
102
  // the `Platform` tool's operations, actor facts and agent docs (imports no domain module)
102
103
  PlatformModule,
103
104
  QueueModule.registerQueue(MAINTENANCE_QUEUE_NAME),
105
+ // the connector tool listings owed after a create or a setup (consumer: the worker role's
106
+ // ConnectorToolsProcessor)
107
+ ConnectorToolsQueueModule,
104
108
  // a trial run's approvals become its scheduled task's grants (scheduled tasks spec §7)
105
109
  ScheduledTaskStoreModule,
106
110
  // connector credentials (also the git gateway's, without importing this module)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.84",
3
+ "version": "0.1.0-rc.85",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -75,7 +75,7 @@
75
75
  "@types/ws": "^8.18.2",
76
76
  "@types/yauzl": "3.4.0",
77
77
  "ws": "^8.22.0",
78
- "@capybara-hq/testing": "0.1.0-rc.38"
78
+ "@capybara-hq/testing": "0.1.0-rc.39"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -b"
@@ -0,0 +1,5 @@
1
+ -- Plugin pages spec §5.2.1 (ruling R17): the kernel creates template connectors as no person (a
2
+ -- plugin scope sync, the startup reconciliation), so such a connector has no creator. Relaxing NOT
3
+ -- NULL is expand-only: rows written before keep their creator, and dropping NOT NULL on a nullable
4
+ -- column is a no-op.
5
+ ALTER TABLE connectors ALTER COLUMN created_by DROP NOT NULL;