@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
@@ -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
+ }
@@ -64,6 +64,14 @@ export interface DeviceAskFacts {
64
64
  * `addNetworkHostsIn` accepts), so an offered decision does not fail for that.
65
65
  */
66
66
  export declare function deviceAskTerms(f: DeviceAskFacts): Required<Pick<NetworkPlanContext, "refusal" | "offer" | "onList" | "deviceBlocks">>;
67
+ /**
68
+ * The ask terms for a device service's refusals (browser use spec §7.1): a long-lived service is
69
+ * reached only through the device's own list, never a per-exec run grant, so a host is offered
70
+ * only `always` and refused when the list cannot take it (`listAddRefusal`: beyond the org's or
71
+ * platform's hosts, or a device with no list of its own); a host the list already holds waits for
72
+ * it to apply ({@link deviceAskTerms}' `onList`).
73
+ */
74
+ export declare function serviceAskTerms(f: DeviceAskFacts): Required<Pick<NetworkPlanContext, "refusal" | "offer" | "onList" | "deviceBlocks">>;
67
75
  /** Asked, allowed this time (a run grant: "once"). */
68
76
  export declare const allowedOnceNote: (hosts: readonly string[]) => string;
69
77
  /**
@@ -71,6 +79,11 @@ export declare const allowedOnceNote: (hosts: readonly string[]) => string;
71
79
  * apply at `appliesAt`, never to the command that asked, which is not run again.
72
80
  */
73
81
  export declare const addedToDeviceNote: (hosts: readonly string[], appliesAt: NetworkAppliesAt) => string;
82
+ /**
83
+ * Not asked: a device service's call that already asked once (it ran again after the person added
84
+ * hosts to the device's list, browser use spec §7.1) was refused more hosts; one ask per call.
85
+ */
86
+ export declare const serviceAskedNote: (hosts: readonly string[]) => string;
74
87
  /**
75
88
  * Not asked: the device's network settings already allow the host (its own list, added by an
76
89
  * earlier answer or on the device page, or the org's hosts it follows), but its sandbox has not
@@ -3,7 +3,7 @@ import { NETWORK_ASK_MAX_HOSTS, NETWORK_HOST_MAX_CHARS } from "../conversations/
3
3
  import { coversHost } from "../sandbox/modes.js";
4
4
  import { ESCALATION_UNATTENDED_WHY } from "../sandbox/review/permission-candidate.js";
5
5
  import { networkGrantKey, unattendedFails, unattendedRules, } from "../schedules/unattended.js";
6
- import { NETWORK_ASK_CANCELLED_NOTE, } from "./approvals.service.js";
6
+ import { NETWORK_ASK_CANCELLED_NOTE, networkAskHosts, } from "./approvals.service.js";
7
7
  /**
8
8
  * Network asks in the tool pipeline (network ask-to-allow spec §6.2, §6.6–§6.9, §8.3): what a
9
9
  * command's reported refusals turn into (an ask to the device owner, or notes written at once) and
@@ -84,6 +84,25 @@ export function deviceAskTerms(f) {
84
84
  offer: (hosts) => networkAskOffer({ perOperationHosts }, f.limitsApplyAt, f.ownList && hosts.length > 0 && hosts.every((h) => f.listAddRefusal(h) === null)),
85
85
  };
86
86
  }
87
+ /**
88
+ * The ask terms for a device service's refusals (browser use spec §7.1): a long-lived service is
89
+ * reached only through the device's own list, never a per-exec run grant, so a host is offered
90
+ * only `always` and refused when the list cannot take it (`listAddRefusal`: beyond the org's or
91
+ * platform's hosts, or a device with no list of its own); a host the list already holds waits for
92
+ * it to apply ({@link deviceAskTerms}' `onList`).
93
+ */
94
+ export function serviceAskTerms(f) {
95
+ const terms = deviceAskTerms(f);
96
+ return {
97
+ refusal: f.listAddRefusal,
98
+ onList: terms.onList,
99
+ deviceBlocks: () => false,
100
+ offer: (hosts) => {
101
+ const o = terms.offer(hosts);
102
+ return o?.scopes.includes("always") ? { scopes: ["always"], appliesAt: o.appliesAt } : null;
103
+ },
104
+ };
105
+ }
87
106
  /** When a host added to the device's list applies, as the model reads it. */
88
107
  const APPLIES_TEXT = {
89
108
  "next-command": "from the next command",
@@ -97,6 +116,11 @@ export const allowedOnceNote = (hosts) => `${blockedLead(hosts)} The user allowe
97
116
  * apply at `appliesAt`, never to the command that asked, which is not run again.
98
117
  */
99
118
  export const addedToDeviceNote = (hosts, appliesAt) => `${blockedLead(hosts)} The person added ${list(hosts)} to this device's network list; it applies ${APPLIES_TEXT[appliesAt]}. This command is not run again.`;
119
+ /**
120
+ * Not asked: a device service's call that already asked once (it ran again after the person added
121
+ * hosts to the device's list, browser use spec §7.1) was refused more hosts; one ask per call.
122
+ */
123
+ export const serviceAskedNote = (hosts) => `${blockedLead(hosts)} This call already asked for network access once; call the tool again to ask for ${pron(hosts)}.`;
100
124
  /**
101
125
  * Not asked: the device's network settings already allow the host (its own list, added by an
102
126
  * earlier answer or on the device page, or the org's hosts it follows), but its sandbox has not
@@ -319,7 +343,7 @@ const NO_OFFER_WHY = "the device's owner changes the device's network on its pag
319
343
  * wait (created to expiry). Null while it is pending.
320
344
  */
321
345
  export function settledNetworkNotes(a, hours) {
322
- const asked = (a.detail?.hosts ?? []).map((h) => h.host);
346
+ const asked = a.detail === null ? [] : networkAskHosts(a.detail);
323
347
  switch (a.status) {
324
348
  case "approved": {
325
349
  const granted = a.detail?.grantedHosts ?? asked;
@@ -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();
@@ -2,6 +2,7 @@ import { type ConversationSource, type FormAnswer, type InputForm, type Logger }
2
2
  import type { AgentDefinition } from "../agents/definition.js";
3
3
  import { ConversationApprovalProfile } from "../conversations/approval-profile.js";
4
4
  import { EventLog } from "../conversations/event-log.js";
5
+ import { type ReviewRecord } from "../conversations/events.js";
5
6
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
7
  import { ConversationDevices } from "../devices/conversation-devices.js";
7
8
  import { EffectiveConfigs } from "../extensions/effective-config.js";
@@ -340,22 +341,42 @@ export type ToolResume = {
340
341
  answer: FormAnswer | null;
341
342
  };
342
343
  /** 执行阶段的结果。 */
344
+ /**
345
+ * Hosts a device service reported refused during a handler's call (the call scope, browser use
346
+ * spec §7.1): the pipeline asks the device owner about them after the call.
347
+ */
348
+ export interface ServiceBlocked {
349
+ /** The device the call's `ctx.deviceAccess` calls resolved; null: the conversation's device. */
350
+ deviceId: string | null;
351
+ hosts: string[];
352
+ /** The page the refusals came from, when the service said. */
353
+ url: string | null;
354
+ }
343
355
  export type ExecOutcome =
344
356
  /** 工具返回了结果(可能是工具自己报告的错误,或畸形结果,由渲染阶段处理)。 */
345
357
  {
346
358
  kind: "result";
347
359
  result: unknown;
360
+ blocked?: ServiceBlocked;
361
+ review?: ReviewRecord;
348
362
  }
349
- /** 处理函数需要用户输入(表单尚未校验)。 */
363
+ /**
364
+ * The handler needs the user's input (the form is not validated yet). `review` and `blocked`:
365
+ * what the round collected before it asked ({@link withBlocked}), kept for the call's result.
366
+ */
350
367
  | {
351
368
  kind: "input_required";
352
369
  form: InputForm;
353
370
  state: unknown;
371
+ blocked?: ServiceBlocked;
372
+ review?: ReviewRecord;
354
373
  }
355
374
  /** 执行失败(超时、抛错、熔断、中止等),message 给模型看。 */
356
375
  | {
357
376
  kind: "error";
358
377
  message: string;
378
+ blocked?: ServiceBlocked;
379
+ review?: ReviewRecord;
359
380
  }
360
381
  /** 发起人未连接个人凭据:除错误结果外再写 `connection_required`。 */
361
382
  | {
@@ -522,6 +543,14 @@ export declare class ToolPipeline {
522
543
  * settles (P-D2).
523
544
  */
524
545
  private networkBlocked;
546
+ /**
547
+ * A device service's report (the call scope, browser use spec §7.1) on the device the call's
548
+ * conversation works in (the root conversation's for a sub-agent, as the sandbox tools resolve
549
+ * it): a report that names no device is about that one; a report naming another device id (the
550
+ * conversation moved to another device during the call) is ignored with a warning, never asked
551
+ * about.
552
+ */
553
+ private ownDeviceReport;
525
554
  /** Appends a sub-agent's connect card to its root conversation ({@link rootSurfaceOf}). */
526
555
  private surfaceConnectInRoot;
527
556
  /**