@capybara-hq/kernel 0.1.0-rc.122 → 0.1.0-rc.124

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/admin.controller.d.ts +2 -2
  3. package/dist/admin/admin.controller.js +1 -1
  4. package/dist/admin/health.service.js +5 -5
  5. package/dist/admin/overview.service.d.ts +2 -2
  6. package/dist/admin/overview.service.js +1 -1
  7. package/dist/agents/agents.module.js +4 -0
  8. package/dist/agents/agents.schemas.js +1 -0
  9. package/dist/agents/models.controller.d.ts +2 -2
  10. package/dist/agents/onboarding-checklist.d.ts +30 -0
  11. package/dist/agents/onboarding-checklist.js +176 -0
  12. package/dist/agents/readiness.controller.d.ts +1 -0
  13. package/dist/agents/readiness.controller.js +12 -2
  14. package/dist/agents/readiness.service.d.ts +5 -2
  15. package/dist/agents/readiness.service.js +14 -3
  16. package/dist/automations/automations.service.js +7 -21
  17. package/dist/automations/events/acceptance.d.ts +2 -0
  18. package/dist/automations/events/acceptance.js +14 -3
  19. package/dist/automations/events/sweep.job.d.ts +3 -36
  20. package/dist/automations/events/sweep.job.js +5 -127
  21. package/dist/automations/fire.d.ts +3 -0
  22. package/dist/automations/fire.js +18 -1
  23. package/dist/automations/grant-rules.d.ts +0 -14
  24. package/dist/automations/grant-rules.js +0 -18
  25. package/dist/automations/scan.job.js +22 -16
  26. package/dist/catalog/catalog.module.d.ts +4 -7
  27. package/dist/catalog/catalog.module.js +4 -10
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/plugin-import.js +2 -1
  30. package/dist/catalog/plugin-install.d.ts +2 -2
  31. package/dist/catalog/plugin-install.js +2 -2
  32. package/dist/catalog/template-connector-ensure.d.ts +4 -7
  33. package/dist/catalog/template-connector-ensure.js +11 -15
  34. package/dist/channels/supervisor.js +34 -23
  35. package/dist/channels/webhook.d.ts +1 -0
  36. package/dist/channels/webhook.js +10 -5
  37. package/dist/conversations/job-org.d.ts +2 -0
  38. package/dist/conversations/job-org.js +12 -0
  39. package/dist/ctx/create-ctx.js +2 -1
  40. package/dist/db/kernel-schema.d.ts +1 -0
  41. package/dist/dial-in/auth.controller.js +3 -2
  42. package/dist/dial-in/auth.service.js +3 -2
  43. package/dist/dial-in/gateway.d.ts +0 -1
  44. package/dist/dial-in/gateway.js +6 -9
  45. package/dist/extensions/host.d.ts +2 -2
  46. package/dist/extensions/host.js +22 -13
  47. package/dist/extensions/installs.d.ts +1 -0
  48. package/dist/extensions/installs.js +2 -0
  49. package/dist/html/html-document.controller.js +3 -0
  50. package/dist/html/html-document.service.js +2 -0
  51. package/dist/http/plugin-route-access.js +7 -2
  52. package/dist/identity/account-avatar.controller.js +4 -2
  53. package/dist/identity/accounts.js +19 -32
  54. package/dist/identity/api-tokens.d.ts +2 -0
  55. package/dist/identity/api-tokens.js +14 -10
  56. package/dist/identity/audit.js +10 -5
  57. package/dist/identity/binding.d.ts +1 -1
  58. package/dist/identity/binding.js +19 -10
  59. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -8
  60. package/dist/lifecycle/kernel-lifecycle.js +11 -37
  61. package/dist/models/purposes.d.ts +24 -3
  62. package/dist/models/purposes.js +131 -14
  63. package/dist/orgs/directory-sync.js +6 -4
  64. package/dist/orgs/roles.d.ts +1 -1
  65. package/dist/orgs/roles.js +1 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +1 -1
  68. package/dist/platform/ops/agents.ops.js +1 -1
  69. package/dist/platform/ops/models.ops.js +3 -3
  70. package/dist/push/fanout.d.ts +1 -0
  71. package/dist/push/fanout.js +11 -4
  72. package/dist/push/recipients.d.ts +3 -1
  73. package/dist/push/recipients.js +29 -22
  74. package/dist/runtime/maintenance.d.ts +5 -1
  75. package/dist/runtime/maintenance.js +50 -11
  76. package/dist/runtime/providers.d.ts +12 -9
  77. package/dist/runtime/providers.js +2 -23
  78. package/dist/runtime/run-orphan-check.job.d.ts +1 -0
  79. package/dist/runtime/run-orphan-check.job.js +23 -21
  80. package/dist/runtime/usage-report.d.ts +2 -1
  81. package/dist/runtime/usage-report.js +26 -4
  82. package/dist/sandbox/providers.d.ts +2 -0
  83. package/dist/sandbox/providers.js +2 -0
  84. package/dist/shares/liveness.d.ts +3 -2
  85. package/dist/shares/liveness.js +26 -11
  86. package/dist/shares/share-open.service.js +2 -0
  87. package/dist/skills/usable.d.ts +2 -0
  88. package/dist/skills/usable.js +56 -0
  89. package/dist/tools/builtins/platform.js +17 -12
  90. package/dist/tools/connector-setup.d.ts +5 -1
  91. package/dist/tools/connector-setup.js +14 -0
  92. package/dist/tools/credentials.d.ts +5 -0
  93. package/dist/tools/credentials.js +10 -0
  94. package/dist/tools/oauth/flow.d.ts +1 -0
  95. package/dist/tools/oauth/flow.js +8 -3
  96. package/dist/tools/registry.d.ts +2 -0
  97. package/dist/tools/registry.js +6 -0
  98. package/package.json +3 -3
  99. package/src/migrations/0209_onboarding_checklist.sql +5 -0
  100. package/dist/catalog/template-connector-reconcile.d.ts +0 -44
  101. package/dist/catalog/template-connector-reconcile.js +0 -114
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.96";
211
+ readonly sdk: "0.1.0-rc.97";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -1190,7 +1190,8 @@ let PluginImport = class PluginImport {
1190
1190
  const total = await this.cleanupStagingRows();
1191
1191
  // display files no version or staging lists (an abandoned import's), older than a staging
1192
1192
  try {
1193
- await sweepDisplayFiles(this.db, PLUGIN_STAGING_TTL_MS);
1193
+ // org-filter: deployment-wide display files can be retained by staging in any org.
1194
+ await asPlatform("collect display files unused by any version or staging row", () => sweepDisplayFiles(this.db, PLUGIN_STAGING_TTL_MS));
1194
1195
  }
1195
1196
  catch (err) {
1196
1197
  this.log.warn("cannot sweep unused catalog display files", { err });
@@ -573,8 +573,8 @@ export declare class PluginInstaller {
573
573
  * connector from the template yet (one a switch-off kept is reused, left as it is). Created like
574
574
  * an install's ({@link planConnector}, `createDeferredIn`: no outbound call, `needs_config` when
575
575
  * it needs an org credential or OAuth client) and recorded on the install. Returns its id, or
576
- * undefined when none was created. `actor` null: the kernel itself (the startup reconciliation,
577
- * `TemplateConnectorReconciler`), which checks the template is on and holds the org lock.
576
+ * undefined when none was created. `actor` null: the kernel itself (`TemplateConnectorEnsurer`),
577
+ * which checks the template is on and holds the org lock.
578
578
  */
579
579
  createSwitchedOnTemplateConnectorIn(orgId: string, actor: string | null, platformTemplateId: string, opts?: {
580
580
  actorTokenId?: string;
@@ -1736,8 +1736,8 @@ let PluginInstaller = class PluginInstaller {
1736
1736
  * connector from the template yet (one a switch-off kept is reused, left as it is). Created like
1737
1737
  * an install's ({@link planConnector}, `createDeferredIn`: no outbound call, `needs_config` when
1738
1738
  * it needs an org credential or OAuth client) and recorded on the install. Returns its id, or
1739
- * undefined when none was created. `actor` null: the kernel itself (the startup reconciliation,
1740
- * `TemplateConnectorReconciler`), which checks the template is on and holds the org lock.
1739
+ * undefined when none was created. `actor` null: the kernel itself (`TemplateConnectorEnsurer`),
1740
+ * which checks the template is on and holds the org lock.
1741
1741
  */
1742
1742
  async createSwitchedOnTemplateConnectorIn(orgId, actor, platformTemplateId, opts = {}) {
1743
1743
  const row = await this.db
@@ -29,13 +29,12 @@ export interface EnsureResult {
29
29
  * `createDeferredIn`, no outbound call, `needs_config` when it needs an org credential or OAuth
30
30
  * client, recorded on the install). The create re-checks that the connector kind is available
31
31
  * in the org. A refusal (an `ApiError` from those checks) is logged and skipped. Any other error
32
- * is thrown: the caller's job retries, or the startup pass stops without its mark. A template
33
- * whose connector extension is not loaded on this replica is counted in `notLoaded` and not
34
- * attempted: the queued ensure retries until it loads.
32
+ * is thrown so the caller can retry. A template whose connector extension is still loading is
33
+ * counted in `notLoaded` and skipped. The queued ensure retries it.
35
34
  *
36
35
  * Callers: the `template-connectors-ensure` job (owed by an install's commit and by an org
37
- * switching an extension on), the plugin scope sync after it added a plugin's dependencies, and
38
- * the one-off startup reconciliation (`TemplateConnectorReconciler`).
36
+ * switching an extension on), the plugin scope sync after it adds a plugin's dependencies, and
37
+ * the cursor-based sweep.
39
38
  */
40
39
  export declare class TemplateConnectorEnsurer {
41
40
  private readonly kdb;
@@ -53,8 +52,6 @@ export declare class TemplateConnectorEnsurer {
53
52
  /** The refusals already warned about (a lease per org and template). */
54
53
  locks: Pick<LockService, "lease">, txHost: TransactionHost);
55
54
  private get db();
56
- /** The live orgs with at least one template connector they never had (the startup pass). */
57
- orgsMissing(): Promise<string[]>;
58
55
  /**
59
56
  * The backstop sweep (ruling R30, `CatalogJobs.sweepTemplateConnectors`): runs
60
57
  * {@link ensureTemplateConnectorsIn} for at most `limit` orgs that have a template connector
@@ -11,6 +11,7 @@ import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { ApiError } from "../errors.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
14
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
15
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
16
17
  import { LockService } from "../infra/lock/lock.service.js";
@@ -35,13 +36,12 @@ import { PluginInstaller } from "./plugin-install.js";
35
36
  * `createDeferredIn`, no outbound call, `needs_config` when it needs an org credential or OAuth
36
37
  * client, recorded on the install). The create re-checks that the connector kind is available
37
38
  * in the org. A refusal (an `ApiError` from those checks) is logged and skipped. Any other error
38
- * is thrown: the caller's job retries, or the startup pass stops without its mark. A template
39
- * whose connector extension is not loaded on this replica is counted in `notLoaded` and not
40
- * attempted: the queued ensure retries until it loads.
39
+ * is thrown so the caller can retry. A template whose connector extension is still loading is
40
+ * counted in `notLoaded` and skipped. The queued ensure retries it.
41
41
  *
42
42
  * Callers: the `template-connectors-ensure` job (owed by an install's commit and by an org
43
- * switching an extension on), the plugin scope sync after it added a plugin's dependencies, and
44
- * the one-off startup reconciliation (`TemplateConnectorReconciler`).
43
+ * switching an extension on), the plugin scope sync after it adds a plugin's dependencies, and
44
+ * the cursor-based sweep.
45
45
  */
46
46
  let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
47
47
  kdb;
@@ -67,11 +67,6 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
67
67
  get db() {
68
68
  return this.kdb.db;
69
69
  }
70
- /** The live orgs with at least one template connector they never had (the startup pass). */
71
- async orgsMissing() {
72
- const rows = await this.missingQuery(undefined, undefined).execute();
73
- return [...new Set(rows.map((r) => r.org_id))];
74
- }
75
70
  /**
76
71
  * The backstop sweep (ruling R30, `CatalogJobs.sweepTemplateConnectors`): runs
77
72
  * {@link ensureTemplateConnectorsIn} for at most `limit` orgs that have a template connector
@@ -91,7 +86,8 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
91
86
  const loaded = new Set(this.installer.loadedConnectors().map((c) => c.plugin));
92
87
  if (loaded.size === 0)
93
88
  return { orgs: 0, created: 0 };
94
- const rows = await this.missingQuery(undefined, undefined)
89
+ // org-filter: deployment-wide sweep of candidate installs, before checking each org's kinds.
90
+ const rows = await asPlatform("find template connector sweep candidates", () => this.missingQuery(undefined, undefined)
95
91
  .where(sql `t.file->'template'->>'plugin'`, "in", [...loaded])
96
92
  .where("t.disabled", "=", false)
97
93
  .where(({ not, exists, selectFrom }) => not(exists(selectFrom("component_org_switches as s")
@@ -109,7 +105,7 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
109
105
  .whereRef("s.org_id", "=", "a.org_id")
110
106
  .where("s.enabled", "=", true)),
111
107
  ]))
112
- .execute();
108
+ .execute());
113
109
  const kindsByOrg = new Map();
114
110
  for (const r of rows) {
115
111
  const t = r.file.template;
@@ -130,7 +126,7 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
130
126
  if (orgs.length >= opts.limit)
131
127
  break;
132
128
  opts.signal?.throwIfAborted();
133
- const available = await this.connectors.kinds(orgId);
129
+ const available = await withOrgScope(orgId, () => this.connectors.kinds(orgId));
134
130
  if (wanted.some((w) => available.some((k) => k.kind === w.connector && k.plugin === w.plugin)))
135
131
  orgs.push(orgId);
136
132
  }
@@ -146,10 +142,10 @@ let TemplateConnectorEnsurer = class TemplateConnectorEnsurer {
146
142
  let created = 0;
147
143
  for (const orgId of orgs) {
148
144
  opts.signal?.throwIfAborted();
149
- const r = await this.ensureTemplateConnectorsIn(orgId, undefined, {
145
+ const r = await withOrgScope(orgId, () => this.ensureTemplateConnectorsIn(orgId, undefined, {
150
146
  ...(opts.signal !== undefined && { signal: opts.signal }),
151
147
  via: "sweep",
152
- });
148
+ }));
153
149
  created += r.created;
154
150
  }
155
151
  return { orgs: orgs.length, created };
@@ -16,6 +16,7 @@ import { ExtensionRegistry } from "../extensions/registry.js";
16
16
  import { ReplicaStatusStore } from "../extensions/sources.js";
17
17
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
18
18
  import { KernelDb } from "../infra/database/kernel-db.js";
19
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
19
20
  import { LockService } from "../infra/lock/lock.service.js";
20
21
  import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
21
22
  import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
@@ -263,7 +264,7 @@ let ChannelSupervisor = class ChannelSupervisor {
263
264
  // watchdog's to log and judge (lost at the renewal deadline)
264
265
  const ok = await h.lease.renew().catch(() => undefined);
265
266
  if (ok === true)
266
- await this.afterRenew(id, h, ttl);
267
+ await withOrgScope(h.orgId, () => this.afterRenew(id, h, ttl));
267
268
  // false: the key is gone or taken, or the lease was already lost (`drop` is idempotent)
268
269
  else if (ok === false)
269
270
  this.drop(id, h);
@@ -372,21 +373,31 @@ let ChannelSupervisor = class ChannelSupervisor {
372
373
  * 可以持有的连接:active、未删除、所属组织未删除、插件在该组织启用(组织停用插件 / 删除组织时持有方据此断开),
373
374
  * 且插件在本进程已加载——滚动升级期间还没有该插件的副本根本不考虑它(不取租约、不记失败),留给有插件的副本。
374
375
  */
375
- runnable(plugins) {
376
+ runnable(plugins, ids) {
376
377
  const db = this.db.db;
377
- return (db
378
- .selectFrom("channel_connections")
379
- .innerJoin("orgs", "orgs.id", "channel_connections.org_id")
380
- .innerJoin(enabledExtensionsByOrg(db).as("en"), (j) => j
381
- .onRef("en.plugin", "=", "channel_connections.plugin")
382
- .onRef("en.org_id", "=", "channel_connections.org_id"))
383
- .select(["channel_connections.id", "channel_connections.plugin"])
384
- .where("channel_connections.status", "=", "active")
385
- // Webhook-mode connections get callbacks on the gateway route instead (F9)
386
- .where("channel_connections.inbound_mode", "=", "long_connection")
387
- .where("channel_connections.deleted_at", "is", null)
388
- .where("orgs.deleted_at", "is", null)
389
- .where("channel_connections.plugin", "in", plugins));
378
+ // org-filter: deployment-wide scan for active long connections served by this gateway
379
+ return asPlatform("list runnable channel connections across orgs", () => {
380
+ let query = db
381
+ .selectFrom("channel_connections")
382
+ .innerJoin("orgs", "orgs.id", "channel_connections.org_id")
383
+ .innerJoin(enabledExtensionsByOrg(db).as("en"), (j) => j
384
+ .onRef("en.plugin", "=", "channel_connections.plugin")
385
+ .onRef("en.org_id", "=", "channel_connections.org_id"))
386
+ .select([
387
+ "channel_connections.id",
388
+ "channel_connections.org_id",
389
+ "channel_connections.plugin",
390
+ ])
391
+ .where("channel_connections.status", "=", "active")
392
+ // Webhook-mode connections get callbacks on the gateway route instead (F9)
393
+ .where("channel_connections.inbound_mode", "=", "long_connection")
394
+ .where("channel_connections.deleted_at", "is", null)
395
+ .where("orgs.deleted_at", "is", null)
396
+ .where("channel_connections.plugin", "in", plugins);
397
+ if (ids)
398
+ query = query.where("channel_connections.id", "in", ids);
399
+ return query.execute();
400
+ });
390
401
  }
391
402
  /**
392
403
  * 持有的连接仍须可持有(bus 广播是尽力而为,这里兜底)。交还不等待:交还要等插件 `connect` 返回(至多 SETTLE_MS),
@@ -397,9 +408,7 @@ let ChannelSupervisor = class ChannelSupervisor {
397
408
  if (ids.length === 0)
398
409
  return;
399
410
  const plugins = this.localPlugins();
400
- const live = new Set(plugins.length === 0
401
- ? []
402
- : (await this.runnable(plugins).where("channel_connections.id", "in", ids).execute()).map((r) => r.id));
411
+ const live = new Set(plugins.length === 0 ? [] : (await this.runnable(plugins, ids)).map((r) => r.id));
403
412
  for (const id of ids) {
404
413
  const h = this.held.get(id);
405
414
  if (h && !live.has(id))
@@ -418,7 +427,7 @@ let ChannelSupervisor = class ChannelSupervisor {
418
427
  const plugins = this.localPlugins();
419
428
  if (plugins.length === 0)
420
429
  return;
421
- const rows = await this.runnable(plugins).execute();
430
+ const rows = await this.runnable(plugins);
422
431
  const runnable = new Map();
423
432
  for (const r of rows)
424
433
  runnable.set(r.plugin, (runnable.get(r.plugin) ?? 0) + 1);
@@ -431,7 +440,7 @@ let ChannelSupervisor = class ChannelSupervisor {
431
440
  if (held >= target)
432
441
  full.add(p);
433
442
  }
434
- for (const { id, plugin } of rows) {
443
+ for (const { id, plugin, org_id: orgId } of rows) {
435
444
  if (this.stopped)
436
445
  return;
437
446
  if (full.has(plugin))
@@ -454,7 +463,7 @@ let ChannelSupervisor = class ChannelSupervisor {
454
463
  await lease.release();
455
464
  return;
456
465
  }
457
- await this.connect(id, lease);
466
+ await withOrgScope(orgId, () => this.connect(id, lease));
458
467
  }
459
468
  }
460
469
  /** 已取得租约:读配置并在后台跑插件的 `connect`。 */
@@ -483,6 +492,7 @@ let ChannelSupervisor = class ChannelSupervisor {
483
492
  const abort = new AbortController();
484
493
  const now = Date.now();
485
494
  const h = {
495
+ orgId: rt.row.orgId,
486
496
  plugin: rt.row.plugin,
487
497
  lease,
488
498
  abort,
@@ -714,7 +724,8 @@ export async function checkGatewayPresence(deps) {
714
724
  return false;
715
725
  // Webhook-mode connections count too (Ruling R4): the webhook route is served only by gateway
716
726
  // replicas, so without one their callbacks get no answer either
717
- const rows = await deps.db
727
+ // org-filter: deployment-wide count of active connections requiring a gateway
728
+ const rows = await asPlatform("count connections needing a gateway across orgs", () => deps.db
718
729
  .selectFrom("channel_connections")
719
730
  .innerJoin("orgs", "orgs.id", "channel_connections.org_id")
720
731
  .innerJoin(enabledExtensionsByOrg(deps.db).as("en"), (j) => j
@@ -725,7 +736,7 @@ export async function checkGatewayPresence(deps) {
725
736
  .where("channel_connections.deleted_at", "is", null)
726
737
  .where("orgs.deleted_at", "is", null)
727
738
  .groupBy("channel_connections.plugin")
728
- .execute();
739
+ .execute());
729
740
  const counts = new Map(rows.map((r) => [r.plugin, Number(r.n)]));
730
741
  const plugins = [...counts.keys()].filter((p) => (counts.get(p) ?? 0) > 0).sort();
731
742
  if (plugins.length === 0)
@@ -96,4 +96,5 @@ export declare class ChannelWebhooks {
96
96
  private runtime;
97
97
  private respond;
98
98
  private respondBefore;
99
+ private handleInOrg;
99
100
  }
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { ApiError, errorBody } from "../errors.js";
12
12
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
13
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
13
14
  import { LockService } from "../infra/lock/lock.service.js";
14
15
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
15
16
  import { ChannelConnections } from "./connections.service.js";
@@ -168,11 +169,11 @@ let ChannelWebhooks = class ChannelWebhooks {
168
169
  this.log.warn("cannot record the channel webhook marker", { connectionId, err });
169
170
  }
170
171
  }
171
- async runtime(connectionId, deadline) {
172
+ async runtime(connectionId, orgId, deadline) {
172
173
  const ttl = this.runtimeCacheMs;
173
174
  const now = Date.now();
174
175
  const hit = this.runtimes.get(connectionId);
175
- if (hit && hit.expiresAt > now)
176
+ if (hit?.orgId === orgId && hit.expiresAt > now)
176
177
  return hit.value;
177
178
  const generation = this.generation;
178
179
  const value = await raceAbort(this.connections.runtime(connectionId), deadline);
@@ -185,7 +186,7 @@ let ChannelWebhooks = class ChannelWebhooks {
185
186
  break;
186
187
  this.runtimes.delete(oldest);
187
188
  }
188
- this.runtimes.set(connectionId, { value, expiresAt: now + ttl });
189
+ this.runtimes.set(connectionId, { orgId, value, expiresAt: now + ttl });
189
190
  }
190
191
  return value;
191
192
  }
@@ -206,7 +207,8 @@ let ChannelWebhooks = class ChannelWebhooks {
206
207
  }
207
208
  }
208
209
  async respondBefore(connectionId, request, deadline) {
209
- const row = await raceAbort(this.connections.row(connectionId), deadline);
210
+ // org-filter: deployment-wide lookup of the connection addressed by an incoming webhook
211
+ const row = await asPlatform("identify the connection receiving a channel webhook", () => raceAbort(this.connections.row(connectionId), deadline));
210
212
  if (row === undefined ||
211
213
  row.inboundMode !== "webhook" ||
212
214
  row.status !== "active" ||
@@ -214,9 +216,12 @@ let ChannelWebhooks = class ChannelWebhooks {
214
216
  this.invalidate(connectionId);
215
217
  return notFound();
216
218
  }
219
+ return withOrgScope(row.orgId, () => this.handleInOrg(connectionId, row.orgId, request, deadline));
220
+ }
221
+ async handleInOrg(connectionId, orgId, request, deadline) {
217
222
  let runtime;
218
223
  try {
219
- runtime = await this.runtime(connectionId, deadline);
224
+ runtime = await this.runtime(connectionId, orgId, deadline);
220
225
  }
221
226
  catch (err) {
222
227
  if (err instanceof WebhookDeadline)
@@ -1,3 +1,5 @@
1
1
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
2
  /** Looks up the owning org before a worker processes a conversation job. */
3
3
  export declare function resolveConversationOrg(db: KernelSchemaDb, conversationId: string): Promise<string | undefined>;
4
+ /** A run backstop may carry just its run id. When both ids are present they must agree. */
5
+ export declare function resolveRunOrg(db: KernelSchemaDb, runId: string, conversationId?: string): Promise<string | undefined>;
@@ -9,3 +9,15 @@ export async function resolveConversationOrg(db, conversationId) {
9
9
  .executeTakeFirst());
10
10
  return row?.org_id;
11
11
  }
12
+ /** A run backstop may carry just its run id. When both ids are present they must agree. */
13
+ export async function resolveRunOrg(db, runId, conversationId) {
14
+ // org-filter: deployment-wide lookup of the conversation owner of a queued run id
15
+ const row = await asPlatform("resolve the org of a queued run", () => db
16
+ .selectFrom("runs as r")
17
+ .innerJoin("conversations as c", "c.id", "r.conversation_id")
18
+ .select("c.org_id")
19
+ .where("r.id", "=", runId)
20
+ .$if(conversationId !== undefined, (q) => q.where("c.id", "=", conversationId))
21
+ .executeTakeFirst());
22
+ return row?.org_id;
23
+ }
@@ -619,7 +619,8 @@ identity = { sha256: null }) {
619
619
  // current role still meets the slot's minRole (a demoted caller's token stops working)
620
620
  if (slot === undefined || slot.id === "platform.page")
621
621
  return null;
622
- const role = await currentOrgRole(deps.db, name, claims.orgId, claims.accountId);
622
+ const { orgId, accountId } = claims;
623
+ const role = await withOrgScope(orgId, () => currentOrgRole(deps.db, name, orgId, accountId));
623
624
  if (role === undefined || !canUseSlot(slot, role))
624
625
  return null;
625
626
  // a skill file's token: the current role must still read skills (the issuing route's check)
@@ -226,6 +226,7 @@ export interface OrgsTable {
226
226
  storage_purge_claimed_at: TsNullable;
227
227
  }
228
228
  export interface MembershipsTable {
229
+ checklist_dismissed: Generated<boolean>;
229
230
  org_id: string;
230
231
  account_id: string;
231
232
  role: "owner" | "admin" | "member" | "guest";
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Controller, Get, HttpCode, Inject, Post, Req, Res } from "@nestjs/common";
11
11
  import { CurrentPrincipal, Public, requireUser, SessionOnly, } from "../identity/principal.js";
12
+ import { withOrgScope } from "../infra/database/org-scope.js";
12
13
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
13
14
  import { Throttled } from "../infra/throttler/throttler.guard.js";
14
15
  import { ZBody, ZParam, ZQuery } from "../infra/validation/zod-params.js";
@@ -57,11 +58,11 @@ let DialInAuthController = class DialInAuthController {
57
58
  }
58
59
  async providers(principal, query, req, reply) {
59
60
  const p = requireUser(principal);
60
- return this.counted(req, reply, () => this.auth.providers(p, query));
61
+ return this.counted(req, reply, () => withOrgScope(query.orgId, () => this.auth.providers(p, query)));
61
62
  }
62
63
  async confirm(principal, body, req, reply) {
63
64
  const p = requireUser(principal);
64
- return this.counted(req, reply, () => this.auth.confirm(p, body));
65
+ return this.counted(req, reply, () => withOrgScope(body.orgId, () => this.auth.confirm(p, body)));
65
66
  }
66
67
  async deny(principal, body, req, reply) {
67
68
  requireUser(principal);
@@ -17,6 +17,7 @@ import { audit } from "../identity/audit.js";
17
17
  import { sha256Hex } from "../identity/hash.js";
18
18
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
19
  import { KernelDb } from "../infra/database/kernel-db.js";
20
+ import { withOrgScope } from "../infra/database/org-scope.js";
20
21
  import { TransactionHost } from "../infra/database/transaction-host.js";
21
22
  import { Transactional } from "../infra/database/transactional.decorator.js";
22
23
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
@@ -188,7 +189,7 @@ let DialInAuthService = class DialInAuthService {
188
189
  case "approved": {
189
190
  const grant = JSON.parse(r[1]);
190
191
  const dialIn = this.config.get().devices.dialIn;
191
- const [deployment, settings, device, org] = await Promise.all([
192
+ const [deployment, settings, device, org] = await withOrgScope(grant.orgId, () => Promise.all([
192
193
  readDeploymentDevicePolicy(this.db.db, this.config),
193
194
  readOrgSettings(this.db.db, grant.orgId),
194
195
  this.db.db
@@ -203,7 +204,7 @@ let DialInAuthService = class DialInAuthService {
203
204
  .where("id", "=", grant.orgId)
204
205
  // the grant's org exists: the device row it names references it
205
206
  .executeTakeFirstOrThrow(),
206
- ]);
207
+ ]));
207
208
  return {
208
209
  ...grant,
209
210
  connectUrl,
@@ -251,7 +251,6 @@ export declare class DialInGateway {
251
251
  * before the upgrade): null for an unknown or revoked credential.
252
252
  */
253
253
  admit(credential: string): Promise<DialInAdmission>;
254
- private admitted;
255
254
  /**
256
255
  * Serves one upgraded socket of a machine until it closes, speaking `protocol` (the route
257
256
  * admitted it). The credential and the provider are checked again here, with the socket paused,
@@ -283,12 +283,12 @@ class DeviceConnection {
283
283
  this.schedulePing();
284
284
  socket.on("pong", () => {
285
285
  this.missedPongs = 0;
286
- this.traffic();
286
+ this.inOrg(() => this.traffic());
287
287
  });
288
288
  socket.on("message", (data, isBinary) => {
289
289
  if (this.state === "closed")
290
290
  return;
291
- this.traffic();
291
+ this.inOrg(() => this.traffic());
292
292
  if (isBinary) {
293
293
  void this.inOrg(() => this.onBinary(data));
294
294
  return;
@@ -851,7 +851,7 @@ class DeviceConnection {
851
851
  return;
852
852
  this.accepted = undefined;
853
853
  try {
854
- const r = accepted.handler.onClose?.(this.deviceId, this.closeReason, this.info());
854
+ const r = this.inOrg(() => accepted.handler.onClose?.(this.deviceId, this.closeReason, this.info()));
855
855
  if (r instanceof Promise)
856
856
  r.catch((e) => this.gw.log.warn("device provider failed onClose", {
857
857
  deviceId: this.deviceId,
@@ -974,14 +974,11 @@ let DialInGateway = class DialInGateway {
974
974
  * before the upgrade): null for an unknown or revoked credential.
975
975
  */
976
976
  async admit(credential) {
977
- // the credential names the device and its org: looked up before any org is known
978
- return asPlatform("dial-in credential lookup", () => this.admitted(credential));
979
- }
980
- async admitted(credential) {
981
- const identity = await this.machines.authenticate(credential);
977
+ // org-filter: deployment-wide lookup of a machine credential before its org is known
978
+ const identity = await asPlatform("dial-in credential lookup", () => this.machines.authenticate(credential));
982
979
  if (identity === null)
983
980
  return null;
984
- const serving = await this.handlers.forDevice(identity.deviceId);
981
+ const serving = await withOrgScope(identity.orgId, () => this.handlers.forDevice(identity.deviceId));
985
982
  return "unavailable" in serving
986
983
  ? { identity, unavailable: serving.unavailable }
987
984
  : { identity, serving };
@@ -243,8 +243,8 @@ export declare class ExtensionHost {
243
243
  private readonly deps;
244
244
  /** 配置声明插件的部署配置最近一次判定是否合法(后台列表用;没判定过时按启动配置校验)。 */
245
245
  private readonly configValidity;
246
- /** 已告警过的「部署配置不合法」(插件名 → 说明;每个周期都会重新判定,同一说明只告警一次)。 */
247
- private readonly configWarned;
246
+ /** The last config diagnostic by plugin, including its level, to deduplicate reconcile logs. */
247
+ private readonly configReported;
248
248
  /** `<name>@<version>` whose invalid config UI hints were warned about (a log dedupe only). */
249
249
  private readonly configUiWarned;
250
250
  /**
@@ -15,7 +15,7 @@ import { EXTENSION_POINT_CARDINALITY, parseExtensionPoint, SDK_VERSION, } from "
15
15
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
- import { changedPaths, configFields, secretValues, unreachableSecrets } from "../config/fields.js";
18
+ import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
19
19
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
20
20
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
21
21
  import { kernelDb } from "../db/kernel-schema.js";
@@ -387,8 +387,8 @@ let ExtensionHost = class ExtensionHost {
387
387
  deps;
388
388
  /** 配置声明插件的部署配置最近一次判定是否合法(后台列表用;没判定过时按启动配置校验)。 */
389
389
  configValidity = new Map();
390
- /** 已告警过的「部署配置不合法」(插件名 → 说明;每个周期都会重新判定,同一说明只告警一次)。 */
391
- configWarned = new Map();
390
+ /** The last config diagnostic by plugin, including its level, to deduplicate reconcile logs. */
391
+ configReported = new Map();
392
392
  /** `<name>@<version>` whose invalid config UI hints were warned about (a log dedupe only). */
393
393
  configUiWarned = new Set();
394
394
  /**
@@ -958,6 +958,7 @@ let ExtensionHost = class ExtensionHost {
958
958
  const a = {
959
959
  manifest: c.manifest,
960
960
  source: "install",
961
+ optionalBootstrap: c.d.source === "bootstrap" && !c.d.required,
961
962
  sha256: c.d.sha256,
962
963
  entryUrl: c.entryUrl,
963
964
  migrationsDir: c.migrationsDir,
@@ -1379,20 +1380,28 @@ let ExtensionHost = class ExtensionHost {
1379
1380
  }
1380
1381
  if (schema && parsed) {
1381
1382
  if (!parsed.success) {
1382
- // 只列路径与按 issue 类型生成的说明(不用 zod 的 message:自定义消息可能拼入输入值)
1383
- const detail = toIssues(parsed.error)
1384
- .map((i) => `${i.path || "<root>"}: ${i.message}`)
1385
- .join("; ");
1386
- // 待配置(C10):配置声明与安装记录都一样,内核照常启动;配置改好后下一次 reconcile 加载
1387
- if (this.configWarned.get(name) !== detail) {
1388
- this.configWarned.set(name, detail);
1389
- this.log.warn("extension not loaded: its deployment config is missing or invalid (set it in the admin console or the startup config; it loads without a restart)", { plugin: name, source: a.source, detail });
1383
+ // Report schema paths and issue kinds only, since custom messages can expose input values.
1384
+ const issues = toIssues(parsed.error);
1385
+ const detail = issues.map((i) => `${i.path || "<root>"}: ${i.message}`).join("; ");
1386
+ const unconfigured = a.optionalBootstrap === true &&
1387
+ issues.every((issue) => {
1388
+ const value = issue.path === "" ? raw : getPath(raw, issue.path);
1389
+ return value === undefined || value === "";
1390
+ });
1391
+ const level = unconfigured ? "info" : "warn";
1392
+ const report = `${level}:${detail}`;
1393
+ if (this.configReported.get(name) !== report) {
1394
+ this.configReported.set(name, report);
1395
+ const next = "set it in Admin → Extensions or the startup config; it loads without a restart";
1396
+ this.log[level](unconfigured
1397
+ ? `optional preinstalled extension is waiting for deployment config (${next})`
1398
+ : `extension not loaded: its deployment config is missing or invalid (${next})`, { plugin: name, source: a.source, detail });
1390
1399
  }
1391
1400
  retryLater();
1392
1401
  await this.writeStatus({ ...base, state: "pending", reason: "config", detail });
1393
1402
  return undefined;
1394
1403
  }
1395
- this.configWarned.delete(name);
1404
+ this.configReported.delete(name);
1396
1405
  config = parsed.data;
1397
1406
  this.reportSecrets(schema, config);
1398
1407
  }
@@ -2034,7 +2043,7 @@ let ExtensionHost = class ExtensionHost {
2034
2043
  if (declared)
2035
2044
  this.pendingActivations.set(p.plugin, { ...declared, fatal: false });
2036
2045
  }
2037
- this.configWarned.set(p.plugin, detail);
2046
+ this.configReported.set(p.plugin, `warn:${detail}`);
2038
2047
  this.log.warn(message, { plugin: p.plugin, source: p.source, detail });
2039
2048
  await this.writeStatus({ ...p, state: "pending", reason: "config", detail });
2040
2049
  }
@@ -52,6 +52,7 @@ export interface DesiredExtension {
52
52
  sha256: string;
53
53
  version: string;
54
54
  source: "npm" | "file" | "catalog" | "bootstrap";
55
+ required: boolean;
55
56
  migratedSha: string | null;
56
57
  /**
57
58
  * Where the package bytes are kept. At startup the host loads the packages kept in PG first: the
@@ -332,6 +332,7 @@ let ExtensionInstalls = class ExtensionInstalls {
332
332
  "extension_installs.sha256",
333
333
  "extension_installs.version",
334
334
  "extension_installs.source",
335
+ "extension_installs.required",
335
336
  "extension_installs.migrated_sha",
336
337
  "extension_packages.section",
337
338
  "extension_packages.blob_store",
@@ -346,6 +347,7 @@ let ExtensionInstalls = class ExtensionInstalls {
346
347
  sha256: r.sha256,
347
348
  version: r.version,
348
349
  source: r.source,
350
+ required: r.required,
349
351
  migratedSha: r.migrated_sha,
350
352
  blobStore: r.blob_store,
351
353
  section: r.section,
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Controller, Get, HttpCode, Inject, Param, Post, Res } from "@nestjs/common";
11
11
  import { z } from "zod";
12
12
  import { CurrentPrincipal, Public, requireUser } from "../identity/principal.js";
13
+ import { bindRequestScope } from "../infra/database/org-scope.js";
13
14
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
15
  import { ZParam } from "../infra/validation/zod-params.js";
15
16
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
@@ -60,6 +61,8 @@ let HtmlDocumentController = class HtmlDocumentController {
60
61
  const claims = this.tokens.verify(token);
61
62
  if (claims === null)
62
63
  throw htmlNotFound();
64
+ if (claims.kind !== "share")
65
+ bindRequestScope({ kind: "org", orgId: claims.orgId });
63
66
  await this.documents.serve(claims, reply);
64
67
  }
65
68
  };